Change the ModuleProvider interface to not throw exceptions.
[oota-llvm.git] / lib / Bytecode / Reader / ReaderWrappers.cpp
1 //===- ReaderWrappers.cpp - Parse bytecode from file or buffer  -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements loading and parsing a bytecode file and parsing a
11 // bytecode module from a given buffer.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Bytecode/Analyzer.h"
16 #include "llvm/Bytecode/Reader.h"
17 #include "Reader.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/System/MappedFile.h"
22 #include "llvm/System/Program.h"
23 #include <cerrno>
24 #include <iostream>
25 #include <memory>
26
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // BytecodeFileReader - Read from an mmap'able file descriptor.
31 //
32
33 namespace {
34   /// BytecodeFileReader - parses a bytecode file from a file
35   ///
36   class BytecodeFileReader : public BytecodeReader {
37   private:
38     sys::MappedFile mapFile;
39
40     BytecodeFileReader(const BytecodeFileReader&); // Do not implement
41     void operator=(const BytecodeFileReader &BFR); // Do not implement
42
43   public:
44     BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
45   };
46 }
47
48 BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
49                                        llvm::BytecodeHandler* H )
50   : BytecodeReader(H)
51   , mapFile( sys::Path(Filename))
52 {
53   mapFile.map();
54   unsigned char* buffer = reinterpret_cast<unsigned char*>(mapFile.base());
55   ParseBytecode(buffer, mapFile.size(), Filename);
56 }
57
58 //===----------------------------------------------------------------------===//
59 // BytecodeBufferReader - Read from a memory buffer
60 //
61
62 namespace {
63   /// BytecodeBufferReader - parses a bytecode file from a buffer
64   ///
65   class BytecodeBufferReader : public BytecodeReader {
66   private:
67     const unsigned char *Buffer;
68     bool MustDelete;
69
70     BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
71     void operator=(const BytecodeBufferReader &BFR);   // Do not implement
72
73   public:
74     BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
75                          const std::string &ModuleID,
76                          llvm::BytecodeHandler* Handler = 0);
77     ~BytecodeBufferReader();
78
79   };
80 }
81
82 BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
83                                            unsigned Length,
84                                            const std::string &ModuleID,
85                                            llvm::BytecodeHandler* H )
86   : BytecodeReader(H)
87 {
88   // If not aligned, allocate a new buffer to hold the bytecode...
89   const unsigned char *ParseBegin = 0;
90   if (reinterpret_cast<uint64_t>(Buf) & 3) {
91     Buffer = new unsigned char[Length+4];
92     unsigned Offset = 4 - ((intptr_t)Buffer & 3);   // Make sure it's aligned
93     ParseBegin = Buffer + Offset;
94     memcpy((unsigned char*)ParseBegin, Buf, Length);    // Copy it over
95     MustDelete = true;
96   } else {
97     // If we don't need to copy it over, just use the caller's copy
98     ParseBegin = Buffer = Buf;
99     MustDelete = false;
100   }
101   try {
102     ParseBytecode(ParseBegin, Length, ModuleID);
103   } catch (...) {
104     if (MustDelete) delete [] Buffer;
105     throw;
106   }
107 }
108
109 BytecodeBufferReader::~BytecodeBufferReader() {
110   if (MustDelete) delete [] Buffer;
111 }
112
113 //===----------------------------------------------------------------------===//
114 //  BytecodeStdinReader - Read bytecode from Standard Input
115 //
116
117 namespace {
118   /// BytecodeStdinReader - parses a bytecode file from stdin
119   ///
120   class BytecodeStdinReader : public BytecodeReader {
121   private:
122     std::vector<unsigned char> FileData;
123     unsigned char *FileBuf;
124
125     BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
126     void operator=(const BytecodeStdinReader &BFR);  // Do not implement
127
128   public:
129     BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
130   };
131 }
132
133 BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
134   : BytecodeReader(H)
135 {
136   sys::Program::ChangeStdinToBinary();
137   char Buffer[4096*4];
138
139   // Read in all of the data from stdin, we cannot mmap stdin...
140   while (std::cin.good()) {
141     std::cin.read(Buffer, 4096*4);
142     int BlockSize = std::cin.gcount();
143     if (0 >= BlockSize)
144       break;
145     FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
146   }
147
148   if (FileData.empty())
149     throw std::string("Standard Input empty!");
150
151   FileBuf = &FileData[0];
152   ParseBytecode(FileBuf, FileData.size(), "<stdin>");
153 }
154
155 //===----------------------------------------------------------------------===//
156 // Varargs transmogrification code...
157 //
158
159 // CheckVarargs - This is used to automatically translate old-style varargs to
160 // new style varargs for backwards compatibility.
161 static ModuleProvider* CheckVarargs(ModuleProvider* MP) {
162   Module* M = MP->getModule();
163
164   // check to see if va_start takes arguements...
165   Function* F = M->getNamedFunction("llvm.va_start");
166   if(F == 0) return MP; //No varargs use, just return.
167
168   if (F->getFunctionType()->getNumParams() == 1)
169     return MP; // Modern varargs processing, just return.
170
171   // If we get to this point, we know that we have an old-style module.
172   // Materialize the whole thing to perform the rewriting.
173   if (MP->materializeModule() == 0)
174     return 0;
175
176   if(Function* F = M->getNamedFunction("llvm.va_start")) {
177     assert(F->arg_size() == 0 && "Obsolete va_start takes 0 argument!");
178
179     //foo = va_start()
180     // ->
181     //bar = alloca typeof(foo)
182     //va_start(bar)
183     //foo = load bar
184
185     const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
186     const Type* ArgTy = F->getFunctionType()->getReturnType();
187     const Type* ArgTyPtr = PointerType::get(ArgTy);
188     Function* NF = M->getOrInsertFunction("llvm.va_start",
189                                           RetTy, ArgTyPtr, (Type *)0);
190
191     for(Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E;)
192       if (CallInst* CI = dyn_cast<CallInst>(*I++)) {
193         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
194         new CallInst(NF, bar, "", CI);
195         Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
196         CI->replaceAllUsesWith(foo);
197         CI->getParent()->getInstList().erase(CI);
198       }
199     F->setName("");
200   }
201
202   if(Function* F = M->getNamedFunction("llvm.va_end")) {
203     assert(F->arg_size() == 1 && "Obsolete va_end takes 1 argument!");
204     //vaend foo
205     // ->
206     //bar = alloca 1 of typeof(foo)
207     //vaend bar
208     const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
209     const Type* ArgTy = F->getFunctionType()->getParamType(0);
210     const Type* ArgTyPtr = PointerType::get(ArgTy);
211     Function* NF = M->getOrInsertFunction("llvm.va_end",
212                                           RetTy, ArgTyPtr, (Type *)0);
213
214     for(Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E;)
215       if (CallInst* CI = dyn_cast<CallInst>(*I++)) {
216         AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
217         new StoreInst(CI->getOperand(1), bar, CI);
218         new CallInst(NF, bar, "", CI);
219         CI->getParent()->getInstList().erase(CI);
220       }
221     F->setName("");
222   }
223
224   if(Function* F = M->getNamedFunction("llvm.va_copy")) {
225     assert(F->arg_size() == 1 && "Obsolete va_copy takes 1 argument!");
226     //foo = vacopy(bar)
227     // ->
228     //a = alloca 1 of typeof(foo)
229     //b = alloca 1 of typeof(foo)
230     //store bar -> b
231     //vacopy(a, b)
232     //foo = load a
233
234     const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
235     const Type* ArgTy = F->getFunctionType()->getReturnType();
236     const Type* ArgTyPtr = PointerType::get(ArgTy);
237     Function* NF = M->getOrInsertFunction("llvm.va_copy",
238                                           RetTy, ArgTyPtr, ArgTyPtr, (Type *)0);
239
240     for(Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E;)
241       if (CallInst* CI = dyn_cast<CallInst>(*I++)) {
242         AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
243         AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
244         new StoreInst(CI->getOperand(1), b, CI);
245         new CallInst(NF, a, b, "", CI);
246         Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
247         CI->replaceAllUsesWith(foo);
248         CI->getParent()->getInstList().erase(CI);
249       }
250     F->setName("");
251   }
252   return MP;
253 }
254
255 //===----------------------------------------------------------------------===//
256 // Wrapper functions
257 //===----------------------------------------------------------------------===//
258
259 /// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
260 /// buffer
261 ModuleProvider*
262 llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
263                                       unsigned Length,
264                                       const std::string &ModuleID,
265                                       BytecodeHandler* H ) {
266   return CheckVarargs(
267      new BytecodeBufferReader(Buffer, Length, ModuleID, H));
268 }
269
270 /// ParseBytecodeBuffer - Parse a given bytecode buffer
271 ///
272 Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
273                                   const std::string &ModuleID,
274                                   std::string *ErrorStr){
275   try {
276     std::auto_ptr<ModuleProvider>
277       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
278     return AMP->releaseModule();
279   } catch (std::string &err) {
280     if (ErrorStr) *ErrorStr = err;
281     return 0;
282   }
283 }
284
285 /// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
286 ///
287 ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
288                                                 BytecodeHandler* H) {
289   if (Filename != std::string("-"))        // Read from a file...
290     return CheckVarargs(new BytecodeFileReader(Filename,H));
291   else                                     // Read from stdin
292     return CheckVarargs(new BytecodeStdinReader(H));
293 }
294
295 /// ParseBytecodeFile - Parse the given bytecode file
296 ///
297 Module *llvm::ParseBytecodeFile(const std::string &Filename,
298                                 std::string *ErrorStr) {
299   try {
300     std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
301     return AMP->releaseModule();
302   } catch (std::string &err) {
303     if (ErrorStr) *ErrorStr = err;
304     return 0;
305   }
306 }
307
308 // AnalyzeBytecodeFile - analyze one file
309 Module* llvm::AnalyzeBytecodeFile(
310   const std::string &Filename,  ///< File to analyze
311   BytecodeAnalysis& bca,        ///< Statistical output
312   std::string *ErrorStr,        ///< Error output
313   std::ostream* output          ///< Dump output
314 )
315 {
316   try {
317     BytecodeHandler* analyzerHandler =createBytecodeAnalyzerHandler(bca,output);
318     std::auto_ptr<ModuleProvider> AMP(
319       getBytecodeModuleProvider(Filename,analyzerHandler));
320     return AMP->releaseModule();
321   } catch (std::string &err) {
322     if (ErrorStr) *ErrorStr = err;
323     return 0;
324   }
325 }
326
327 // AnalyzeBytecodeBuffer - analyze a buffer
328 Module* llvm::AnalyzeBytecodeBuffer(
329   const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
330   unsigned Length,             ///< Size of the bytecode buffer
331   const std::string& ModuleID, ///< Identifier for the module
332   BytecodeAnalysis& bca,       ///< The results of the analysis
333   std::string* ErrorStr,       ///< Errors, if any.
334   std::ostream* output         ///< Dump output, if any
335 )
336 {
337   try {
338     BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
339     std::auto_ptr<ModuleProvider>
340       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
341     return AMP->releaseModule();
342   } catch (std::string &err) {
343     if (ErrorStr) *ErrorStr = err;
344     return 0;
345   }
346 }
347
348 bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
349                                          Module::LibraryListType& deplibs) {
350   try {
351     std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
352     Module* M = AMP->releaseModule();
353
354     deplibs = M->getLibraries();
355     delete M;
356     return true;
357   } catch (...) {
358     deplibs.clear();
359     return false;
360   }
361 }
362
363 static void getSymbols(Module*M, std::vector<std::string>& symbols) {
364   // Loop over global variables
365   for (Module::global_iterator GI = M->global_begin(), GE=M->global_end(); GI != GE; ++GI)
366     if (!GI->isExternal() && !GI->hasInternalLinkage())
367       if (!GI->getName().empty())
368         symbols.push_back(GI->getName());
369
370   // Loop over functions.
371   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
372     if (!FI->isExternal() && !FI->hasInternalLinkage())
373       if (!FI->getName().empty())
374         symbols.push_back(FI->getName());
375 }
376
377 // Get just the externally visible defined symbols from the bytecode
378 bool llvm::GetBytecodeSymbols(const sys::Path& fName,
379                               std::vector<std::string>& symbols) {
380   std::auto_ptr<ModuleProvider> AMP(
381       getBytecodeModuleProvider(fName.toString()));
382
383   // Get the module from the provider
384   Module* M = AMP->materializeModule();
385   if (M == 0) return false;
386
387   // Get the symbols
388   getSymbols(M, symbols);
389
390   // Done with the module
391   return true;
392 }
393
394 ModuleProvider*
395 llvm::GetBytecodeSymbols(const unsigned char*Buffer, unsigned Length,
396                          const std::string& ModuleID,
397                          std::vector<std::string>& symbols) {
398
399   ModuleProvider* MP = 0;
400   try {
401     // Get the module provider
402     MP = getBytecodeBufferModuleProvider(Buffer, Length, ModuleID);
403
404     // Get the module from the provider
405     Module* M = MP->materializeModule();
406     if (M == 0) return 0;
407
408     // Get the symbols
409     getSymbols(M, symbols);
410
411     // Done with the module. Note that ModuleProvider will delete the
412     // Module when it is deleted. Also note that its the caller's responsibility
413     // to delete the ModuleProvider.
414     return MP;
415
416   } catch (...) {
417     // We delete only the ModuleProvider here because its destructor will
418     // also delete the Module (we used materializeModule not releaseModule).
419     delete MP;
420   }
421   return 0;
422 }