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