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