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