Implement global variable support
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
1 //===- Reader.cpp - Code to read bytecode files -----------------------------===
2 //
3 // This library implements the functionality defined in llvm/Bytecode/Reader.h
4 //
5 // Note that this library should be as fast as possible, reentrant, and 
6 // threadsafe!!
7 //
8 // TODO: Make error message outputs be configurable depending on an option?
9 // TODO: Allow passing in an option to ignore the symbol table
10 //
11 //===------------------------------------------------------------------------===
12
13 #include "llvm/Bytecode/Reader.h"
14 #include "llvm/Bytecode/Format.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/Module.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/ConstPoolVals.h"
20 #include "llvm/iOther.h"
21 #include "ReaderInternals.h"
22 #include <sys/types.h>
23 #include <sys/mman.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <algorithm>
28
29 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
30   if (Ty->isPrimitiveType()) {
31     Slot = Ty->getPrimitiveID();
32   } else {
33     // Check the method level types first...
34     TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
35                                         MethodTypeValues.end(), Ty);
36     if (I != MethodTypeValues.end()) {
37       Slot = FirstDerivedTyID+ModuleTypeValues.size()+
38              (&*I - &MethodTypeValues[0]);
39     } else {
40       I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
41       if (I == ModuleTypeValues.end()) return true;   // Didn't find type!
42       Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
43     }
44   }
45   //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
46   return false;
47 }
48
49 const Type *BytecodeParser::getType(unsigned ID) {
50   const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
51   if (T) return T;
52   
53   //cerr << "Looking up Type ID: " << ID << endl;
54
55   const Value *D = getValue(Type::TypeTy, ID, false);
56   if (D == 0) return failure<const Type*>(0);
57
58   return D->castTypeAsserting();
59 }
60
61 bool BytecodeParser::insertValue(Value *Val, vector<ValueList> &ValueTab) {
62   unsigned type;
63   if (getTypeSlot(Val->getType(), type)) return failure(true);
64   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
65  
66   if (ValueTab.size() <= type)
67     ValueTab.resize(type+1, ValueList());
68
69   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
70   //     << "] = " << Val << endl;
71   ValueTab[type].push_back(Val);
72
73   return false;
74 }
75
76 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
77   unsigned Num = oNum;
78   unsigned type;   // The type plane it lives in...
79
80   if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
81
82   if (type == Type::TypeTyID) {  // The 'type' plane has implicit values
83     assert(Create == false);
84     const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
85     if (T) return (Value*)T;   // Asked for a primitive type...
86
87     // Otherwise, derived types need offset...
88     Num -= FirstDerivedTyID;
89
90     // Is it a module level type?
91     if (Num < ModuleTypeValues.size())
92       return (Value*)(const Type*)ModuleTypeValues[Num];
93
94     // Nope, is it a method level type?
95     Num -= ModuleTypeValues.size();
96     if (Num < MethodTypeValues.size())
97       return (Value*)(const Type*)MethodTypeValues[Num];
98
99     return 0;
100   }
101
102   if (type < ModuleValues.size()) {
103     if (Num < ModuleValues[type].size())
104       return ModuleValues[type][Num];
105     Num -= ModuleValues[type].size();
106   }
107
108   if (Values.size() > type && Values[type].size() > Num)
109     return Values[type][Num];
110
111   if (!Create) return failure<Value*>(0);  // Do not create a placeholder?
112
113   Value *d = 0;
114   switch (Ty->getPrimitiveID()) {
115   case Type::LabelTyID: d = new    BBPHolder(Ty, oNum); break;
116   case Type::MethodTyID:
117     cerr << "Creating method pholder! : " << type << ":" << oNum << " " 
118          << Ty->getName() << endl;
119     d = new MethPHolder(Ty, oNum);
120     insertValue(d, LateResolveModuleValues);
121     return d;
122   default:                   d = new   DefPHolder(Ty, oNum); break;
123   }
124
125   assert(d != 0 && "How did we not make something?");
126   if (insertValue(d, LateResolveValues)) return failure<Value*>(0);
127   return d;
128 }
129
130 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
131   bool Error = false;
132   for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
133     ValueList &DL = ValTab[ty];
134     unsigned Size;
135     while ((Size = DL.size())) {
136       unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
137
138       Value *D = DL[Size-1];
139       DL.pop_back();
140
141       Value *NewDef = getValue(D->getType(), IDNumber, false);
142       if (NewDef == 0) {
143         Error = true;  // Unresolved thinger
144         cerr << "Unresolvable reference found: <" << D->getType()->getName()
145              << ">:" << IDNumber << "!\n";
146       } else {
147         // Fixup all of the uses of this placeholder def...
148         D->replaceAllUsesWith(NewDef);
149
150         // Now that all the uses are gone, delete the placeholder...
151         // If we couldn't find a def (error case), then leak a little
152         delete D;  // memory, 'cause otherwise we can't remove all uses!
153       }
154     }
155   }
156
157   return Error;
158 }
159
160 bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf, 
161                                      BasicBlock *&BB) {
162   BB = new BasicBlock();
163
164   while (Buf < EndBuf) {
165     Instruction *Inst;
166     if (ParseInstruction(Buf, EndBuf, Inst)) {
167       delete BB;
168       return failure(true);
169     }
170
171     if (Inst == 0) { delete BB; return failure(true); }
172     if (insertValue(Inst, Values)) { delete BB; return failure(true); }
173
174     BB->getInstList().push_back(Inst);
175
176     BCR_TRACE(4, Inst);
177   }
178
179   return false;
180 }
181
182 bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
183                                       SymbolTable *ST) {
184   while (Buf < EndBuf) {
185     // Symtab block header: [num entries][type id number]
186     unsigned NumEntries, Typ;
187     if (read_vbr(Buf, EndBuf, NumEntries) ||
188         read_vbr(Buf, EndBuf, Typ)) return failure(true);
189     const Type *Ty = getType(Typ);
190     if (Ty == 0) return failure(true);
191
192     BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
193               " entries\n");
194
195     for (unsigned i = 0; i < NumEntries; ++i) {
196       // Symtab entry: [def slot #][name]
197       unsigned slot;
198       if (read_vbr(Buf, EndBuf, slot)) return failure(true);
199       string Name;
200       if (read(Buf, EndBuf, Name, false))  // Not aligned...
201         return failure(true);
202
203       Value *D = getValue(Ty, slot, false); // Find mapping...
204       if (D == 0) {
205         BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << endl);
206         return failure(true);
207       }
208       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
209                 if (!D->isInstruction()) cerr << endl);
210
211       D->setName(Name, ST);
212     }
213   }
214
215   if (Buf > EndBuf) return failure(true);
216   return false;
217 }
218
219
220 bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf, 
221                                  Module *C) {
222   // Clear out the local values table...
223   Values.clear();
224   if (MethodSignatureList.empty()) return failure(true);  // Unexpected method!
225
226   const MethodType *MTy = MethodSignatureList.front().first;
227   unsigned MethSlot = MethodSignatureList.front().second;
228   MethodSignatureList.pop_front();
229   Method *M = new Method(MTy);
230
231   BCR_TRACE(2, "METHOD TYPE: " << MTy << endl);
232
233   const MethodType::ParamTypes &Params = MTy->getParamTypes();
234   for (MethodType::ParamTypes::const_iterator It = Params.begin();
235        It != Params.end(); ++It) {
236     MethodArgument *MA = new MethodArgument(*It);
237     if (insertValue(MA, Values)) { delete M; return failure(true); }
238     M->getArgumentList().push_back(MA);
239   }
240
241   while (Buf < EndBuf) {
242     unsigned Type, Size;
243     const uchar *OldBuf = Buf;
244     if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return failure(true); }
245
246     switch (Type) {
247     case BytecodeFormat::ConstantPool:
248       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
249       if (ParseConstantPool(Buf, Buf+Size, Values, MethodTypeValues)) {
250         delete M; return failure(true);
251       }
252       break;
253
254     case BytecodeFormat::BasicBlock: {
255       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
256       BasicBlock *BB;
257       if (ParseBasicBlock(Buf, Buf+Size, BB) ||
258           insertValue(BB, Values)) {
259         delete M; return failure(true);                // Parse error... :(
260       }
261
262       M->getBasicBlocks().push_back(BB);
263       break;
264     }
265
266     case BytecodeFormat::SymbolTable:
267       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
268       if (ParseSymbolTable(Buf, Buf+Size, M->getSymbolTableSure())) {
269         delete M; return failure(true);
270       }
271       break;
272
273     default:
274       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
275       Buf += Size;
276       if (OldBuf > Buf) return failure(true); // Wrap around!
277       break;
278     }
279     BCR_TRACE(2, "} end block\n");
280
281     if (align32(Buf, EndBuf)) {
282       delete M;    // Malformed bc file, read past end of block.
283       return failure(true);
284     }
285   }
286
287   if (postResolveValues(LateResolveValues) ||
288       postResolveValues(LateResolveModuleValues)) {
289     delete M; return failure(true);     // Unresolvable references!
290   }
291
292   Value *MethPHolder = getValue(MTy, MethSlot, false);
293   assert(MethPHolder && "Something is broken no placeholder found!");
294   assert(MethPHolder->isMethod() && "Not a method?");
295
296   unsigned type;  // Type slot
297   assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
298   getTypeSlot(MTy, type);
299
300   C->getMethodList().push_back(M);
301
302   // Replace placeholder with the real method pointer...
303   ModuleValues[type][MethSlot] = M;
304
305   // If anyone is using the placeholder make them use the real method instead
306   MethPHolder->replaceAllUsesWith(M);
307
308   // We don't need the placeholder anymore!
309   delete MethPHolder;
310
311   return false;
312 }
313
314 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
315                                           Module *C) {
316   if (!MethodSignatureList.empty()) 
317     return failure(true);  // Two ModuleGlobal blocks?
318
319   // Read global variables...
320   unsigned VarType;
321   if (read_vbr(Buf, End, VarType)) return failure(true);
322   while (VarType != Type::VoidTyID) { // List is terminated by Void
323     const Type *Ty = getType(VarType);
324     if (!Ty || !Ty->isPointerType()) { 
325       cerr << "Global not pointer type!  Ty = " << Ty << endl;
326       return failure(true); 
327     }
328
329     // Create the global variable...
330     GlobalVariable *GV = new GlobalVariable(Ty);
331     insertValue(GV, ModuleValues);
332     C->getGlobalList().push_back(GV);
333
334     if (read_vbr(Buf, End, VarType)) return failure(true);
335     BCR_TRACE(2, "Global Variable of type: " << Ty->getDescription() << endl);
336   }
337
338   // Read the method signatures for all of the methods that are coming, and 
339   // create fillers in the Value tables.
340   unsigned MethSignature;
341   if (read_vbr(Buf, End, MethSignature)) return failure(true);
342   while (MethSignature != Type::VoidTyID) { // List is terminated by Void
343     const Type *Ty = getType(MethSignature);
344     if (!Ty || !Ty->isMethodType()) { 
345       cerr << "Method not meth type!  Ty = " << Ty << endl;
346       return failure(true); 
347     }
348
349     // When the ModuleGlobalInfo section is read, we load the type of each 
350     // method and the 'ModuleValues' slot that it lands in.  We then load a 
351     // placeholder into its slot to reserve it.  When the method is loaded, this
352     // placeholder is replaced.
353
354     // Insert the placeholder...
355     Value *Def = new MethPHolder(Ty, 0);
356     insertValue(Def, ModuleValues);
357
358     // Figure out which entry of its typeslot it went into...
359     unsigned TypeSlot;
360     if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
361
362     unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
363     
364     // Keep track of this information in a linked list that is emptied as 
365     // methods are loaded...
366     //
367     MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
368     if (read_vbr(Buf, End, MethSignature)) return failure(true);
369     BCR_TRACE(2, "Method of type: " << Ty << endl);
370   }
371
372   if (align32(Buf, End)) return failure(true);
373
374   // This is for future proofing... in the future extra fields may be added that
375   // we don't understand, so we transparently ignore them.
376   //
377   Buf = End;
378   return false;
379 }
380
381 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf, 
382                                 Module *&C) {
383
384   unsigned Type, Size;
385   if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
386   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
387     return failure(true);                      // Hrm, not a class?
388
389   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
390   MethodSignatureList.clear();                 // Just in case...
391
392   // Read into instance variables...
393   if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
394   if (align32(Buf, EndBuf)) return failure(true);
395   BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
396
397   C = new Module();
398   while (Buf < EndBuf) {
399     const uchar *OldBuf = Buf;
400     if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
401     switch (Type) {
402     case BytecodeFormat::ConstantPool:
403       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
404       if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
405         delete C; return failure(true);
406       }
407       break;
408
409     case BytecodeFormat::ModuleGlobalInfo:
410       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
411
412       if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
413         delete C; return failure(true);
414       }
415       break;
416
417     case BytecodeFormat::Method: {
418       BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
419       if (ParseMethod(Buf, Buf+Size, C)) {
420         delete C; return failure(true);               // Error parsing method
421       }
422       break;
423     }
424
425     case BytecodeFormat::SymbolTable:
426       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
427       if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
428         delete C; return failure(true);
429       }
430       break;
431
432     default:
433       cerr << "  Unknown class block: " << Type << endl;
434       Buf += Size;
435       if (OldBuf > Buf) return failure(true); // Wrap around!
436       break;
437     }
438     BCR_TRACE(1, "} end block\n");
439     if (align32(Buf, EndBuf)) { delete C; return failure(true); }
440   }
441
442   if (!MethodSignatureList.empty())      // Expected more methods!
443     return failure(true);
444
445   BCR_TRACE(0, "} end block\n\n");
446   return false;
447 }
448
449 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
450   LateResolveValues.clear();
451   unsigned Sig;
452   // Read and check signature...
453   if (read(Buf, EndBuf, Sig) ||
454       Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
455     return failure<Module*>(0);                          // Invalid signature!
456
457   Module *Result;
458   if (ParseModule(Buf, EndBuf, Result)) return 0;
459   return Result;
460 }
461
462
463 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
464   BytecodeParser Parser;
465   return Parser.ParseBytecode(Buffer, Buffer+Length);
466 }
467
468 // Parse and return a class file...
469 //
470 Module *ParseBytecodeFile(const string &Filename) {
471   struct stat StatBuf;
472   Module *Result = 0;
473
474   if (Filename != string("-")) {        // Read from a file...
475     int FD = open(Filename.c_str(), O_RDONLY);
476     if (FD == -1) return failure<Module*>(0);
477
478     if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
479
480     int Length = StatBuf.st_size;
481     if (Length == 0) { close(FD); return failure<Module*>(0); }
482     uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ, 
483                                 MAP_PRIVATE, FD, 0);
484     if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
485
486     BytecodeParser Parser;
487     Result  = Parser.ParseBytecode(Buffer, Buffer+Length);
488
489     munmap((char*)Buffer, Length);
490     close(FD);
491   } else {                              // Read from stdin
492     size_t FileSize = 0;
493     int BlockSize;
494     uchar Buffer[4096], *FileData = 0;
495     while ((BlockSize = read(0, Buffer, 4))) {
496       if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
497
498       FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
499       memcpy(FileData+FileSize, Buffer, BlockSize);
500       FileSize += BlockSize;
501     }
502
503     if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
504
505 #define ALIGN_PTRS 1
506 #if ALIGN_PTRS
507     uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE, 
508                               MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
509     assert((Buf != (uchar*)-1) && "mmap returned error!");
510     free(FileData);
511     memcpy(Buf, FileData, FileSize);
512 #else
513     uchar *Buf = FileData;
514 #endif
515
516     BytecodeParser Parser;
517     Result = Parser.ParseBytecode(Buf, Buf+FileSize);
518
519 #if ALIGN_PTRS
520     munmap((char*)Buf, FileSize);   // Free mmap'd data area
521 #else
522     free(FileData);          // Free realloc'd block of memory
523 #endif
524   }
525
526   return Result;
527 }