Transform two methods to return pointers directly instead of returning them
[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: Return error messages to caller instead of printing them out directly.
9 // TODO: Allow passing in an option to ignore the symbol table
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "ReaderInternals.h"
14 #include "llvm/Bytecode/Reader.h"
15 #include "llvm/Bytecode/Format.h"
16 #include "llvm/Constants.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iOther.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
21 #include "Config/unistd.h"
22 #include "Config/sys/mman.h"
23 #include "Config/sys/stat.h"
24 #include "Config/sys/types.h"
25 #include <algorithm>
26 #include <memory>
27
28 static inline void ALIGN32(const unsigned char *&begin,
29                            const unsigned char *end) {
30   if (align32(begin, end))
31     throw std::string("Alignment error in buffer: read past end of block.");
32 }
33
34 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
35   if (Ty->isPrimitiveType())
36     return Ty->getPrimitiveID();
37
38   // Check the function level types first...
39   TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
40                                       FunctionTypeValues.end(), Ty);
41   if (I != FunctionTypeValues.end())
42     return FirstDerivedTyID + ModuleTypeValues.size() +
43              (&*I - &FunctionTypeValues[0]);
44
45   I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
46   if (I == ModuleTypeValues.end())
47     throw std::string("Didn't find type in ModuleTypeValues.");
48   return FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
49 }
50
51 const Type *BytecodeParser::getType(unsigned ID) {
52   if (ID < Type::NumPrimitiveIDs) {
53     const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
54     if (T) return T;
55   }
56   
57   //cerr << "Looking up Type ID: " << ID << "\n";
58   const Value *V = getValue(Type::TypeTy, ID, false);
59   return cast_or_null<Type>(V);
60 }
61
62 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
63   assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
64           Val->getType()->isPrimitiveType() ||
65           !cast<Constant>(Val)->isNullValue()) &&
66          "Cannot read null values from bytecode!");
67   unsigned type = getTypeSlot(Val->getType());
68   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
69  
70   if (ValueTab.size() <= type) {
71     unsigned OldSize = ValueTab.size();
72     ValueTab.resize(type+1);
73     while (OldSize != type+1)
74       ValueTab[OldSize++] = new ValueList();
75   }
76
77   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
78   //   << "] = " << Val << "\n";
79   ValueTab[type]->push_back(Val);
80
81   bool HasOffset = HasImplicitZeroInitializer &&
82     !Val->getType()->isPrimitiveType();
83
84   return ValueTab[type]->size()-1 + HasOffset;
85 }
86
87
88 void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
89                                 Value *Val) {
90   assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
91   assert((!HasImplicitZeroInitializer || Slot != 0) &&
92          "Cannot change zero init");
93   unsigned type = getTypeSlot(Val->getType());
94   assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
95   ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
96 }
97
98 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
99   unsigned Num = oNum;
100   unsigned type = getTypeSlot(Ty);    // The type plane it lives in...
101
102   if (type == Type::TypeTyID) {   // The 'type' plane has implicit values
103     assert(Create == false);
104     if (Num < Type::NumPrimitiveIDs) {
105       const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
106       if (T) return (Value*)T;   // Asked for a primitive type...
107     }
108
109     // Otherwise, derived types need offset...
110     Num -= FirstDerivedTyID;
111
112     // Is it a module-level type?
113     if (Num < ModuleTypeValues.size())
114       return (Value*)ModuleTypeValues[Num].get();
115
116     // Nope, is it a function-level type?
117     Num -= ModuleTypeValues.size();
118     if (Num < FunctionTypeValues.size())
119       return (Value*)FunctionTypeValues[Num].get();
120
121     return 0;
122   }
123
124   if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
125     if (Num == 0)
126       return Constant::getNullValue(Ty);
127     --Num;
128   }
129
130   if (type < ModuleValues.size()) {
131     if (Num < ModuleValues[type]->size())
132       return ModuleValues[type]->getOperand(Num);
133     Num -= ModuleValues[type]->size();
134   }
135
136   if (Values.size() > type && Values[type]->size() > Num)
137     return Values[type]->getOperand(Num);
138
139   if (!Create) return 0;  // Do not create a placeholder?
140
141   Value *d = 0;
142   switch (Ty->getPrimitiveID()) {
143   case Type::LabelTyID:
144     d = new BBPHolder(Ty, oNum);
145     break;
146   default:
147     d = new ValPHolder(Ty, oNum);
148     break;
149   }
150
151   assert(d != 0 && "How did we not make something?");
152   if (insertValue(d, LateResolveValues) == -1) return 0;
153   return d;
154 }
155
156 /// getConstantValue - Just like getValue, except that it returns a null pointer
157 /// only on error.  It always returns a constant (meaning that if the value is
158 /// defined, but is not a constant, that is an error).  If the specified
159 /// constant hasn't been parsed yet, a placeholder is defined and used.  Later,
160 /// after the real value is parsed, the placeholder is eliminated.
161 ///
162 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
163   if (Value *V = getValue(Ty, Slot, false))
164     return dyn_cast<Constant>(V);      // If we already have the value parsed...
165
166   std::pair<const Type*, unsigned> Key(Ty, Slot);
167   GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
168
169   if (I != GlobalRefs.end() && I->first == Key) {
170     BCR_TRACE(5, "Previous forward ref found!\n");
171     return cast<Constant>(I->second);
172   } else {
173     // Create a placeholder for the constant reference and
174     // keep track of the fact that we have a forward ref to recycle it
175     BCR_TRACE(5, "Creating new forward ref to a constant!\n");
176     Constant *C = new ConstPHolder(Ty, Slot);
177     
178     // Keep track of the fact that we have a forward ref to recycle it
179     GlobalRefs.insert(I, std::make_pair(Key, C));
180     return C;
181   }
182 }
183
184
185 void BytecodeParser::postResolveValues(ValueTable &ValTab) {
186   while (!ValTab.empty()) {
187     ValueList &VL = *ValTab.back();
188     ValTab.pop_back();    
189
190     while (!VL.empty()) {
191       Value *V = VL.back();
192       unsigned IDNumber = getValueIDNumberFromPlaceHolder(V);
193       VL.pop_back();
194
195       Value *NewVal = getValue(V->getType(), IDNumber, false);
196       if (NewVal == 0)
197         throw std::string("Unresolvable reference found: <" +
198                           V->getType()->getDescription() + ">:" + 
199                           utostr(IDNumber) + ".");
200
201       // Fixup all of the uses of this placeholder def...
202       V->replaceAllUsesWith(NewVal);
203       
204       // Now that all the uses are gone, delete the placeholder...
205       // If we couldn't find a def (error case), then leak a little
206       delete V;  // memory, 'cause otherwise we can't remove all uses!
207     }
208     delete &VL;
209   }
210 }
211
212 std::auto_ptr<BasicBlock>
213 BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
214                                 const unsigned char *EndBuf) {
215   std::auto_ptr<BasicBlock> BB(new BasicBlock());
216
217   while (Buf < EndBuf) {
218     Instruction *Inst;
219     ParseInstruction(Buf, EndBuf, Inst);
220
221     if (Inst == 0) { throw std::string("Could not parse Instruction."); }
222     if (insertValue(Inst, Values) == -1) { 
223       throw std::string("Could not insert value.");
224     }
225
226     BB->getInstList().push_back(Inst);
227     BCR_TRACE(4, Inst);
228   }
229
230   return BB;
231 }
232
233 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
234                                       const unsigned char *EndBuf,
235                                       SymbolTable *ST) {
236   while (Buf < EndBuf) {
237     // Symtab block header: [num entries][type id number]
238     unsigned NumEntries, Typ;
239     if (read_vbr(Buf, EndBuf, NumEntries) ||
240         read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
241     const Type *Ty = getType(Typ);
242     if (Ty == 0) throw std::string("Invalid type read in symbol table.");
243
244     BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
245                  " entries\n");
246
247     for (unsigned i = 0; i < NumEntries; ++i) {
248       // Symtab entry: [def slot #][name]
249       unsigned slot;
250       if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
251       std::string Name;
252       if (read(Buf, EndBuf, Name, false))  // Not aligned...
253         throw std::string("Buffer not aligned.");
254
255       Value *V = getValue(Ty, slot, false); // Find mapping...
256       if (V == 0) {
257         BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
258         throw std::string("Failed value look-up.");
259       }
260       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
261                 if (!isa<Instruction>(V)) std::cerr << "\n");
262
263       V->setName(Name, ST);
264     }
265   }
266
267   if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
268 }
269
270 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
271   GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
272                                                               Slot));
273   if (I == GlobalRefs.end()) return;   // Never forward referenced?
274
275   BCR_TRACE(3, "Mutating forward refs!\n");
276   Value *VPH = I->second;   // Get the placeholder...
277
278   VPH->replaceAllUsesWith(NewV);
279
280   // If this is a global variable being resolved, remove the placeholder from
281   // the module...
282   if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
283     GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
284
285   delete VPH;                         // Delete the old placeholder
286   GlobalRefs.erase(I);                // Remove the map entry for it
287 }
288
289 void
290 BytecodeParser::ParseFunction(const unsigned char *&Buf,
291                               const unsigned char *EndBuf) {
292   if (FunctionSignatureList.empty())
293     throw std::string("FunctionSignatureList empty!");
294
295   Function *F = FunctionSignatureList.back().first;
296   unsigned FunctionSlot = FunctionSignatureList.back().second;
297   FunctionSignatureList.pop_back();
298
299   // Save the information for future reading of the function
300   LazyFunctionInfo *LFI = new LazyFunctionInfo();
301   LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
302   LazyFunctionLoadMap[F] = LFI;
303   // Pretend we've `parsed' this function
304   Buf = EndBuf;
305 }
306
307 void BytecodeParser::materializeFunction(Function* F) {
308   // Find {start, end} pointers and slot in the map. If not there, we're done.
309   std::map<Function*, LazyFunctionInfo*>::iterator Fi =
310     LazyFunctionLoadMap.find(F);
311   if (Fi == LazyFunctionLoadMap.end()) return;
312   
313   LazyFunctionInfo *LFI = Fi->second;
314   const unsigned char *Buf = LFI->Buf;
315   const unsigned char *EndBuf = LFI->EndBuf;
316   unsigned FunctionSlot = LFI->FunctionSlot;
317   LazyFunctionLoadMap.erase(Fi);
318   delete LFI;
319
320   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
321
322   if (!hasInternalMarkerOnly) {
323     unsigned LinkageType;
324     if (read_vbr(Buf, EndBuf, LinkageType)) 
325       throw std::string("ParseFunction: Error reading from buffer.");
326     if (LinkageType & ~0x3) 
327       throw std::string("Invalid linkage type for Function.");
328     Linkage = (GlobalValue::LinkageTypes)LinkageType;
329   } else {
330     // We used to only support two linkage models: internal and external
331     unsigned isInternal;
332     if (read_vbr(Buf, EndBuf, isInternal)) 
333       throw std::string("ParseFunction: Error reading from buffer.");
334     if (isInternal) Linkage = GlobalValue::InternalLinkage;
335   }
336
337   F->setLinkage(Linkage);
338
339   const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
340   Function::aiterator AI = F->abegin();
341   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
342        It != Params.end(); ++It, ++AI) {
343     if (insertValue(AI, Values) == -1)
344       throw std::string("Error reading function arguments!");
345   }
346
347   while (Buf < EndBuf) {
348     unsigned Type, Size;
349     const unsigned char *OldBuf = Buf;
350     readBlock(Buf, EndBuf, Type, Size);
351
352     switch (Type) {
353     case BytecodeFormat::ConstantPool: {
354       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
355       ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
356       break;
357     }
358
359     case BytecodeFormat::BasicBlock: {
360       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
361       std::auto_ptr<BasicBlock> BB = ParseBasicBlock(Buf, Buf+Size);
362       if (!BB.get() || insertValue(BB.get(), Values) == -1)
363         throw std::string("Parse error: BasicBlock");
364
365       F->getBasicBlockList().push_back(BB.release());
366       break;
367     }
368
369     case BytecodeFormat::SymbolTable: {
370       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
371       ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable());
372       break;
373     }
374
375     default:
376       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
377       Buf += Size;
378       if (OldBuf > Buf) 
379         throw std::string("Wrapped around reading bytecode.");
380       break;
381     }
382     BCR_TRACE(2, "} end block\n");
383
384     // Malformed bc file if read past end of block.
385     ALIGN32(Buf, EndBuf);
386   }
387
388   // Check for unresolvable references
389   postResolveValues(LateResolveValues);
390
391   //ResolveReferencesToValue(F, FunctionSlot);
392
393   // Clear out function-level types...
394   FunctionTypeValues.clear();
395
396   freeTable(Values);
397 }
398
399 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
400                                            const unsigned char *End) {
401   if (!FunctionSignatureList.empty())
402     throw std::string("Two ModuleGlobalInfo packets found!");
403
404   // Read global variables...
405   unsigned VarType;
406   if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
407   while (VarType != Type::VoidTyID) { // List is terminated by Void
408     unsigned SlotNo;
409     GlobalValue::LinkageTypes Linkage;
410
411     if (!hasInternalMarkerOnly) {
412       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
413       // bit2,3 = Linkage, bit4+ = slot#
414       SlotNo = VarType >> 4;
415       Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
416     } else {
417       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
418       // bit2 = isInternal, bit3+ = slot#
419       SlotNo = VarType >> 3;
420       Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
421         GlobalValue::ExternalLinkage;
422     }
423
424     const Type *Ty = getType(SlotNo);
425     if (!Ty || !isa<PointerType>(Ty))
426       throw std::string("Global not pointer type!  Ty = " + 
427                         Ty->getDescription());
428
429     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
430
431     // Create the global variable...
432     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
433                                             0, "", TheModule);
434     int DestSlot = insertValue(GV, ModuleValues);
435     if (DestSlot == -1) throw Error_DestSlot;
436     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
437     ResolveReferencesToValue(GV, (unsigned)DestSlot);
438
439     if (VarType & 2) { // Does it have an initializer?
440       unsigned InitSlot;
441       if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
442       GlobalInits.push_back(std::make_pair(GV, InitSlot));
443     }
444     if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
445   }
446
447   // Read the function objects for all of the functions that are coming
448   unsigned FnSignature;
449   if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
450   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
451     const Type *Ty = getType(FnSignature);
452     if (!Ty || !isa<PointerType>(Ty) ||
453         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) { 
454       throw std::string("Function not ptr to func type!  Ty = " +
455                         Ty->getDescription());
456     }
457
458     // We create functions by passing the underlying FunctionType to create...
459     Ty = cast<PointerType>(Ty)->getElementType();
460
461     // When the ModuleGlobalInfo section is read, we load the type of each
462     // function and the 'ModuleValues' slot that it lands in.  We then load a
463     // placeholder into its slot to reserve it.  When the function is loaded,
464     // this placeholder is replaced.
465
466     // Insert the placeholder...
467     Function *Func = new Function(cast<FunctionType>(Ty),
468                                   GlobalValue::InternalLinkage, "", TheModule);
469     int DestSlot = insertValue(Func, ModuleValues);
470     if (DestSlot == -1) throw Error_DestSlot;
471     ResolveReferencesToValue(Func, (unsigned)DestSlot);
472
473     // Keep track of this information in a list that is emptied as functions are
474     // loaded...
475     //
476     FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
477
478     if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
479     BCR_TRACE(2, "Function of type: " << Ty << "\n");
480   }
481
482   ALIGN32(Buf, End);
483
484   // Now that the function signature list is set up, reverse it so that we can 
485   // remove elements efficiently from the back of the vector.
486   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
487
488   // This is for future proofing... in the future extra fields may be added that
489   // we don't understand, so we transparently ignore them.
490   //
491   Buf = End;
492 }
493
494 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
495                                       const unsigned char *EndBuf) {
496   unsigned Version;
497   if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
498
499   // Unpack version number: low four bits are for flags, top bits = version
500   Module::Endianness  Endianness;
501   Module::PointerSize PointerSize;
502   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
503   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
504
505   bool hasNoEndianness = Version & 4;
506   bool hasNoPointerSize = Version & 8;
507   
508   RevisionNum = Version >> 4;
509
510   // Default values for the current bytecode version
511   HasImplicitZeroInitializer = true;
512   hasInternalMarkerOnly = false;
513   FirstDerivedTyID = 14;
514
515   switch (RevisionNum) {
516   case 0:                  // Initial revision
517     // Version #0 didn't have any of the flags stored correctly, and in fact as
518     // only valid with a 14 in the flags values.  Also, it does not support
519     // encoding zero initializers for arrays compactly.
520     //
521     if (Version != 14) throw std::string("Unknown revision 0 flags?");
522     HasImplicitZeroInitializer = false;
523     Endianness  = Module::BigEndian;
524     PointerSize = Module::Pointer64;
525     hasInternalMarkerOnly = true;
526     hasNoEndianness = hasNoPointerSize = false;
527     break;
528   case 1:
529     // Version #1 has four bit fields: isBigEndian, hasLongPointers,
530     // hasNoEndianness, and hasNoPointerSize.
531     hasInternalMarkerOnly = true;
532     break;
533   case 2:
534     // Version #2 added information about all 4 linkage types instead of just
535     // having internal and external.
536     break;
537   default:
538     throw std::string("Unknown bytecode version number!");
539   }
540
541   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
542   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
543
544   TheModule->setEndianness(Endianness);
545   TheModule->setPointerSize(PointerSize);
546   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
547   BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
548                << PointerSize << "\n");
549   BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
550 }
551
552 void BytecodeParser::ParseModule(const unsigned char *Buf,
553                                  const unsigned char *EndBuf) {
554   unsigned Type, Size;
555   readBlock(Buf, EndBuf, Type, Size);
556   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
557     throw std::string("Expected Module packet! B: "+
558         utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
559         " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
560
561   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
562   FunctionSignatureList.clear();                 // Just in case...
563
564   // Read into instance variables...
565   ParseVersionInfo(Buf, EndBuf);
566   ALIGN32(Buf, EndBuf);
567
568   while (Buf < EndBuf) {
569     const unsigned char *OldBuf = Buf;
570     readBlock(Buf, EndBuf, Type, Size);
571     switch (Type) {
572     case BytecodeFormat::GlobalTypePlane:
573       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
574       ParseGlobalTypes(Buf, Buf+Size);
575       break;
576
577     case BytecodeFormat::ModuleGlobalInfo:
578       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
579       ParseModuleGlobalInfo(Buf, Buf+Size);
580       break;
581
582     case BytecodeFormat::ConstantPool:
583       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
584       ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
585       break;
586
587     case BytecodeFormat::Function: {
588       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
589       ParseFunction(Buf, Buf+Size);
590       break;
591     }
592
593     case BytecodeFormat::SymbolTable:
594       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
595       ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable());
596       break;
597
598     default:
599       Buf += Size;
600       if (OldBuf > Buf) throw std::string("Expected Module Block!");
601       break;
602     }
603     BCR_TRACE(1, "} end block\n");
604     ALIGN32(Buf, EndBuf);
605   }
606
607   // After the module constant pool has been read, we can safely initialize
608   // global variables...
609   while (!GlobalInits.empty()) {
610     GlobalVariable *GV = GlobalInits.back().first;
611     unsigned Slot = GlobalInits.back().second;
612     GlobalInits.pop_back();
613
614     // Look up the initializer value...
615     if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
616       if (GV->hasInitializer()) 
617         throw std::string("Global *already* has an initializer?!");
618       GV->setInitializer(cast<Constant>(V));
619     } else
620       throw std::string("Cannot find initializer value.");
621   }
622
623   if (!FunctionSignatureList.empty())
624     throw std::string("Function expected, but bytecode stream ended!");
625
626   BCR_TRACE(0, "} end block\n\n");
627 }
628
629 void
630 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
631                               const std::string &ModuleID) {
632
633   unsigned char *EndBuf = (unsigned char*)(Buf + Length);
634
635   // Read and check signature...
636   unsigned Sig;
637   if (read(Buf, EndBuf, Sig) ||
638       Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
639     throw std::string("Invalid bytecode signature!");
640
641   TheModule = new Module(ModuleID);
642   try { 
643     ParseModule(Buf, EndBuf);
644   } catch (std::string &Error) {
645     freeState();       // Must destroy handles before deleting module!
646     delete TheModule;
647     TheModule = 0;
648     throw;
649   }
650 }