Provide more information in the error message that occurs when there are
[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 "Reader.h"
20 #include "llvm/Bytecode/BytecodeHandler.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/SymbolTable.h"
25 #include "llvm/Bytecode/Format.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/Compressor.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include <sstream>
30 #include <algorithm>
31 using namespace llvm;
32
33 namespace {
34
35 /// @brief A class for maintaining the slot number definition
36 /// as a placeholder for the actual definition for forward constants defs.
37 class ConstantPlaceHolder : public ConstantExpr {
38   unsigned ID;
39   ConstantPlaceHolder();                       // DO NOT IMPLEMENT
40   void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
41 public:
42   ConstantPlaceHolder(const Type *Ty, unsigned id) 
43     : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty),
44     ID(id) {}
45   unsigned getID() { return ID; }
46 };
47
48 }
49
50 // Provide some details on error
51 inline void BytecodeReader::error(std::string err) {
52   err +=  " (Vers=" ;
53   err += itostr(RevisionNum) ;
54   err += ", Pos=" ;
55   err += itostr(At-MemStart);
56   err += ")";
57   throw err;
58 }
59
60 //===----------------------------------------------------------------------===//
61 // Bytecode Reading Methods
62 //===----------------------------------------------------------------------===//
63
64 /// Determine if the current block being read contains any more data.
65 inline bool BytecodeReader::moreInBlock() {
66   return At < BlockEnd;
67 }
68
69 /// Throw an error if we've read past the end of the current block
70 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
71   if (At > BlockEnd)
72     error(std::string("Attempt to read past the end of ") + block_name +
73           " block.");
74 }
75
76 /// Align the buffer position to a 32 bit boundary
77 inline void BytecodeReader::align32() {
78   if (hasAlignment) {
79     BufPtr Save = At;
80     At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
81     if (At > Save) 
82       if (Handler) Handler->handleAlignment(At - Save);
83     if (At > BlockEnd) 
84       error("Ran out of data while aligning!");
85   }
86 }
87
88 /// Read a whole unsigned integer
89 inline unsigned BytecodeReader::read_uint() {
90   if (At+4 > BlockEnd) 
91     error("Ran out of data reading uint!");
92   At += 4;
93   return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
94 }
95
96 /// Read a variable-bit-rate encoded unsigned integer
97 inline unsigned BytecodeReader::read_vbr_uint() {
98   unsigned Shift = 0;
99   unsigned Result = 0;
100   BufPtr Save = At;
101   
102   do {
103     if (At == BlockEnd) 
104       error("Ran out of data reading vbr_uint!");
105     Result |= (unsigned)((*At++) & 0x7F) << Shift;
106     Shift += 7;
107   } while (At[-1] & 0x80);
108   if (Handler) Handler->handleVBR32(At-Save);
109   return Result;
110 }
111
112 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
113 inline uint64_t BytecodeReader::read_vbr_uint64() {
114   unsigned Shift = 0;
115   uint64_t Result = 0;
116   BufPtr Save = At;
117   
118   do {
119     if (At == BlockEnd) 
120       error("Ran out of data reading vbr_uint64!");
121     Result |= (uint64_t)((*At++) & 0x7F) << Shift;
122     Shift += 7;
123   } while (At[-1] & 0x80);
124   if (Handler) Handler->handleVBR64(At-Save);
125   return Result;
126 }
127
128 /// Read a variable-bit-rate encoded signed 64-bit integer.
129 inline int64_t BytecodeReader::read_vbr_int64() {
130   uint64_t R = read_vbr_uint64();
131   if (R & 1) {
132     if (R != 1)
133       return -(int64_t)(R >> 1);
134     else   // There is no such thing as -0 with integers.  "-0" really means
135            // 0x8000000000000000.
136       return 1LL << 63;
137   } else
138     return  (int64_t)(R >> 1);
139 }
140
141 /// Read a pascal-style string (length followed by text)
142 inline std::string BytecodeReader::read_str() {
143   unsigned Size = read_vbr_uint();
144   const unsigned char *OldAt = At;
145   At += Size;
146   if (At > BlockEnd)             // Size invalid?
147     error("Ran out of data reading a string!");
148   return std::string((char*)OldAt, Size);
149 }
150
151 /// Read an arbitrary block of data
152 inline void BytecodeReader::read_data(void *Ptr, void *End) {
153   unsigned char *Start = (unsigned char *)Ptr;
154   unsigned Amount = (unsigned char *)End - Start;
155   if (At+Amount > BlockEnd) 
156     error("Ran out of data!");
157   std::copy(At, At+Amount, Start);
158   At += Amount;
159 }
160
161 /// Read a float value in little-endian order
162 inline void BytecodeReader::read_float(float& FloatVal) {
163   /// FIXME: This isn't optimal, it has size problems on some platforms
164   /// where FP is not IEEE.
165   union {
166     float f;
167     uint32_t i;
168   } FloatUnion;
169   FloatUnion.i = At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24);
170   At+=sizeof(uint32_t);
171   FloatVal = FloatUnion.f;
172 }
173
174 /// Read a double value in little-endian order
175 inline void BytecodeReader::read_double(double& DoubleVal) {
176   /// FIXME: This isn't optimal, it has size problems on some platforms
177   /// where FP is not IEEE.
178   union {
179     double d;
180     uint64_t i;
181   } DoubleUnion;
182   DoubleUnion.i = (uint64_t(At[0]) <<  0) | (uint64_t(At[1]) << 8) | 
183                   (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
184                   (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) | 
185                   (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56);
186   At+=sizeof(uint64_t);
187   DoubleVal = DoubleUnion.d;
188 }
189
190 /// Read a block header and obtain its type and size
191 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
192   if ( hasLongBlockHeaders ) {
193     Type = read_uint();
194     Size = read_uint();
195     switch (Type) {
196     case BytecodeFormat::Reserved_DoNotUse : 
197       error("Reserved_DoNotUse used as Module Type?");
198       Type = BytecodeFormat::ModuleBlockID; break;
199     case BytecodeFormat::Module: 
200       Type = BytecodeFormat::ModuleBlockID; break;
201     case BytecodeFormat::Function:
202       Type = BytecodeFormat::FunctionBlockID; break;
203     case BytecodeFormat::ConstantPool:
204       Type = BytecodeFormat::ConstantPoolBlockID; break;
205     case BytecodeFormat::SymbolTable:
206       Type = BytecodeFormat::SymbolTableBlockID; break;
207     case BytecodeFormat::ModuleGlobalInfo:
208       Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
209     case BytecodeFormat::GlobalTypePlane:
210       Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
211     case BytecodeFormat::InstructionList:
212       Type = BytecodeFormat::InstructionListBlockID; break;
213     case BytecodeFormat::CompactionTable:
214       Type = BytecodeFormat::CompactionTableBlockID; break;
215     case BytecodeFormat::BasicBlock:
216       /// This block type isn't used after version 1.1. However, we have to
217       /// still allow the value in case this is an old bc format file.
218       /// We just let its value creep thru.
219       break;
220     default:
221       error("Invalid block id found: " + utostr(Type));
222       break;
223     }
224   } else {
225     Size = read_uint();
226     Type = Size & 0x1F; // mask low order five bits
227     Size >>= 5; // get rid of five low order bits, leaving high 27
228   }
229   BlockStart = At;
230   if (At + Size > BlockEnd)
231     error("Attempt to size a block past end of memory");
232   BlockEnd = At + Size;
233   if (Handler) Handler->handleBlock(Type, BlockStart, Size);
234 }
235
236
237 /// In LLVM 1.2 and before, Types were derived from Value and so they were
238 /// written as part of the type planes along with any other Value. In LLVM
239 /// 1.3 this changed so that Type does not derive from Value. Consequently,
240 /// the BytecodeReader's containers for Values can't contain Types because
241 /// there's no inheritance relationship. This means that the "Type Type"
242 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3 
243 /// whenever a bytecode construct must have both types and values together, 
244 /// the types are always read/written first and then the Values. Furthermore
245 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
246 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
247 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
248 /// For LLVM 1.2 and before, this function will decrement the type id by
249 /// one to account for the missing Type::TypeTyID enumerator if the value is
250 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
251 /// function returns true, otherwise false. This helps detect situations
252 /// where the pre 1.3 bytecode is indicating that what follows is a type.
253 /// @returns true iff type id corresponds to pre 1.3 "type type" 
254 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
255   if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
256     if (TypeId == Type::LabelTyID) {
257       TypeId = Type::VoidTyID; // sanitize it
258       return true; // indicate we got TypeTyID in pre 1.3 bytecode
259     } else if (TypeId > Type::LabelTyID)
260       --TypeId; // shift all planes down because type type plane is missing
261   }
262   return false;
263 }
264
265 /// Reads a vbr uint to read in a type id and does the necessary
266 /// conversion on it by calling sanitizeTypeId.
267 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
268 /// @see sanitizeTypeId
269 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
270   TypeId = read_vbr_uint();
271   if ( !has32BitTypes )
272     if ( TypeId == 0x00FFFFFF )
273       TypeId = read_vbr_uint();
274   return sanitizeTypeId(TypeId);
275 }
276
277 //===----------------------------------------------------------------------===//
278 // IR Lookup Methods
279 //===----------------------------------------------------------------------===//
280
281 /// Determine if a type id has an implicit null value
282 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
283   if (!hasExplicitPrimitiveZeros)
284     return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
285   return TyID >= Type::FirstDerivedTyID;
286 }
287
288 /// Obtain a type given a typeid and account for things like compaction tables,
289 /// function level vs module level, and the offsetting for the primitive types.
290 const Type *BytecodeReader::getType(unsigned ID) {
291   if (ID < Type::FirstDerivedTyID)
292     if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
293       return T;   // Asked for a primitive type...
294
295   // Otherwise, derived types need offset...
296   ID -= Type::FirstDerivedTyID;
297
298   if (!CompactionTypes.empty()) {
299     if (ID >= CompactionTypes.size())
300       error("Type ID out of range for compaction table!");
301     return CompactionTypes[ID].first;
302   }
303
304   // Is it a module-level type?
305   if (ID < ModuleTypes.size())
306     return ModuleTypes[ID].get();
307
308   // Nope, is it a function-level type?
309   ID -= ModuleTypes.size();
310   if (ID < FunctionTypes.size())
311     return FunctionTypes[ID].get();
312
313   error("Illegal type reference!");
314   return Type::VoidTy;
315 }
316
317 /// Get a sanitized type id. This just makes sure that the \p ID
318 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
319 /// @see sanitizeTypeId
320 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
321   if (sanitizeTypeId(ID))
322     error("Invalid type id encountered");
323   return getType(ID);
324 }
325
326 /// This method just saves some coding. It uses read_typeid to read
327 /// in a sanitized type id, errors that its not the type type, and
328 /// then calls getType to return the type value.
329 inline const Type* BytecodeReader::readSanitizedType() {
330   unsigned ID;
331   if (read_typeid(ID))
332     error("Invalid type id encountered");
333   return getType(ID);
334 }
335
336 /// Get the slot number associated with a type accounting for primitive
337 /// types, compaction tables, and function level vs module level.
338 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
339   if (Ty->isPrimitiveType())
340     return Ty->getTypeID();
341
342   // Scan the compaction table for the type if needed.
343   if (!CompactionTypes.empty()) {
344     for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
345       if (CompactionTypes[i].first == Ty)
346         return Type::FirstDerivedTyID + i; 
347
348     error("Couldn't find type specified in compaction table!");
349   }
350
351   // Check the function level types first...
352   TypeListTy::iterator I = std::find(FunctionTypes.begin(),
353                                      FunctionTypes.end(), Ty);
354
355   if (I != FunctionTypes.end())
356     return Type::FirstDerivedTyID + ModuleTypes.size() + 
357            (&*I - &FunctionTypes[0]);
358
359   // Check the module level types now...
360   I = std::find(ModuleTypes.begin(), ModuleTypes.end(), Ty);
361   if (I == ModuleTypes.end())
362     error("Didn't find type in ModuleTypes.");
363   return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
364 }
365
366 /// This is just like getType, but when a compaction table is in use, it is
367 /// ignored.  It also ignores function level types.
368 /// @see getType
369 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
370   if (Slot < Type::FirstDerivedTyID) {
371     const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
372     if (!Ty)
373       error("Not a primitive type ID?");
374     return Ty;
375   }
376   Slot -= Type::FirstDerivedTyID;
377   if (Slot >= ModuleTypes.size())
378     error("Illegal compaction table type reference!");
379   return ModuleTypes[Slot];
380 }
381
382 /// This is just like getTypeSlot, but when a compaction table is in use, it
383 /// is ignored. It also ignores function level types.
384 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
385   if (Ty->isPrimitiveType())
386     return Ty->getTypeID();
387   TypeListTy::iterator I = std::find(ModuleTypes.begin(),
388                                       ModuleTypes.end(), Ty);
389   if (I == ModuleTypes.end())
390     error("Didn't find type in ModuleTypes.");
391   return Type::FirstDerivedTyID + (&*I - &ModuleTypes[0]);
392 }
393
394 /// Retrieve a value of a given type and slot number, possibly creating 
395 /// it if it doesn't already exist. 
396 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
397   assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
398   unsigned Num = oNum;
399
400   // If there is a compaction table active, it defines the low-level numbers.
401   // If not, the module values define the low-level numbers.
402   if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
403     if (Num < CompactionValues[type].size())
404       return CompactionValues[type][Num];
405     Num -= CompactionValues[type].size();
406   } else {
407     // By default, the global type id is the type id passed in
408     unsigned GlobalTyID = type;
409
410     // If the type plane was compactified, figure out the global type ID by
411     // adding the derived type ids and the distance.
412     if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
413       GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
414
415     if (hasImplicitNull(GlobalTyID)) {
416       if (Num == 0)
417         return Constant::getNullValue(getType(type));
418       --Num;
419     }
420
421     if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
422       if (Num < ModuleValues[GlobalTyID]->size())
423         return ModuleValues[GlobalTyID]->getOperand(Num);
424       Num -= ModuleValues[GlobalTyID]->size();
425     }
426   }
427
428   if (FunctionValues.size() > type && 
429       FunctionValues[type] && 
430       Num < FunctionValues[type]->size())
431     return FunctionValues[type]->getOperand(Num);
432
433   if (!Create) return 0;  // Do not create a placeholder?
434
435   // Did we already create a place holder?
436   std::pair<unsigned,unsigned> KeyValue(type, oNum);
437   ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
438   if (I != ForwardReferences.end() && I->first == KeyValue)
439     return I->second;   // We have already created this placeholder
440
441   // If the type exists (it should)
442   if (const Type* Ty = getType(type)) {
443     // Create the place holder
444     Value *Val = new Argument(Ty);
445     ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
446     return Val;
447   }
448   throw "Can't create placeholder for value of type slot #" + utostr(type);
449 }
450
451 /// This is just like getValue, but when a compaction table is in use, it 
452 /// is ignored.  Also, no forward references or other fancy features are 
453 /// supported.
454 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
455   if (SlotNo == 0)
456     return Constant::getNullValue(getType(TyID));
457
458   if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
459     TyID -= Type::FirstDerivedTyID;
460     if (TyID >= CompactionTypes.size())
461       error("Type ID out of range for compaction table!");
462     TyID = CompactionTypes[TyID].second;
463   }
464
465   --SlotNo;
466
467   if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
468       SlotNo >= ModuleValues[TyID]->size()) {
469     if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
470       error("Corrupt compaction table entry!"
471             + utostr(TyID) + ", " + utostr(SlotNo) + ": " 
472             + utostr(ModuleValues.size()));
473     else 
474       error("Corrupt compaction table entry!"
475             + utostr(TyID) + ", " + utostr(SlotNo) + ": " 
476             + utostr(ModuleValues.size()) + ", "
477             + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
478             + ", "
479             + utostr(ModuleValues[TyID]->size()));
480   }
481   return ModuleValues[TyID]->getOperand(SlotNo);
482 }
483
484 /// Just like getValue, except that it returns a null pointer
485 /// only on error.  It always returns a constant (meaning that if the value is
486 /// defined, but is not a constant, that is an error).  If the specified
487 /// constant hasn't been parsed yet, a placeholder is defined and used.  
488 /// Later, after the real value is parsed, the placeholder is eliminated.
489 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
490   if (Value *V = getValue(TypeSlot, Slot, false))
491     if (Constant *C = dyn_cast<Constant>(V))
492       return C;   // If we already have the value parsed, just return it
493     else
494       error("Value for slot " + utostr(Slot) + 
495             " is expected to be a constant!");
496
497   const Type *Ty = getType(TypeSlot);
498   std::pair<const Type*, unsigned> Key(Ty, Slot);
499   ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
500
501   if (I != ConstantFwdRefs.end() && I->first == Key) {
502     return I->second;
503   } else {
504     // Create a placeholder for the constant reference and
505     // keep track of the fact that we have a forward ref to recycle it
506     Constant *C = new ConstantPlaceHolder(Ty, Slot);
507     
508     // Keep track of the fact that we have a forward ref to recycle it
509     ConstantFwdRefs.insert(I, std::make_pair(Key, C));
510     return C;
511   }
512 }
513
514 //===----------------------------------------------------------------------===//
515 // IR Construction Methods
516 //===----------------------------------------------------------------------===//
517
518 /// As values are created, they are inserted into the appropriate place
519 /// with this method. The ValueTable argument must be one of ModuleValues
520 /// or FunctionValues data members of this class.
521 unsigned BytecodeReader::insertValue(Value *Val, unsigned type, 
522                                       ValueTable &ValueTab) {
523   assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
524           !hasImplicitNull(type) &&
525          "Cannot read null values from bytecode!");
526
527   if (ValueTab.size() <= type)
528     ValueTab.resize(type+1);
529
530   if (!ValueTab[type]) ValueTab[type] = new ValueList();
531
532   ValueTab[type]->push_back(Val);
533
534   bool HasOffset = hasImplicitNull(type);
535   return ValueTab[type]->size()-1 + HasOffset;
536 }
537
538 /// Insert the arguments of a function as new values in the reader.
539 void BytecodeReader::insertArguments(Function* F) {
540   const FunctionType *FT = F->getFunctionType();
541   Function::aiterator AI = F->abegin();
542   for (FunctionType::param_iterator It = FT->param_begin();
543        It != FT->param_end(); ++It, ++AI)
544     insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
545 }
546
547 //===----------------------------------------------------------------------===//
548 // Bytecode Parsing Methods
549 //===----------------------------------------------------------------------===//
550
551 /// This method parses a single instruction. The instruction is
552 /// inserted at the end of the \p BB provided. The arguments of
553 /// the instruction are provided in the \p Oprnds vector.
554 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
555                                       BasicBlock* BB) {
556   BufPtr SaveAt = At;
557
558   // Clear instruction data
559   Oprnds.clear();
560   unsigned iType = 0;
561   unsigned Opcode = 0;
562   unsigned Op = read_uint();
563
564   // bits   Instruction format:        Common to all formats
565   // --------------------------
566   // 01-00: Opcode type, fixed to 1.
567   // 07-02: Opcode
568   Opcode    = (Op >> 2) & 63;
569   Oprnds.resize((Op >> 0) & 03);
570
571   // Extract the operands
572   switch (Oprnds.size()) {
573   case 1:
574     // bits   Instruction format:
575     // --------------------------
576     // 19-08: Resulting type plane
577     // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
578     //
579     iType   = (Op >>  8) & 4095;
580     Oprnds[0] = (Op >> 20) & 4095;
581     if (Oprnds[0] == 4095)    // Handle special encoding for 0 operands...
582       Oprnds.resize(0);
583     break;
584   case 2:
585     // bits   Instruction format:
586     // --------------------------
587     // 15-08: Resulting type plane
588     // 23-16: Operand #1
589     // 31-24: Operand #2  
590     //
591     iType   = (Op >>  8) & 255;
592     Oprnds[0] = (Op >> 16) & 255;
593     Oprnds[1] = (Op >> 24) & 255;
594     break;
595   case 3:
596     // bits   Instruction format:
597     // --------------------------
598     // 13-08: Resulting type plane
599     // 19-14: Operand #1
600     // 25-20: Operand #2
601     // 31-26: Operand #3
602     //
603     iType   = (Op >>  8) & 63;
604     Oprnds[0] = (Op >> 14) & 63;
605     Oprnds[1] = (Op >> 20) & 63;
606     Oprnds[2] = (Op >> 26) & 63;
607     break;
608   case 0:
609     At -= 4;  // Hrm, try this again...
610     Opcode = read_vbr_uint();
611     Opcode >>= 2;
612     iType = read_vbr_uint();
613
614     unsigned NumOprnds = read_vbr_uint();
615     Oprnds.resize(NumOprnds);
616
617     if (NumOprnds == 0)
618       error("Zero-argument instruction found; this is invalid.");
619
620     for (unsigned i = 0; i != NumOprnds; ++i)
621       Oprnds[i] = read_vbr_uint();
622     align32();
623     break;
624   }
625
626   const Type *InstTy = getSanitizedType(iType);
627
628   // We have enough info to inform the handler now.
629   if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
630
631   // Declare the resulting instruction we'll build.
632   Instruction *Result = 0;
633
634   // If this is a bytecode format that did not include the unreachable
635   // instruction, bump up all opcodes numbers to make space.
636   if (hasNoUnreachableInst) {
637     if (Opcode >= Instruction::Unreachable &&
638         Opcode < 62) {
639       ++Opcode;
640     }
641   }
642
643   // Handle binary operators
644   if (Opcode >= Instruction::BinaryOpsBegin &&
645       Opcode <  Instruction::BinaryOpsEnd  && Oprnds.size() == 2)
646     Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
647                                     getValue(iType, Oprnds[0]),
648                                     getValue(iType, Oprnds[1]));
649
650   switch (Opcode) {
651   default: 
652     if (Result == 0) 
653       error("Illegal instruction read!");
654     break;
655   case Instruction::VAArg:
656     Result = new VAArgInst(getValue(iType, Oprnds[0]), 
657                            getSanitizedType(Oprnds[1]));
658     break;
659   case Instruction::VANext:
660     Result = new VANextInst(getValue(iType, Oprnds[0]), 
661                             getSanitizedType(Oprnds[1]));
662     break;
663   case Instruction::Cast:
664     Result = new CastInst(getValue(iType, Oprnds[0]), 
665                           getSanitizedType(Oprnds[1]));
666     break;
667   case Instruction::Select:
668     Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
669                             getValue(iType, Oprnds[1]),
670                             getValue(iType, Oprnds[2]));
671     break;
672   case Instruction::PHI: {
673     if (Oprnds.size() == 0 || (Oprnds.size() & 1))
674       error("Invalid phi node encountered!");
675
676     PHINode *PN = new PHINode(InstTy);
677     PN->op_reserve(Oprnds.size());
678     for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
679       PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
680     Result = PN;
681     break;
682   }
683
684   case Instruction::Shl:
685   case Instruction::Shr:
686     Result = new ShiftInst((Instruction::OtherOps)Opcode,
687                            getValue(iType, Oprnds[0]),
688                            getValue(Type::UByteTyID, Oprnds[1]));
689     break;
690   case Instruction::Ret:
691     if (Oprnds.size() == 0)
692       Result = new ReturnInst();
693     else if (Oprnds.size() == 1)
694       Result = new ReturnInst(getValue(iType, Oprnds[0]));
695     else
696       error("Unrecognized instruction!");
697     break;
698
699   case Instruction::Br:
700     if (Oprnds.size() == 1)
701       Result = new BranchInst(getBasicBlock(Oprnds[0]));
702     else if (Oprnds.size() == 3)
703       Result = new BranchInst(getBasicBlock(Oprnds[0]), 
704           getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
705     else
706       error("Invalid number of operands for a 'br' instruction!");
707     break;
708   case Instruction::Switch: {
709     if (Oprnds.size() & 1)
710       error("Switch statement with odd number of arguments!");
711
712     SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
713                                    getBasicBlock(Oprnds[1]));
714     for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
715       I->addCase(cast<Constant>(getValue(iType, Oprnds[i])),
716                  getBasicBlock(Oprnds[i+1]));
717     Result = I;
718     break;
719   }
720
721   case Instruction::Call: {
722     if (Oprnds.size() == 0)
723       error("Invalid call instruction encountered!");
724
725     Value *F = getValue(iType, Oprnds[0]);
726
727     // Check to make sure we have a pointer to function type
728     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
729     if (PTy == 0) error("Call to non function pointer value!");
730     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
731     if (FTy == 0) error("Call to non function pointer value!");
732
733     std::vector<Value *> Params;
734     if (!FTy->isVarArg()) {
735       FunctionType::param_iterator It = FTy->param_begin();
736
737       for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
738         if (It == FTy->param_end())
739           error("Invalid call instruction!");
740         Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
741       }
742       if (It != FTy->param_end())
743         error("Invalid call instruction!");
744     } else {
745       Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
746
747       unsigned FirstVariableOperand;
748       if (Oprnds.size() < FTy->getNumParams())
749         error("Call instruction missing operands!");
750
751       // Read all of the fixed arguments
752       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
753         Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
754       
755       FirstVariableOperand = FTy->getNumParams();
756
757       if ((Oprnds.size()-FirstVariableOperand) & 1) 
758         error("Invalid call instruction!");   // Must be pairs of type/value
759         
760       for (unsigned i = FirstVariableOperand, e = Oprnds.size(); 
761            i != e; i += 2)
762         Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
763     }
764
765     Result = new CallInst(F, Params);
766     break;
767   }
768   case Instruction::Invoke: {
769     if (Oprnds.size() < 3) 
770       error("Invalid invoke instruction!");
771     Value *F = getValue(iType, Oprnds[0]);
772
773     // Check to make sure we have a pointer to function type
774     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
775     if (PTy == 0) 
776       error("Invoke to non function pointer value!");
777     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
778     if (FTy == 0) 
779       error("Invoke to non function pointer value!");
780
781     std::vector<Value *> Params;
782     BasicBlock *Normal, *Except;
783
784     if (!FTy->isVarArg()) {
785       Normal = getBasicBlock(Oprnds[1]);
786       Except = getBasicBlock(Oprnds[2]);
787
788       FunctionType::param_iterator It = FTy->param_begin();
789       for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
790         if (It == FTy->param_end())
791           error("Invalid invoke instruction!");
792         Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
793       }
794       if (It != FTy->param_end())
795         error("Invalid invoke instruction!");
796     } else {
797       Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
798
799       Normal = getBasicBlock(Oprnds[0]);
800       Except = getBasicBlock(Oprnds[1]);
801       
802       unsigned FirstVariableArgument = FTy->getNumParams()+2;
803       for (unsigned i = 2; i != FirstVariableArgument; ++i)
804         Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
805                                   Oprnds[i]));
806       
807       if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
808         error("Invalid invoke instruction!");
809
810       for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
811         Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
812     }
813
814     Result = new InvokeInst(F, Normal, Except, Params);
815     break;
816   }
817   case Instruction::Malloc:
818     if (Oprnds.size() > 2) 
819       error("Invalid malloc instruction!");
820     if (!isa<PointerType>(InstTy))
821       error("Invalid malloc instruction!");
822
823     Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
824                             Oprnds.size() ? getValue(Type::UIntTyID,
825                                                    Oprnds[0]) : 0);
826     break;
827
828   case Instruction::Alloca:
829     if (Oprnds.size() > 2) 
830       error("Invalid alloca instruction!");
831     if (!isa<PointerType>(InstTy))
832       error("Invalid alloca instruction!");
833
834     Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
835                             Oprnds.size() ? getValue(Type::UIntTyID, 
836                             Oprnds[0]) :0);
837     break;
838   case Instruction::Free:
839     if (!isa<PointerType>(InstTy))
840       error("Invalid free instruction!");
841     Result = new FreeInst(getValue(iType, Oprnds[0]));
842     break;
843   case Instruction::GetElementPtr: {
844     if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
845       error("Invalid getelementptr instruction!");
846
847     std::vector<Value*> Idx;
848
849     const Type *NextTy = InstTy;
850     for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
851       const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
852       if (!TopTy) 
853         error("Invalid getelementptr instruction!"); 
854
855       unsigned ValIdx = Oprnds[i];
856       unsigned IdxTy = 0;
857       if (!hasRestrictedGEPTypes) {
858         // Struct indices are always uints, sequential type indices can be any
859         // of the 32 or 64-bit integer types.  The actual choice of type is
860         // encoded in the low two bits of the slot number.
861         if (isa<StructType>(TopTy))
862           IdxTy = Type::UIntTyID;
863         else {
864           switch (ValIdx & 3) {
865           default:
866           case 0: IdxTy = Type::UIntTyID; break;
867           case 1: IdxTy = Type::IntTyID; break;
868           case 2: IdxTy = Type::ULongTyID; break;
869           case 3: IdxTy = Type::LongTyID; break;
870           }
871           ValIdx >>= 2;
872         }
873       } else {
874         IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
875       }
876
877       Idx.push_back(getValue(IdxTy, ValIdx));
878
879       // Convert ubyte struct indices into uint struct indices.
880       if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
881         if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
882           Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
883
884       NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
885     }
886
887     Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
888     break;
889   }
890
891   case 62:   // volatile load
892   case Instruction::Load:
893     if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
894       error("Invalid load instruction!");
895     Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
896     break;
897
898   case 63:   // volatile store 
899   case Instruction::Store: {
900     if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
901       error("Invalid store instruction!");
902
903     Value *Ptr = getValue(iType, Oprnds[1]);
904     const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
905     Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
906                            Opcode == 63);
907     break;
908   }
909   case Instruction::Unwind:
910     if (Oprnds.size() != 0) error("Invalid unwind instruction!");
911     Result = new UnwindInst();
912     break;
913   case Instruction::Unreachable:
914     if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
915     Result = new UnreachableInst();
916     break;
917   }  // end switch(Opcode) 
918
919   unsigned TypeSlot;
920   if (Result->getType() == InstTy)
921     TypeSlot = iType;
922   else
923     TypeSlot = getTypeSlot(Result->getType());
924
925   insertValue(Result, TypeSlot, FunctionValues);
926   BB->getInstList().push_back(Result);
927 }
928
929 /// Get a particular numbered basic block, which might be a forward reference.
930 /// This works together with ParseBasicBlock to handle these forward references
931 /// in a clean manner.  This function is used when constructing phi, br, switch,
932 /// and other instructions that reference basic blocks. Blocks are numbered
933 /// sequentially as they appear in the function.
934 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
935   // Make sure there is room in the table...
936   if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
937
938   // First check to see if this is a backwards reference, i.e., ParseBasicBlock
939   // has already created this block, or if the forward reference has already
940   // been created.
941   if (ParsedBasicBlocks[ID])
942     return ParsedBasicBlocks[ID];
943
944   // Otherwise, the basic block has not yet been created.  Do so and add it to
945   // the ParsedBasicBlocks list.
946   return ParsedBasicBlocks[ID] = new BasicBlock();
947 }
948
949 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.  
950 /// This method reads in one of the basicblock packets. This method is not used
951 /// for bytecode files after LLVM 1.0
952 /// @returns The basic block constructed.
953 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
954   if (Handler) Handler->handleBasicBlockBegin(BlockNo);
955
956   BasicBlock *BB = 0;
957
958   if (ParsedBasicBlocks.size() == BlockNo)
959     ParsedBasicBlocks.push_back(BB = new BasicBlock());
960   else if (ParsedBasicBlocks[BlockNo] == 0)
961     BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
962   else
963     BB = ParsedBasicBlocks[BlockNo];
964
965   std::vector<unsigned> Operands;
966   while (moreInBlock())
967     ParseInstruction(Operands, BB);
968
969   if (Handler) Handler->handleBasicBlockEnd(BlockNo);
970   return BB;
971 }
972
973 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
974 /// In post 1.0 bytecode files, we no longer emit basic block individually, 
975 /// in order to avoid per-basic-block overhead.
976 /// @returns Rhe number of basic blocks encountered.
977 unsigned BytecodeReader::ParseInstructionList(Function* F) {
978   unsigned BlockNo = 0;
979   std::vector<unsigned> Args;
980
981   while (moreInBlock()) {
982     if (Handler) Handler->handleBasicBlockBegin(BlockNo);
983     BasicBlock *BB;
984     if (ParsedBasicBlocks.size() == BlockNo)
985       ParsedBasicBlocks.push_back(BB = new BasicBlock());
986     else if (ParsedBasicBlocks[BlockNo] == 0)
987       BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
988     else
989       BB = ParsedBasicBlocks[BlockNo];
990     ++BlockNo;
991     F->getBasicBlockList().push_back(BB);
992
993     // Read instructions into this basic block until we get to a terminator
994     while (moreInBlock() && !BB->getTerminator())
995       ParseInstruction(Args, BB);
996
997     if (!BB->getTerminator())
998       error("Non-terminated basic block found!");
999
1000     if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1001   }
1002
1003   return BlockNo;
1004 }
1005
1006 /// Parse a symbol table. This works for both module level and function
1007 /// level symbol tables.  For function level symbol tables, the CurrentFunction
1008 /// parameter must be non-zero and the ST parameter must correspond to
1009 /// CurrentFunction's symbol table. For Module level symbol tables, the
1010 /// CurrentFunction argument must be zero.
1011 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1012                                       SymbolTable *ST) {
1013   if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1014
1015   // Allow efficient basic block lookup by number.
1016   std::vector<BasicBlock*> BBMap;
1017   if (CurrentFunction)
1018     for (Function::iterator I = CurrentFunction->begin(),
1019            E = CurrentFunction->end(); I != E; ++I)
1020       BBMap.push_back(I);
1021
1022   /// In LLVM 1.3 we write types separately from values so
1023   /// The types are always first in the symbol table. This is
1024   /// because Type no longer derives from Value.
1025   if (!hasTypeDerivedFromValue) {
1026     // Symtab block header: [num entries]
1027     unsigned NumEntries = read_vbr_uint();
1028     for (unsigned i = 0; i < NumEntries; ++i) {
1029       // Symtab entry: [def slot #][name]
1030       unsigned slot = read_vbr_uint();
1031       std::string Name = read_str();
1032       const Type* T = getType(slot);
1033       ST->insert(Name, T);
1034     }
1035   }
1036
1037   while (moreInBlock()) {
1038     // Symtab block header: [num entries][type id number]
1039     unsigned NumEntries = read_vbr_uint();
1040     unsigned Typ = 0;
1041     bool isTypeType = read_typeid(Typ);
1042     const Type *Ty = getType(Typ);
1043
1044     for (unsigned i = 0; i != NumEntries; ++i) {
1045       // Symtab entry: [def slot #][name]
1046       unsigned slot = read_vbr_uint();
1047       std::string Name = read_str();
1048
1049       // if we're reading a pre 1.3 bytecode file and the type plane
1050       // is the "type type", handle it here
1051       if (isTypeType) {
1052         const Type* T = getType(slot);
1053         if (T == 0)
1054           error("Failed type look-up for name '" + Name + "'");
1055         ST->insert(Name, T);
1056         continue; // code below must be short circuited
1057       } else {
1058         Value *V = 0;
1059         if (Typ == Type::LabelTyID) {
1060           if (slot < BBMap.size())
1061             V = BBMap[slot];
1062         } else {
1063           V = getValue(Typ, slot, false); // Find mapping...
1064         }
1065         if (V == 0)
1066           error("Failed value look-up for name '" + Name + "'");
1067         V->setName(Name, ST);
1068       }
1069     }
1070   }
1071   checkPastBlockEnd("Symbol Table");
1072   if (Handler) Handler->handleSymbolTableEnd();
1073 }
1074
1075 /// Read in the types portion of a compaction table. 
1076 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1077   for (unsigned i = 0; i != NumEntries; ++i) {
1078     unsigned TypeSlot = 0;
1079     if (read_typeid(TypeSlot))
1080       error("Invalid type in compaction table: type type");
1081     const Type *Typ = getGlobalTableType(TypeSlot);
1082     CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1083     if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1084   }
1085 }
1086
1087 /// Parse a compaction table.
1088 void BytecodeReader::ParseCompactionTable() {
1089
1090   // Notify handler that we're beginning a compaction table.
1091   if (Handler) Handler->handleCompactionTableBegin();
1092
1093   // In LLVM 1.3 Type no longer derives from Value. So, 
1094   // we always write them first in the compaction table
1095   // because they can't occupy a "type plane" where the
1096   // Values reside.
1097   if (! hasTypeDerivedFromValue) {
1098     unsigned NumEntries = read_vbr_uint();
1099     ParseCompactionTypes(NumEntries);
1100   }
1101
1102   // Compaction tables live in separate blocks so we have to loop
1103   // until we've read the whole thing.
1104   while (moreInBlock()) {
1105     // Read the number of Value* entries in the compaction table
1106     unsigned NumEntries = read_vbr_uint();
1107     unsigned Ty = 0;
1108     unsigned isTypeType = false;
1109
1110     // Decode the type from value read in. Most compaction table
1111     // planes will have one or two entries in them. If that's the
1112     // case then the length is encoded in the bottom two bits and
1113     // the higher bits encode the type. This saves another VBR value.
1114     if ((NumEntries & 3) == 3) {
1115       // In this case, both low-order bits are set (value 3). This
1116       // is a signal that the typeid follows.
1117       NumEntries >>= 2;
1118       isTypeType = read_typeid(Ty);
1119     } else {
1120       // In this case, the low-order bits specify the number of entries
1121       // and the high order bits specify the type.
1122       Ty = NumEntries >> 2;
1123       isTypeType = sanitizeTypeId(Ty);
1124       NumEntries &= 3;
1125     }
1126
1127     // if we're reading a pre 1.3 bytecode file and the type plane
1128     // is the "type type", handle it here
1129     if (isTypeType) {
1130       ParseCompactionTypes(NumEntries);
1131     } else {
1132       // Make sure we have enough room for the plane.
1133       if (Ty >= CompactionValues.size())
1134         CompactionValues.resize(Ty+1);
1135
1136       // Make sure the plane is empty or we have some kind of error.
1137       if (!CompactionValues[Ty].empty())
1138         error("Compaction table plane contains multiple entries!");
1139
1140       // Notify handler about the plane.
1141       if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1142
1143       // Push the implicit zero.
1144       CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1145
1146       // Read in each of the entries, put them in the compaction table
1147       // and notify the handler that we have a new compaction table value.
1148       for (unsigned i = 0; i != NumEntries; ++i) {
1149         unsigned ValSlot = read_vbr_uint();
1150         Value *V = getGlobalTableValue(Ty, ValSlot);
1151         CompactionValues[Ty].push_back(V);
1152         if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1153       }
1154     }
1155   }
1156   // Notify handler that the compaction table is done.
1157   if (Handler) Handler->handleCompactionTableEnd();
1158 }
1159     
1160 // Parse a single type. The typeid is read in first. If its a primitive type
1161 // then nothing else needs to be read, we know how to instantiate it. If its
1162 // a derived type, then additional data is read to fill out the type 
1163 // definition.
1164 const Type *BytecodeReader::ParseType() {
1165   unsigned PrimType = 0;
1166   if (read_typeid(PrimType))
1167     error("Invalid type (type type) in type constants!");
1168
1169   const Type *Result = 0;
1170   if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1171     return Result;
1172   
1173   switch (PrimType) {
1174   case Type::FunctionTyID: {
1175     const Type *RetType = readSanitizedType();
1176
1177     unsigned NumParams = read_vbr_uint();
1178
1179     std::vector<const Type*> Params;
1180     while (NumParams--) 
1181       Params.push_back(readSanitizedType());
1182
1183     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1184     if (isVarArg) Params.pop_back();
1185
1186     Result = FunctionType::get(RetType, Params, isVarArg);
1187     break;
1188   }
1189   case Type::ArrayTyID: {
1190     const Type *ElementType = readSanitizedType();
1191     unsigned NumElements = read_vbr_uint();
1192     Result =  ArrayType::get(ElementType, NumElements);
1193     break;
1194   }
1195   case Type::PackedTyID: {
1196     const Type *ElementType = readSanitizedType();
1197     unsigned NumElements = read_vbr_uint();
1198     Result =  PackedType::get(ElementType, NumElements);
1199     break;
1200   }
1201   case Type::StructTyID: {
1202     std::vector<const Type*> Elements;
1203     unsigned Typ = 0;
1204     if (read_typeid(Typ))
1205       error("Invalid element type (type type) for structure!");
1206
1207     while (Typ) {         // List is terminated by void/0 typeid
1208       Elements.push_back(getType(Typ));
1209       if (read_typeid(Typ))
1210         error("Invalid element type (type type) for structure!");
1211     }
1212
1213     Result = StructType::get(Elements);
1214     break;
1215   }
1216   case Type::PointerTyID: {
1217     Result = PointerType::get(readSanitizedType());
1218     break;
1219   }
1220
1221   case Type::OpaqueTyID: {
1222     Result = OpaqueType::get();
1223     break;
1224   }
1225
1226   default:
1227     error("Don't know how to deserialize primitive type " + utostr(PrimType));
1228     break;
1229   }
1230   if (Handler) Handler->handleType(Result);
1231   return Result;
1232 }
1233
1234 // ParseTypes - We have to use this weird code to handle recursive
1235 // types.  We know that recursive types will only reference the current slab of
1236 // values in the type plane, but they can forward reference types before they
1237 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1238 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
1239 // this ugly problem, we pessimistically insert an opaque type for each type we
1240 // are about to read.  This means that forward references will resolve to
1241 // something and when we reread the type later, we can replace the opaque type
1242 // with a new resolved concrete type.
1243 //
1244 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1245   assert(Tab.size() == 0 && "should not have read type constants in before!");
1246
1247   // Insert a bunch of opaque types to be resolved later...
1248   Tab.reserve(NumEntries);
1249   for (unsigned i = 0; i != NumEntries; ++i)
1250     Tab.push_back(OpaqueType::get());
1251
1252   if (Handler) 
1253     Handler->handleTypeList(NumEntries);
1254
1255   // Loop through reading all of the types.  Forward types will make use of the
1256   // opaque types just inserted.
1257   //
1258   for (unsigned i = 0; i != NumEntries; ++i) {
1259     const Type* NewTy = ParseType();
1260     const Type* OldTy = Tab[i].get();
1261     if (NewTy == 0) 
1262       error("Couldn't parse type!");
1263
1264     // Don't directly push the new type on the Tab. Instead we want to replace 
1265     // the opaque type we previously inserted with the new concrete value. This
1266     // approach helps with forward references to types. The refinement from the
1267     // abstract (opaque) type to the new type causes all uses of the abstract
1268     // type to use the concrete type (NewTy). This will also cause the opaque
1269     // type to be deleted.
1270     cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1271
1272     // This should have replaced the old opaque type with the new type in the
1273     // value table... or with a preexisting type that was already in the system.
1274     // Let's just make sure it did.
1275     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1276   }
1277 }
1278
1279 /// Parse a single constant value
1280 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1281   // We must check for a ConstantExpr before switching by type because
1282   // a ConstantExpr can be of any type, and has no explicit value.
1283   // 
1284   // 0 if not expr; numArgs if is expr
1285   unsigned isExprNumArgs = read_vbr_uint();
1286
1287   if (isExprNumArgs) {
1288     // 'undef' is encoded with 'exprnumargs' == 1.
1289     if (!hasNoUndefValue)
1290       if (--isExprNumArgs == 0)
1291         return UndefValue::get(getType(TypeID));
1292   
1293     // FIXME: Encoding of constant exprs could be much more compact!
1294     std::vector<Constant*> ArgVec;
1295     ArgVec.reserve(isExprNumArgs);
1296     unsigned Opcode = read_vbr_uint();
1297
1298     // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1299     if (hasNoUnreachableInst) Opcode++;
1300     
1301     // Read the slot number and types of each of the arguments
1302     for (unsigned i = 0; i != isExprNumArgs; ++i) {
1303       unsigned ArgValSlot = read_vbr_uint();
1304       unsigned ArgTypeSlot = 0;
1305       if (read_typeid(ArgTypeSlot))
1306         error("Invalid argument type (type type) for constant value");
1307       
1308       // Get the arg value from its slot if it exists, otherwise a placeholder
1309       ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1310     }
1311     
1312     // Construct a ConstantExpr of the appropriate kind
1313     if (isExprNumArgs == 1) {           // All one-operand expressions
1314       if (Opcode != Instruction::Cast)
1315         error("Only cast instruction has one argument for ConstantExpr");
1316
1317       Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1318       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1319       return Result;
1320     } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1321       std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1322
1323       if (hasRestrictedGEPTypes) {
1324         const Type *BaseTy = ArgVec[0]->getType();
1325         generic_gep_type_iterator<std::vector<Constant*>::iterator>
1326           GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1327           E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1328         for (unsigned i = 0; GTI != E; ++GTI, ++i)
1329           if (isa<StructType>(*GTI)) {
1330             if (IdxList[i]->getType() != Type::UByteTy)
1331               error("Invalid index for getelementptr!");
1332             IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1333           }
1334       }
1335
1336       Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1337       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1338       return Result;
1339     } else if (Opcode == Instruction::Select) {
1340       if (ArgVec.size() != 3)
1341         error("Select instruction must have three arguments.");
1342       Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1], 
1343                                                  ArgVec[2]);
1344       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1345       return Result;
1346     } else {                            // All other 2-operand expressions
1347       Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1348       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1349       return Result;
1350     }
1351   }
1352   
1353   // Ok, not an ConstantExpr.  We now know how to read the given type...
1354   const Type *Ty = getType(TypeID);
1355   switch (Ty->getTypeID()) {
1356   case Type::BoolTyID: {
1357     unsigned Val = read_vbr_uint();
1358     if (Val != 0 && Val != 1) 
1359       error("Invalid boolean value read.");
1360     Constant* Result = ConstantBool::get(Val == 1);
1361     if (Handler) Handler->handleConstantValue(Result);
1362     return Result;
1363   }
1364
1365   case Type::UByteTyID:   // Unsigned integer types...
1366   case Type::UShortTyID:
1367   case Type::UIntTyID: {
1368     unsigned Val = read_vbr_uint();
1369     if (!ConstantUInt::isValueValidForType(Ty, Val)) 
1370       error("Invalid unsigned byte/short/int read.");
1371     Constant* Result =  ConstantUInt::get(Ty, Val);
1372     if (Handler) Handler->handleConstantValue(Result);
1373     return Result;
1374   }
1375
1376   case Type::ULongTyID: {
1377     Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1378     if (Handler) Handler->handleConstantValue(Result);
1379     return Result;
1380   }
1381
1382   case Type::SByteTyID:   // Signed integer types...
1383   case Type::ShortTyID:
1384   case Type::IntTyID: {
1385   case Type::LongTyID:
1386     int64_t Val = read_vbr_int64();
1387     if (!ConstantSInt::isValueValidForType(Ty, Val)) 
1388       error("Invalid signed byte/short/int/long read.");
1389     Constant* Result = ConstantSInt::get(Ty, Val);
1390     if (Handler) Handler->handleConstantValue(Result);
1391     return Result;
1392   }
1393
1394   case Type::FloatTyID: {
1395     float Val;
1396     read_float(Val);
1397     Constant* Result = ConstantFP::get(Ty, Val);
1398     if (Handler) Handler->handleConstantValue(Result);
1399     return Result;
1400   }
1401
1402   case Type::DoubleTyID: {
1403     double Val;
1404     read_double(Val);
1405     Constant* Result = ConstantFP::get(Ty, Val);
1406     if (Handler) Handler->handleConstantValue(Result);
1407     return Result;
1408   }
1409
1410   case Type::ArrayTyID: {
1411     const ArrayType *AT = cast<ArrayType>(Ty);
1412     unsigned NumElements = AT->getNumElements();
1413     unsigned TypeSlot = getTypeSlot(AT->getElementType());
1414     std::vector<Constant*> Elements;
1415     Elements.reserve(NumElements);
1416     while (NumElements--)     // Read all of the elements of the constant.
1417       Elements.push_back(getConstantValue(TypeSlot,
1418                                           read_vbr_uint()));
1419     Constant* Result = ConstantArray::get(AT, Elements);
1420     if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1421     return Result;
1422   }
1423
1424   case Type::StructTyID: {
1425     const StructType *ST = cast<StructType>(Ty);
1426
1427     std::vector<Constant *> Elements;
1428     Elements.reserve(ST->getNumElements());
1429     for (unsigned i = 0; i != ST->getNumElements(); ++i)
1430       Elements.push_back(getConstantValue(ST->getElementType(i),
1431                                           read_vbr_uint()));
1432
1433     Constant* Result = ConstantStruct::get(ST, Elements);
1434     if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1435     return Result;
1436   }    
1437
1438   case Type::PackedTyID: {
1439     const PackedType *PT = cast<PackedType>(Ty);
1440     unsigned NumElements = PT->getNumElements();
1441     unsigned TypeSlot = getTypeSlot(PT->getElementType());
1442     std::vector<Constant*> Elements;
1443     Elements.reserve(NumElements);
1444     while (NumElements--)     // Read all of the elements of the constant.
1445       Elements.push_back(getConstantValue(TypeSlot,
1446                                           read_vbr_uint()));
1447     Constant* Result = ConstantPacked::get(PT, Elements);
1448     if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1449     return Result;
1450   }
1451
1452   case Type::PointerTyID: {  // ConstantPointerRef value (backwards compat).
1453     const PointerType *PT = cast<PointerType>(Ty);
1454     unsigned Slot = read_vbr_uint();
1455     
1456     // Check to see if we have already read this global variable...
1457     Value *Val = getValue(TypeID, Slot, false);
1458     if (Val) {
1459       GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1460       if (!GV) error("GlobalValue not in ValueTable!");
1461       if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1462       return GV;
1463     } else {
1464       error("Forward references are not allowed here.");
1465     }
1466   }
1467
1468   default:
1469     error("Don't know how to deserialize constant value of type '" +
1470                       Ty->getDescription());
1471     break;
1472   }
1473   return 0;
1474 }
1475
1476 /// Resolve references for constants. This function resolves the forward 
1477 /// referenced constants in the ConstantFwdRefs map. It uses the 
1478 /// replaceAllUsesWith method of Value class to substitute the placeholder
1479 /// instance with the actual instance.
1480 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
1481   ConstantRefsType::iterator I =
1482     ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
1483   if (I == ConstantFwdRefs.end()) return;   // Never forward referenced?
1484
1485   Value *PH = I->second;   // Get the placeholder...
1486   PH->replaceAllUsesWith(NewV);
1487   delete PH;                               // Delete the old placeholder
1488   ConstantFwdRefs.erase(I);                // Remove the map entry for it
1489 }
1490
1491 /// Parse the constant strings section.
1492 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1493   for (; NumEntries; --NumEntries) {
1494     unsigned Typ = 0;
1495     if (read_typeid(Typ))
1496       error("Invalid type (type type) for string constant");
1497     const Type *Ty = getType(Typ);
1498     if (!isa<ArrayType>(Ty))
1499       error("String constant data invalid!");
1500     
1501     const ArrayType *ATy = cast<ArrayType>(Ty);
1502     if (ATy->getElementType() != Type::SByteTy &&
1503         ATy->getElementType() != Type::UByteTy)
1504       error("String constant data invalid!");
1505     
1506     // Read character data.  The type tells us how long the string is.
1507     char Data[ATy->getNumElements()]; 
1508     read_data(Data, Data+ATy->getNumElements());
1509
1510     std::vector<Constant*> Elements(ATy->getNumElements());
1511     if (ATy->getElementType() == Type::SByteTy)
1512       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1513         Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1514     else
1515       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1516         Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1517
1518     // Create the constant, inserting it as needed.
1519     Constant *C = ConstantArray::get(ATy, Elements);
1520     unsigned Slot = insertValue(C, Typ, Tab);
1521     ResolveReferencesToConstant(C, Slot);
1522     if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1523   }
1524 }
1525
1526 /// Parse the constant pool.
1527 void BytecodeReader::ParseConstantPool(ValueTable &Tab, 
1528                                        TypeListTy &TypeTab,
1529                                        bool isFunction) {
1530   if (Handler) Handler->handleGlobalConstantsBegin();
1531
1532   /// In LLVM 1.3 Type does not derive from Value so the types
1533   /// do not occupy a plane. Consequently, we read the types
1534   /// first in the constant pool.
1535   if (isFunction && !hasTypeDerivedFromValue) {
1536     unsigned NumEntries = read_vbr_uint();
1537     ParseTypes(TypeTab, NumEntries);
1538   }
1539
1540   while (moreInBlock()) {
1541     unsigned NumEntries = read_vbr_uint();
1542     unsigned Typ = 0;
1543     bool isTypeType = read_typeid(Typ);
1544
1545     /// In LLVM 1.2 and before, Types were written to the
1546     /// bytecode file in the "Type Type" plane (#12).
1547     /// In 1.3 plane 12 is now the label plane.  Handle this here.
1548     if (isTypeType) {
1549       ParseTypes(TypeTab, NumEntries);
1550     } else if (Typ == Type::VoidTyID) {
1551       /// Use of Type::VoidTyID is a misnomer. It actually means
1552       /// that the following plane is constant strings
1553       assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1554       ParseStringConstants(NumEntries, Tab);
1555     } else {
1556       for (unsigned i = 0; i < NumEntries; ++i) {
1557         Constant *C = ParseConstantValue(Typ);
1558         assert(C && "ParseConstantValue returned NULL!");
1559         unsigned Slot = insertValue(C, Typ, Tab);
1560
1561         // If we are reading a function constant table, make sure that we adjust
1562         // the slot number to be the real global constant number.
1563         //
1564         if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1565             ModuleValues[Typ])
1566           Slot += ModuleValues[Typ]->size();
1567         ResolveReferencesToConstant(C, Slot);
1568       }
1569     }
1570   }
1571
1572   // After we have finished parsing the constant pool, we had better not have
1573   // any dangling references left.
1574   if (!ConstantFwdRefs.empty()) {
1575   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
1576     ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1577     const Type* missingType = I->first.first;
1578     Constant* missingConst = I->second;
1579     error(utostr(ConstantFwdRefs.size()) + 
1580           " unresolved constant reference exist. First one is '" + 
1581           missingConst->getName() + "' of type '" + 
1582           missingType->getDescription() + "'.");
1583   }
1584
1585   checkPastBlockEnd("Constant Pool");
1586   if (Handler) Handler->handleGlobalConstantsEnd();
1587 }
1588
1589 /// Parse the contents of a function. Note that this function can be
1590 /// called lazily by materializeFunction
1591 /// @see materializeFunction
1592 void BytecodeReader::ParseFunctionBody(Function* F) {
1593
1594   unsigned FuncSize = BlockEnd - At;
1595   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1596
1597   unsigned LinkageType = read_vbr_uint();
1598   switch (LinkageType) {
1599   case 0: Linkage = GlobalValue::ExternalLinkage; break;
1600   case 1: Linkage = GlobalValue::WeakLinkage; break;
1601   case 2: Linkage = GlobalValue::AppendingLinkage; break;
1602   case 3: Linkage = GlobalValue::InternalLinkage; break;
1603   case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1604   default:
1605     error("Invalid linkage type for Function.");
1606     Linkage = GlobalValue::InternalLinkage;
1607     break;
1608   }
1609
1610   F->setLinkage(Linkage);
1611   if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1612
1613   // Keep track of how many basic blocks we have read in...
1614   unsigned BlockNum = 0;
1615   bool InsertedArguments = false;
1616
1617   BufPtr MyEnd = BlockEnd;
1618   while (At < MyEnd) {
1619     unsigned Type, Size;
1620     BufPtr OldAt = At;
1621     read_block(Type, Size);
1622
1623     switch (Type) {
1624     case BytecodeFormat::ConstantPoolBlockID:
1625       if (!InsertedArguments) {
1626         // Insert arguments into the value table before we parse the first basic
1627         // block in the function, but after we potentially read in the
1628         // compaction table.
1629         insertArguments(F);
1630         InsertedArguments = true;
1631       }
1632
1633       ParseConstantPool(FunctionValues, FunctionTypes, true);
1634       break;
1635
1636     case BytecodeFormat::CompactionTableBlockID:
1637       ParseCompactionTable();
1638       break;
1639
1640     case BytecodeFormat::BasicBlock: {
1641       if (!InsertedArguments) {
1642         // Insert arguments into the value table before we parse the first basic
1643         // block in the function, but after we potentially read in the
1644         // compaction table.
1645         insertArguments(F);
1646         InsertedArguments = true;
1647       }
1648
1649       BasicBlock *BB = ParseBasicBlock(BlockNum++);
1650       F->getBasicBlockList().push_back(BB);
1651       break;
1652     }
1653
1654     case BytecodeFormat::InstructionListBlockID: {
1655       // Insert arguments into the value table before we parse the instruction
1656       // list for the function, but after we potentially read in the compaction
1657       // table.
1658       if (!InsertedArguments) {
1659         insertArguments(F);
1660         InsertedArguments = true;
1661       }
1662
1663       if (BlockNum) 
1664         error("Already parsed basic blocks!");
1665       BlockNum = ParseInstructionList(F);
1666       break;
1667     }
1668
1669     case BytecodeFormat::SymbolTableBlockID:
1670       ParseSymbolTable(F, &F->getSymbolTable());
1671       break;
1672
1673     default:
1674       At += Size;
1675       if (OldAt > At) 
1676         error("Wrapped around reading bytecode.");
1677       break;
1678     }
1679     BlockEnd = MyEnd;
1680
1681     // Malformed bc file if read past end of block.
1682     align32();
1683   }
1684
1685   // Make sure there were no references to non-existant basic blocks.
1686   if (BlockNum != ParsedBasicBlocks.size())
1687     error("Illegal basic block operand reference");
1688
1689   ParsedBasicBlocks.clear();
1690
1691   // Resolve forward references.  Replace any uses of a forward reference value
1692   // with the real value.
1693
1694   // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1695   // number of operands.  PHI nodes often have forward references, and can also
1696   // often have a very large number of operands.
1697   //
1698   // FIXME: REEVALUATE.  replaceAllUsesWith is _much_ faster now, and this code
1699   // should be simplified back to using it!
1700   //
1701   std::map<Value*, Value*> ForwardRefMapping;
1702   for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator 
1703          I = ForwardReferences.begin(), E = ForwardReferences.end();
1704        I != E; ++I)
1705     ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1706                                             false);
1707
1708   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1709     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1710       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1711         if (Value* V = I->getOperand(i))
1712           if (Argument *A = dyn_cast<Argument>(V)) {
1713             std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1714             if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1715           }
1716
1717   while (!ForwardReferences.empty()) {
1718     std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1719       ForwardReferences.begin();
1720     Value *PlaceHolder = I->second;
1721     ForwardReferences.erase(I);
1722
1723     // Now that all the uses are gone, delete the placeholder...
1724     // If we couldn't find a def (error case), then leak a little
1725     // memory, because otherwise we can't remove all uses!
1726     delete PlaceHolder;
1727   }
1728
1729   // Clear out function-level types...
1730   FunctionTypes.clear();
1731   CompactionTypes.clear();
1732   CompactionValues.clear();
1733   freeTable(FunctionValues);
1734
1735   if (Handler) Handler->handleFunctionEnd(F);
1736 }
1737
1738 /// This function parses LLVM functions lazily. It obtains the type of the
1739 /// function and records where the body of the function is in the bytecode
1740 /// buffer. The caller can then use the ParseNextFunction and 
1741 /// ParseAllFunctionBodies to get handler events for the functions.
1742 void BytecodeReader::ParseFunctionLazily() {
1743   if (FunctionSignatureList.empty())
1744     error("FunctionSignatureList empty!");
1745
1746   Function *Func = FunctionSignatureList.back();
1747   FunctionSignatureList.pop_back();
1748
1749   // Save the information for future reading of the function
1750   LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1751
1752   // This function has a body but it's not loaded so it appears `External'.
1753   // Mark it as a `Ghost' instead to notify the users that it has a body.
1754   Func->setLinkage(GlobalValue::GhostLinkage);
1755
1756   // Pretend we've `parsed' this function
1757   At = BlockEnd;
1758 }
1759
1760 /// The ParserFunction method lazily parses one function. Use this method to 
1761 /// casue the parser to parse a specific function in the module. Note that 
1762 /// this will remove the function from what is to be included by 
1763 /// ParseAllFunctionBodies.
1764 /// @see ParseAllFunctionBodies
1765 /// @see ParseBytecode
1766 void BytecodeReader::ParseFunction(Function* Func) {
1767   // Find {start, end} pointers and slot in the map. If not there, we're done.
1768   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1769
1770   // Make sure we found it
1771   if (Fi == LazyFunctionLoadMap.end()) {
1772     error("Unrecognized function of type " + Func->getType()->getDescription());
1773     return;
1774   }
1775
1776   BlockStart = At = Fi->second.Buf;
1777   BlockEnd = Fi->second.EndBuf;
1778   assert(Fi->first == Func && "Found wrong function?");
1779
1780   LazyFunctionLoadMap.erase(Fi);
1781
1782   this->ParseFunctionBody(Func);
1783 }
1784
1785 /// The ParseAllFunctionBodies method parses through all the previously
1786 /// unparsed functions in the bytecode file. If you want to completely parse
1787 /// a bytecode file, this method should be called after Parsebytecode because
1788 /// Parsebytecode only records the locations in the bytecode file of where
1789 /// the function definitions are located. This function uses that information
1790 /// to materialize the functions.
1791 /// @see ParseBytecode
1792 void BytecodeReader::ParseAllFunctionBodies() {
1793   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1794   LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1795
1796   while (Fi != Fe) {
1797     Function* Func = Fi->first;
1798     BlockStart = At = Fi->second.Buf;
1799     BlockEnd = Fi->second.EndBuf;
1800     this->ParseFunctionBody(Func);
1801     ++Fi;
1802   }
1803 }
1804
1805 /// Parse the global type list
1806 void BytecodeReader::ParseGlobalTypes() {
1807   // Read the number of types
1808   unsigned NumEntries = read_vbr_uint();
1809
1810   // Ignore the type plane identifier for types if the bc file is pre 1.3
1811   if (hasTypeDerivedFromValue)
1812     read_vbr_uint();
1813
1814   ParseTypes(ModuleTypes, NumEntries);
1815 }
1816
1817 /// Parse the Global info (types, global vars, constants)
1818 void BytecodeReader::ParseModuleGlobalInfo() {
1819
1820   if (Handler) Handler->handleModuleGlobalsBegin();
1821
1822   // Read global variables...
1823   unsigned VarType = read_vbr_uint();
1824   while (VarType != Type::VoidTyID) { // List is terminated by Void
1825     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1826     // Linkage, bit4+ = slot#
1827     unsigned SlotNo = VarType >> 5;
1828     if (sanitizeTypeId(SlotNo))
1829       error("Invalid type (type type) for global var!");
1830     unsigned LinkageID = (VarType >> 2) & 7;
1831     bool isConstant = VarType & 1;
1832     bool hasInitializer = VarType & 2;
1833     GlobalValue::LinkageTypes Linkage;
1834
1835     switch (LinkageID) {
1836     case 0: Linkage = GlobalValue::ExternalLinkage;  break;
1837     case 1: Linkage = GlobalValue::WeakLinkage;      break;
1838     case 2: Linkage = GlobalValue::AppendingLinkage; break;
1839     case 3: Linkage = GlobalValue::InternalLinkage;  break;
1840     case 4: Linkage = GlobalValue::LinkOnceLinkage;  break;
1841     default: 
1842       error("Unknown linkage type: " + utostr(LinkageID));
1843       Linkage = GlobalValue::InternalLinkage;
1844       break;
1845     }
1846
1847     const Type *Ty = getType(SlotNo);
1848     if (!Ty) {
1849       error("Global has no type! SlotNo=" + utostr(SlotNo));
1850     }
1851
1852     if (!isa<PointerType>(Ty)) {
1853       error("Global not a pointer type! Ty= " + Ty->getDescription());
1854     }
1855
1856     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1857
1858     // Create the global variable...
1859     GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1860                                             0, "", TheModule);
1861     insertValue(GV, SlotNo, ModuleValues);
1862
1863     unsigned initSlot = 0;
1864     if (hasInitializer) {   
1865       initSlot = read_vbr_uint();
1866       GlobalInits.push_back(std::make_pair(GV, initSlot));
1867     }
1868
1869     // Notify handler about the global value.
1870     if (Handler)
1871       Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1872
1873     // Get next item
1874     VarType = read_vbr_uint();
1875   }
1876
1877   // Read the function objects for all of the functions that are coming
1878   unsigned FnSignature = read_vbr_uint();
1879
1880   if (hasNoFlagsForFunctions)
1881     FnSignature = (FnSignature << 5) + 1;
1882
1883   // List is terminated by VoidTy.
1884   while ((FnSignature >> 5) != Type::VoidTyID) {
1885     const Type *Ty = getType(FnSignature >> 5);
1886     if (!isa<PointerType>(Ty) ||
1887         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1888       error("Function not a pointer to function type! Ty = " + 
1889             Ty->getDescription());
1890     }
1891
1892     // We create functions by passing the underlying FunctionType to create...
1893     const FunctionType* FTy = 
1894       cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1895
1896
1897     // Insert the place holder.
1898     Function* Func = new Function(FTy, GlobalValue::ExternalLinkage, 
1899                                   "", TheModule);
1900     insertValue(Func, FnSignature >> 5, ModuleValues);
1901
1902     // Flags are not used yet.
1903     unsigned Flags = FnSignature & 31;
1904
1905     // Save this for later so we know type of lazily instantiated functions.
1906     // Note that known-external functions do not have FunctionInfo blocks, so we
1907     // do not add them to the FunctionSignatureList.
1908     if ((Flags & (1 << 4)) == 0)
1909       FunctionSignatureList.push_back(Func);
1910
1911     if (Handler) Handler->handleFunctionDeclaration(Func);
1912
1913     // Get the next function signature.
1914     FnSignature = read_vbr_uint();
1915     if (hasNoFlagsForFunctions)
1916       FnSignature = (FnSignature << 5) + 1;
1917   }
1918
1919   // Now that the function signature list is set up, reverse it so that we can 
1920   // remove elements efficiently from the back of the vector.
1921   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1922
1923   // If this bytecode format has dependent library information in it ..
1924   if (!hasNoDependentLibraries) {
1925     // Read in the number of dependent library items that follow
1926     unsigned num_dep_libs = read_vbr_uint();
1927     std::string dep_lib;
1928     while( num_dep_libs-- ) {
1929       dep_lib = read_str();
1930       TheModule->addLibrary(dep_lib);
1931       if (Handler)
1932         Handler->handleDependentLibrary(dep_lib);
1933     }
1934
1935
1936     // Read target triple and place into the module
1937     std::string triple = read_str();
1938     TheModule->setTargetTriple(triple);
1939     if (Handler)
1940       Handler->handleTargetTriple(triple);
1941   }
1942
1943   if (hasInconsistentModuleGlobalInfo)
1944     align32();
1945
1946   // This is for future proofing... in the future extra fields may be added that
1947   // we don't understand, so we transparently ignore them.
1948   //
1949   At = BlockEnd;
1950
1951   if (Handler) Handler->handleModuleGlobalsEnd();
1952 }
1953
1954 /// Parse the version information and decode it by setting flags on the
1955 /// Reader that enable backward compatibility of the reader.
1956 void BytecodeReader::ParseVersionInfo() {
1957   unsigned Version = read_vbr_uint();
1958
1959   // Unpack version number: low four bits are for flags, top bits = version
1960   Module::Endianness  Endianness;
1961   Module::PointerSize PointerSize;
1962   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1963   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1964
1965   bool hasNoEndianness = Version & 4;
1966   bool hasNoPointerSize = Version & 8;
1967   
1968   RevisionNum = Version >> 4;
1969
1970   // Default values for the current bytecode version
1971   hasInconsistentModuleGlobalInfo = false;
1972   hasExplicitPrimitiveZeros = false;
1973   hasRestrictedGEPTypes = false;
1974   hasTypeDerivedFromValue = false;
1975   hasLongBlockHeaders = false;
1976   has32BitTypes = false;
1977   hasNoDependentLibraries = false;
1978   hasAlignment = false;
1979   hasInconsistentBBSlotNums = false;
1980   hasVBRByteTypes = false;
1981   hasUnnecessaryModuleBlockId = false;
1982   hasNoUndefValue = false;
1983   hasNoFlagsForFunctions = false;
1984   hasNoUnreachableInst = false;
1985
1986   switch (RevisionNum) {
1987   case 0:               //  LLVM 1.0, 1.1 (Released)
1988     // Base LLVM 1.0 bytecode format.
1989     hasInconsistentModuleGlobalInfo = true;
1990     hasExplicitPrimitiveZeros = true;
1991
1992     // FALL THROUGH
1993
1994   case 1:               // LLVM 1.2 (Released)
1995     // LLVM 1.2 added explicit support for emitting strings efficiently.
1996
1997     // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1998     // included the size for the alignment at the end, where the rest of the
1999     // blocks did not.
2000
2001     // LLVM 1.2 and before required that GEP indices be ubyte constants for
2002     // structures and longs for sequential types.
2003     hasRestrictedGEPTypes = true;
2004
2005     // LLVM 1.2 and before had the Type class derive from Value class. This
2006     // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
2007     // written differently because Types can no longer be part of the 
2008     // type planes for Values.
2009     hasTypeDerivedFromValue = true;
2010
2011     // FALL THROUGH
2012     
2013   case 2:                // 1.2.5 (Not Released)
2014
2015     // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
2016     // especially for small files where the 8 bytes per block is a large
2017     // fraction of the total block size. In LLVM 1.3, the block type and length
2018     // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2019     // 5 bits for block type.
2020     hasLongBlockHeaders = true;
2021
2022     // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
2023     // this has been reduced to vbr_uint24. It shouldn't make much difference
2024     // since we haven't run into a module with > 24 million types, but for
2025     // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2026     // in various places and to ensure consistency.
2027     has32BitTypes = true;
2028
2029     // LLVM 1.2 and earlier did not provide a target triple nor a list of 
2030     // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2031     // features, for use in future versions of LLVM.
2032     hasNoDependentLibraries = true;
2033
2034     // FALL THROUGH
2035
2036   case 3:               // LLVM 1.3 (Released)
2037     // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2038     // boundaries and at the end of some strings. In extreme cases (e.g. lots 
2039     // of GEP references to a constant array), this can increase the file size
2040     // by 30% or more. In version 1.4 alignment is done away with completely.
2041     hasAlignment = true;
2042
2043     // FALL THROUGH
2044     
2045   case 4:               // 1.3.1 (Not Released)
2046     // In version 4, we did not support the 'undef' constant.
2047     hasNoUndefValue = true;
2048
2049     // In version 4 and above, we did not include space for flags for functions
2050     // in the module info block.
2051     hasNoFlagsForFunctions = true;
2052
2053     // In version 4 and above, we did not include the 'unreachable' instruction
2054     // in the opcode numbering in the bytecode file.
2055     hasNoUnreachableInst = true;
2056     break;
2057
2058     // FALL THROUGH
2059
2060   case 5:               // 1.x.x (Not Released)
2061     break;
2062     // FIXME: NONE of this is implemented yet!
2063
2064     // In version 5, basic blocks have a minimum index of 0 whereas all the 
2065     // other primitives have a minimum index of 1 (because 0 is the "null" 
2066     // value. In version 5, we made this consistent.
2067     hasInconsistentBBSlotNums = true;
2068
2069     // In version 5, the types SByte and UByte were encoded as vbr_uint so that
2070     // signed values > 63 and unsigned values >127 would be encoded as two
2071     // bytes. In version 5, they are encoded directly in a single byte.
2072     hasVBRByteTypes = true;
2073
2074     // In version 5, modules begin with a "Module Block" which encodes a 4-byte
2075     // integer value 0x01 to identify the module block. This is unnecessary and
2076     // removed in version 5.
2077     hasUnnecessaryModuleBlockId = true;
2078
2079   default:
2080     error("Unknown bytecode version number: " + itostr(RevisionNum));
2081   }
2082
2083   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
2084   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2085
2086   TheModule->setEndianness(Endianness);
2087   TheModule->setPointerSize(PointerSize);
2088
2089   if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2090 }
2091
2092 /// Parse a whole module.
2093 void BytecodeReader::ParseModule() {
2094   unsigned Type, Size;
2095
2096   FunctionSignatureList.clear(); // Just in case...
2097
2098   // Read into instance variables...
2099   ParseVersionInfo();
2100   align32();
2101
2102   bool SeenModuleGlobalInfo = false;
2103   bool SeenGlobalTypePlane = false;
2104   BufPtr MyEnd = BlockEnd;
2105   while (At < MyEnd) {
2106     BufPtr OldAt = At;
2107     read_block(Type, Size);
2108
2109     switch (Type) {
2110
2111     case BytecodeFormat::GlobalTypePlaneBlockID:
2112       if (SeenGlobalTypePlane)
2113         error("Two GlobalTypePlane Blocks Encountered!");
2114
2115       if (Size > 0)
2116         ParseGlobalTypes();
2117       SeenGlobalTypePlane = true;
2118       break;
2119
2120     case BytecodeFormat::ModuleGlobalInfoBlockID: 
2121       if (SeenModuleGlobalInfo)
2122         error("Two ModuleGlobalInfo Blocks Encountered!");
2123       ParseModuleGlobalInfo();
2124       SeenModuleGlobalInfo = true;
2125       break;
2126
2127     case BytecodeFormat::ConstantPoolBlockID:
2128       ParseConstantPool(ModuleValues, ModuleTypes,false);
2129       break;
2130
2131     case BytecodeFormat::FunctionBlockID:
2132       ParseFunctionLazily();
2133       break;
2134
2135     case BytecodeFormat::SymbolTableBlockID:
2136       ParseSymbolTable(0, &TheModule->getSymbolTable());
2137       break;
2138
2139     default:
2140       At += Size;
2141       if (OldAt > At) {
2142         error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2143       }
2144       break;
2145     }
2146     BlockEnd = MyEnd;
2147     align32();
2148   }
2149
2150   // After the module constant pool has been read, we can safely initialize
2151   // global variables...
2152   while (!GlobalInits.empty()) {
2153     GlobalVariable *GV = GlobalInits.back().first;
2154     unsigned Slot = GlobalInits.back().second;
2155     GlobalInits.pop_back();
2156
2157     // Look up the initializer value...
2158     // FIXME: Preserve this type ID!
2159
2160     const llvm::PointerType* GVType = GV->getType();
2161     unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2162     if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2163       if (GV->hasInitializer()) 
2164         error("Global *already* has an initializer?!");
2165       if (Handler) Handler->handleGlobalInitializer(GV,CV);
2166       GV->setInitializer(CV);
2167     } else
2168       error("Cannot find initializer value.");
2169   }
2170
2171   /// Make sure we pulled them all out. If we didn't then there's a declaration
2172   /// but a missing body. That's not allowed.
2173   if (!FunctionSignatureList.empty())
2174     error("Function declared, but bytecode stream ended before definition");
2175 }
2176
2177 /// This function completely parses a bytecode buffer given by the \p Buf
2178 /// and \p Length parameters.
2179 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length, 
2180                                    const std::string &ModuleID) {
2181
2182   try {
2183     RevisionNum = 0;
2184     At = MemStart = BlockStart = Buf;
2185     MemEnd = BlockEnd = Buf + Length;
2186
2187     // Create the module
2188     TheModule = new Module(ModuleID);
2189
2190     if (Handler) Handler->handleStart(TheModule, Length);
2191
2192     // Read the four bytes of the signature.
2193     unsigned Sig = read_uint();
2194
2195     // If this is a compressed file
2196     if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2197
2198       // Invoke the decompression of the bytecode. Note that we have to skip the
2199       // file's magic number which is not part of the compressed block. Hence,
2200       // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2201       // member for retention until BytecodeReader is destructed.
2202       unsigned decompressedLength = Compressor::decompressToNewBuffer(
2203           (char*)Buf+4,Length-4,decompressedBlock);
2204
2205       // We must adjust the buffer pointers used by the bytecode reader to point
2206       // into the new decompressed block. After decompression, the
2207       // decompressedBlock will point to a contiguous memory area that has
2208       // the decompressed data.
2209       At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2210       MemEnd = BlockEnd = Buf + decompressedLength;
2211
2212     // else if this isn't a regular (uncompressed) bytecode file, then its
2213     // and error, generate that now.
2214     } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2215       error("Invalid bytecode signature: " + utohexstr(Sig));
2216     }
2217
2218     // Tell the handler we're starting a module
2219     if (Handler) Handler->handleModuleBegin(ModuleID);
2220
2221     // Get the module block and size and verify. This is handled specially
2222     // because the module block/size is always written in long format. Other
2223     // blocks are written in short format so the read_block method is used.
2224     unsigned Type, Size;
2225     Type = read_uint();
2226     Size = read_uint();
2227     if (Type != BytecodeFormat::ModuleBlockID) {
2228       error("Expected Module Block! Type:" + utostr(Type) + ", Size:" 
2229             + utostr(Size));
2230     }
2231
2232     // It looks like the darwin ranlib program is broken, and adds trailing
2233     // garbage to the end of some bytecode files.  This hack allows the bc
2234     // reader to ignore trailing garbage on bytecode files.
2235     if (At + Size < MemEnd)
2236       MemEnd = BlockEnd = At+Size;
2237
2238     if (At + Size != MemEnd)
2239       error("Invalid Top Level Block Length! Type:" + utostr(Type)
2240             + ", Size:" + utostr(Size));
2241
2242     // Parse the module contents
2243     this->ParseModule();
2244
2245     // Check for missing functions
2246     if (hasFunctions())
2247       error("Function expected, but bytecode stream ended!");
2248
2249     // Tell the handler we're done with the module
2250     if (Handler) 
2251       Handler->handleModuleEnd(ModuleID);
2252
2253     // Tell the handler we're finished the parse
2254     if (Handler) Handler->handleFinish();
2255
2256   } catch (std::string& errstr) {
2257     if (Handler) Handler->handleError(errstr);
2258     freeState();
2259     delete TheModule;
2260     TheModule = 0;
2261     if (decompressedBlock != 0 ) {
2262       ::free(decompressedBlock);
2263       decompressedBlock = 0;
2264     }
2265     throw;
2266   } catch (...) {
2267     std::string msg("Unknown Exception Occurred");
2268     if (Handler) Handler->handleError(msg);
2269     freeState();
2270     delete TheModule;
2271     TheModule = 0;
2272     if (decompressedBlock != 0) {
2273       ::free(decompressedBlock);
2274       decompressedBlock = 0;
2275     }
2276     throw msg;
2277   }
2278 }
2279
2280 //===----------------------------------------------------------------------===//
2281 //=== Default Implementations of Handler Methods
2282 //===----------------------------------------------------------------------===//
2283
2284 BytecodeHandler::~BytecodeHandler() {}
2285
2286 // vim: sw=2