Add support for global constants, and for initializers for constants
[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   // Clear out method level types...
306   MethodTypeValues.clear();
307
308   // If anyone is using the placeholder make them use the real method instead
309   MethPHolder->replaceAllUsesWith(M);
310
311   // We don't need the placeholder anymore!
312   delete MethPHolder;
313
314   return false;
315 }
316
317 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
318                                           Module *C) {
319   if (!MethodSignatureList.empty()) 
320     return failure(true);  // Two ModuleGlobal blocks?
321
322   // Read global variables...
323   unsigned VarType;
324   if (read_vbr(Buf, End, VarType)) return failure(true);
325   while (VarType != Type::VoidTyID) { // List is terminated by Void
326     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2+ = slot#
327     const Type *Ty = getType(VarType >> 2);
328     if (!Ty || !Ty->isPointerType()) { 
329       cerr << "Global not pointer type!  Ty = " << Ty << endl;
330       return failure(true); 
331     }
332
333     ConstPoolVal *Initializer = 0;
334     if (VarType & 2) { // Does it have an initalizer?
335       // Do not improvise... values must have been stored in the constant pool,
336       // which should have been read before now.
337       //
338       unsigned InitSlot;
339       if (read_vbr(Buf, End, InitSlot)) return failure(true);
340       
341       Value *V = getValue(Ty->castPointerType()->getValueType(),
342                           InitSlot, false);
343       if (V == 0) return failure(true);
344       Initializer = V->castConstantAsserting();
345     }
346
347     // Create the global variable...
348     GlobalVariable *GV = new GlobalVariable(Ty, VarType & 1, Initializer);
349     insertValue(GV, ModuleValues);
350     C->getGlobalList().push_back(GV);
351
352     if (read_vbr(Buf, End, VarType)) return failure(true);
353     BCR_TRACE(2, "Global Variable of type: " << Ty->getDescription() << endl);
354   }
355
356   // Read the method signatures for all of the methods that are coming, and 
357   // create fillers in the Value tables.
358   unsigned MethSignature;
359   if (read_vbr(Buf, End, MethSignature)) return failure(true);
360   while (MethSignature != Type::VoidTyID) { // List is terminated by Void
361     const Type *Ty = getType(MethSignature);
362     if (!Ty || !Ty->isMethodType()) { 
363       cerr << "Method not meth type!  Ty = " << Ty << endl;
364       return failure(true); 
365     }
366
367     // When the ModuleGlobalInfo section is read, we load the type of each 
368     // method and the 'ModuleValues' slot that it lands in.  We then load a 
369     // placeholder into its slot to reserve it.  When the method is loaded, this
370     // placeholder is replaced.
371
372     // Insert the placeholder...
373     Value *Def = new MethPHolder(Ty, 0);
374     insertValue(Def, ModuleValues);
375
376     // Figure out which entry of its typeslot it went into...
377     unsigned TypeSlot;
378     if (getTypeSlot(Def->getType(), TypeSlot)) return failure(true);
379
380     unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
381     
382     // Keep track of this information in a linked list that is emptied as 
383     // methods are loaded...
384     //
385     MethodSignatureList.push_back(make_pair((const MethodType*)Ty, SlotNo));
386     if (read_vbr(Buf, End, MethSignature)) return failure(true);
387     BCR_TRACE(2, "Method of type: " << Ty << endl);
388   }
389
390   if (align32(Buf, End)) return failure(true);
391
392   // This is for future proofing... in the future extra fields may be added that
393   // we don't understand, so we transparently ignore them.
394   //
395   Buf = End;
396   return false;
397 }
398
399 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf, 
400                                 Module *&C) {
401
402   unsigned Type, Size;
403   if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
404   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
405     return failure(true);                      // Hrm, not a class?
406
407   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
408   MethodSignatureList.clear();                 // Just in case...
409
410   // Read into instance variables...
411   if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
412   if (align32(Buf, EndBuf)) return failure(true);
413   BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
414
415   C = new Module();
416   while (Buf < EndBuf) {
417     const uchar *OldBuf = Buf;
418     if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
419     switch (Type) {
420     case BytecodeFormat::ConstantPool:
421       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
422       if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
423         delete C; return failure(true);
424       }
425       break;
426
427     case BytecodeFormat::ModuleGlobalInfo:
428       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
429
430       if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
431         delete C; return failure(true);
432       }
433       break;
434
435     case BytecodeFormat::Method: {
436       BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
437       if (ParseMethod(Buf, Buf+Size, C)) {
438         delete C; return failure(true);               // Error parsing method
439       }
440       break;
441     }
442
443     case BytecodeFormat::SymbolTable:
444       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
445       if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
446         delete C; return failure(true);
447       }
448       break;
449
450     default:
451       cerr << "  Unknown class block: " << Type << endl;
452       Buf += Size;
453       if (OldBuf > Buf) return failure(true); // Wrap around!
454       break;
455     }
456     BCR_TRACE(1, "} end block\n");
457     if (align32(Buf, EndBuf)) { delete C; return failure(true); }
458   }
459
460   if (!MethodSignatureList.empty())      // Expected more methods!
461     return failure(true);
462
463   BCR_TRACE(0, "} end block\n\n");
464   return false;
465 }
466
467 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
468   LateResolveValues.clear();
469   unsigned Sig;
470   // Read and check signature...
471   if (read(Buf, EndBuf, Sig) ||
472       Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
473     return failure<Module*>(0);                          // Invalid signature!
474
475   Module *Result;
476   if (ParseModule(Buf, EndBuf, Result)) return 0;
477   return Result;
478 }
479
480
481 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
482   BytecodeParser Parser;
483   return Parser.ParseBytecode(Buffer, Buffer+Length);
484 }
485
486 // Parse and return a class file...
487 //
488 Module *ParseBytecodeFile(const string &Filename) {
489   struct stat StatBuf;
490   Module *Result = 0;
491
492   if (Filename != string("-")) {        // Read from a file...
493     int FD = open(Filename.c_str(), O_RDONLY);
494     if (FD == -1) return failure<Module*>(0);
495
496     if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
497
498     int Length = StatBuf.st_size;
499     if (Length == 0) { close(FD); return failure<Module*>(0); }
500     uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ, 
501                                 MAP_PRIVATE, FD, 0);
502     if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
503
504     BytecodeParser Parser;
505     Result  = Parser.ParseBytecode(Buffer, Buffer+Length);
506
507     munmap((char*)Buffer, Length);
508     close(FD);
509   } else {                              // Read from stdin
510     size_t FileSize = 0;
511     int BlockSize;
512     uchar Buffer[4096], *FileData = 0;
513     while ((BlockSize = read(0, Buffer, 4))) {
514       if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
515
516       FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
517       memcpy(FileData+FileSize, Buffer, BlockSize);
518       FileSize += BlockSize;
519     }
520
521     if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
522
523 #define ALIGN_PTRS 1
524 #if ALIGN_PTRS
525     uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE, 
526                               MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
527     assert((Buf != (uchar*)-1) && "mmap returned error!");
528     free(FileData);
529     memcpy(Buf, FileData, FileSize);
530 #else
531     uchar *Buf = FileData;
532 #endif
533
534     BytecodeParser Parser;
535     Result = Parser.ParseBytecode(Buf, Buf+FileSize);
536
537 #if ALIGN_PTRS
538     munmap((char*)Buf, FileSize);   // Free mmap'd data area
539 #else
540     free(FileData);          // Free realloc'd block of memory
541 #endif
542   }
543
544   return Result;
545 }