Changes For Bug 352
[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/Support/FileUtilities.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Config/unistd.h"
23 #include <cerrno>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // BytecodeFileReader - Read from an mmap'able file descriptor.
28 //
29
30 namespace {
31   /// BytecodeFileReader - parses a bytecode file from a file
32   ///
33   class BytecodeFileReader : public BytecodeReader {
34   private:
35     unsigned char *Buffer;
36     unsigned Length;
37
38     BytecodeFileReader(const BytecodeFileReader&); // Do not implement
39     void operator=(const BytecodeFileReader &BFR); // Do not implement
40
41   public:
42     BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
43     ~BytecodeFileReader();
44   };
45 }
46
47 static std::string ErrnoMessage (int savedErrNum, std::string descr) {
48    return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
49 }
50
51 BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
52                                        llvm::BytecodeHandler* H ) 
53   : BytecodeReader(H)
54 {
55   Buffer = (unsigned char*)ReadFileIntoAddressSpace(Filename, Length);
56   if (Buffer == 0)
57     throw "Error reading file '" + Filename + "'.";
58
59   try {
60     // Parse the bytecode we mmapped in
61     ParseBytecode(Buffer, Length, Filename);
62   } catch (...) {
63     UnmapFileFromAddressSpace(Buffer, Length);
64     throw;
65   }
66 }
67
68 BytecodeFileReader::~BytecodeFileReader() {
69   // Unmmap the bytecode...
70   UnmapFileFromAddressSpace(Buffer, Length);
71 }
72
73 //===----------------------------------------------------------------------===//
74 // BytecodeBufferReader - Read from a memory buffer
75 //
76
77 namespace {
78   /// BytecodeBufferReader - parses a bytecode file from a buffer
79   ///
80   class BytecodeBufferReader : public BytecodeReader {
81   private:
82     const unsigned char *Buffer;
83     bool MustDelete;
84
85     BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
86     void operator=(const BytecodeBufferReader &BFR);   // Do not implement
87
88   public:
89     BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
90                          const std::string &ModuleID,
91                          llvm::BytecodeHandler* Handler = 0);
92     ~BytecodeBufferReader();
93
94   };
95 }
96
97 BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
98                                            unsigned Length,
99                                            const std::string &ModuleID,
100                                            llvm::BytecodeHandler* H )
101   : BytecodeReader(H)
102 {
103   // If not aligned, allocate a new buffer to hold the bytecode...
104   const unsigned char *ParseBegin = 0;
105   if (reinterpret_cast<uint64_t>(Buf) & 3) {
106     Buffer = new unsigned char[Length+4];
107     unsigned Offset = 4 - ((intptr_t)Buffer & 3);   // Make sure it's aligned
108     ParseBegin = Buffer + Offset;
109     memcpy((unsigned char*)ParseBegin, Buf, Length);    // Copy it over
110     MustDelete = true;
111   } else {
112     // If we don't need to copy it over, just use the caller's copy
113     ParseBegin = Buffer = Buf;
114     MustDelete = false;
115   }
116   try {
117     ParseBytecode(ParseBegin, Length, ModuleID);
118   } catch (...) {
119     if (MustDelete) delete [] Buffer;
120     throw;
121   }
122 }
123
124 BytecodeBufferReader::~BytecodeBufferReader() {
125   if (MustDelete) delete [] Buffer;
126 }
127
128 //===----------------------------------------------------------------------===//
129 //  BytecodeStdinReader - Read bytecode from Standard Input
130 //
131
132 namespace {
133   /// BytecodeStdinReader - parses a bytecode file from stdin
134   /// 
135   class BytecodeStdinReader : public BytecodeReader {
136   private:
137     std::vector<unsigned char> FileData;
138     unsigned char *FileBuf;
139
140     BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
141     void operator=(const BytecodeStdinReader &BFR);  // Do not implement
142
143   public:
144     BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
145   };
146 }
147
148 BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H ) 
149   : BytecodeReader(H)
150 {
151   int BlockSize;
152   unsigned char Buffer[4096*4];
153
154   // Read in all of the data from stdin, we cannot mmap stdin...
155   while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
156     if (BlockSize == -1)
157       throw ErrnoMessage(errno, "read from standard input");
158     
159     FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
160   }
161
162   if (FileData.empty())
163     throw std::string("Standard Input empty!");
164
165   FileBuf = &FileData[0];
166   ParseBytecode(FileBuf, FileData.size(), "<stdin>");
167 }
168
169 //===----------------------------------------------------------------------===//
170 //  Varargs transmogrification code...
171 //
172
173 // CheckVarargs - This is used to automatically translate old-style varargs to
174 // new style varargs for backwards compatibility.
175 static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
176   Module *M = MP->getModule();
177   
178   // Check to see if va_start takes arguments...
179   Function *F = M->getNamedFunction("llvm.va_start");
180   if (F == 0) return MP;  // No varargs use, just return.
181
182   if (F->getFunctionType()->getNumParams() == 0)
183     return MP;  // Modern varargs processing, just return.
184
185   // If we get to this point, we know that we have an old-style module.
186   // Materialize the whole thing to perform the rewriting.
187   MP->materializeModule();
188
189   // If the user is making use of obsolete varargs intrinsics, adjust them for
190   // the user.
191   if (Function *F = M->getNamedFunction("llvm.va_start")) {
192     assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
193         
194     const Type *RetTy = F->getFunctionType()->getParamType(0);
195     RetTy = cast<PointerType>(RetTy)->getElementType();
196     Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
197         
198     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
199       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
200         Value *V = new CallInst(NF, "", CI);
201         new StoreInst(V, CI->getOperand(1), CI);
202         CI->getParent()->getInstList().erase(CI);
203       }
204     F->setName("");
205   }
206
207   if (Function *F = M->getNamedFunction("llvm.va_end")) {
208     assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
209     const Type *ArgTy = F->getFunctionType()->getParamType(0);
210     ArgTy = cast<PointerType>(ArgTy)->getElementType();
211     Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
212                                                   ArgTy, 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         Value *V = new LoadInst(CI->getOperand(1), "", CI);
217         new CallInst(NF, V, "", CI);
218         CI->getParent()->getInstList().erase(CI);
219       }
220     F->setName("");
221   }
222       
223   if (Function *F = M->getNamedFunction("llvm.va_copy")) {
224     assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
225     const Type *ArgTy = F->getFunctionType()->getParamType(0);
226     ArgTy = cast<PointerType>(ArgTy)->getElementType();
227     Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
228                                                   ArgTy, 0);
229         
230     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
231       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
232         Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
233         new StoreInst(V, CI->getOperand(1), CI);
234         CI->getParent()->getInstList().erase(CI);
235       }
236     F->setName("");
237   }
238   return MP;
239 }
240
241 //===----------------------------------------------------------------------===//
242 // Wrapper functions
243 //===----------------------------------------------------------------------===//
244
245 /// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
246 /// buffer
247 ModuleProvider* 
248 llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
249                                       unsigned Length,
250                                       const std::string &ModuleID,
251                                       BytecodeHandler* H ) {
252   return CheckVarargs(
253       new BytecodeBufferReader(Buffer, Length, ModuleID, H));
254 }
255
256 /// ParseBytecodeBuffer - Parse a given bytecode buffer
257 ///
258 Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
259                                   const std::string &ModuleID,
260                                   std::string *ErrorStr){
261   try {
262     std::auto_ptr<ModuleProvider>
263       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
264     return AMP->releaseModule();
265   } catch (std::string &err) {
266     if (ErrorStr) *ErrorStr = err;
267     return 0;
268   }
269 }
270
271 /// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
272 ///
273 ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
274                                                 BytecodeHandler* H) {
275   if (Filename != std::string("-"))        // Read from a file...
276     return CheckVarargs(new BytecodeFileReader(Filename,H));
277   else                                     // Read from stdin
278     return CheckVarargs(new BytecodeStdinReader(H));
279 }
280
281 /// ParseBytecodeFile - Parse the given bytecode file
282 ///
283 Module *llvm::ParseBytecodeFile(const std::string &Filename,
284                                 std::string *ErrorStr) {
285   try {
286     std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
287     return AMP->releaseModule();
288   } catch (std::string &err) {
289     if (ErrorStr) *ErrorStr = err;
290     return 0;
291   }
292 }
293
294 // AnalyzeBytecodeFile - analyze one file
295 Module* llvm::AnalyzeBytecodeFile(
296   const std::string &Filename,  ///< File to analyze
297   BytecodeAnalysis& bca,        ///< Statistical output
298   std::string *ErrorStr,        ///< Error output
299   std::ostream* output          ///< Dump output
300
301 {
302   try {
303     BytecodeHandler* analyzerHandler = createBytecodeAnalyzerHandler(bca,output);
304     std::auto_ptr<ModuleProvider> AMP(
305       getBytecodeModuleProvider(Filename,analyzerHandler));
306     return AMP->releaseModule();
307   } catch (std::string &err) {
308     if (ErrorStr) *ErrorStr = err;
309     return 0;
310   }
311 }
312
313 // AnalyzeBytecodeBuffer - analyze a buffer
314 Module* llvm::AnalyzeBytecodeBuffer(
315   const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
316   unsigned Length,             ///< Size of the bytecode buffer
317   const std::string& ModuleID, ///< Identifier for the module
318   BytecodeAnalysis& bca,       ///< The results of the analysis
319   std::string* ErrorStr,       ///< Errors, if any.
320   std::ostream* output         ///< Dump output, if any
321
322 {
323   try {
324     BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
325     std::auto_ptr<ModuleProvider>
326       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
327     return AMP->releaseModule();
328   } catch (std::string &err) {
329     if (ErrorStr) *ErrorStr = err;
330     return 0;
331   }
332 }
333
334 bool llvm::GetBytecodeDependentLibraries(const std::string &fname, 
335                                          std::vector<std::string>& deplibs) {
336   try {
337     std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
338     Module* M = AMP->releaseModule();
339     deplibs = M->getLibraries();
340     delete M;
341     return true;
342   } catch (...) {
343     deplibs.clear();
344     return false;
345   }
346 }
347
348 // vim: sw=2 ai