Changes necessary to enable linking of archives without LLVM symbol tables.
[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...
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   checkPastBlockEnd("Constant Pool");
1572   if (Handler) Handler->handleGlobalConstantsEnd();
1573 }
1574
1575 /// Parse the contents of a function. Note that this function can be
1576 /// called lazily by materializeFunction
1577 /// @see materializeFunction
1578 void BytecodeReader::ParseFunctionBody(Function* F) {
1579
1580   unsigned FuncSize = BlockEnd - At;
1581   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1582
1583   unsigned LinkageType = read_vbr_uint();
1584   switch (LinkageType) {
1585   case 0: Linkage = GlobalValue::ExternalLinkage; break;
1586   case 1: Linkage = GlobalValue::WeakLinkage; break;
1587   case 2: Linkage = GlobalValue::AppendingLinkage; break;
1588   case 3: Linkage = GlobalValue::InternalLinkage; break;
1589   case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1590   default:
1591     error("Invalid linkage type for Function.");
1592     Linkage = GlobalValue::InternalLinkage;
1593     break;
1594   }
1595
1596   F->setLinkage(Linkage);
1597   if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1598
1599   // Keep track of how many basic blocks we have read in...
1600   unsigned BlockNum = 0;
1601   bool InsertedArguments = false;
1602
1603   BufPtr MyEnd = BlockEnd;
1604   while (At < MyEnd) {
1605     unsigned Type, Size;
1606     BufPtr OldAt = At;
1607     read_block(Type, Size);
1608
1609     switch (Type) {
1610     case BytecodeFormat::ConstantPoolBlockID:
1611       if (!InsertedArguments) {
1612         // Insert arguments into the value table before we parse the first basic
1613         // block in the function, but after we potentially read in the
1614         // compaction table.
1615         insertArguments(F);
1616         InsertedArguments = true;
1617       }
1618
1619       ParseConstantPool(FunctionValues, FunctionTypes, true);
1620       break;
1621
1622     case BytecodeFormat::CompactionTableBlockID:
1623       ParseCompactionTable();
1624       break;
1625
1626     case BytecodeFormat::BasicBlock: {
1627       if (!InsertedArguments) {
1628         // Insert arguments into the value table before we parse the first basic
1629         // block in the function, but after we potentially read in the
1630         // compaction table.
1631         insertArguments(F);
1632         InsertedArguments = true;
1633       }
1634
1635       BasicBlock *BB = ParseBasicBlock(BlockNum++);
1636       F->getBasicBlockList().push_back(BB);
1637       break;
1638     }
1639
1640     case BytecodeFormat::InstructionListBlockID: {
1641       // Insert arguments into the value table before we parse the instruction
1642       // list for the function, but after we potentially read in the compaction
1643       // table.
1644       if (!InsertedArguments) {
1645         insertArguments(F);
1646         InsertedArguments = true;
1647       }
1648
1649       if (BlockNum) 
1650         error("Already parsed basic blocks!");
1651       BlockNum = ParseInstructionList(F);
1652       break;
1653     }
1654
1655     case BytecodeFormat::SymbolTableBlockID:
1656       ParseSymbolTable(F, &F->getSymbolTable());
1657       break;
1658
1659     default:
1660       At += Size;
1661       if (OldAt > At) 
1662         error("Wrapped around reading bytecode.");
1663       break;
1664     }
1665     BlockEnd = MyEnd;
1666
1667     // Malformed bc file if read past end of block.
1668     align32();
1669   }
1670
1671   // Make sure there were no references to non-existant basic blocks.
1672   if (BlockNum != ParsedBasicBlocks.size())
1673     error("Illegal basic block operand reference");
1674
1675   ParsedBasicBlocks.clear();
1676
1677   // Resolve forward references.  Replace any uses of a forward reference value
1678   // with the real value.
1679
1680   // replaceAllUsesWith is very inefficient for instructions which have a LARGE
1681   // number of operands.  PHI nodes often have forward references, and can also
1682   // often have a very large number of operands.
1683   //
1684   // FIXME: REEVALUATE.  replaceAllUsesWith is _much_ faster now, and this code
1685   // should be simplified back to using it!
1686   //
1687   std::map<Value*, Value*> ForwardRefMapping;
1688   for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator 
1689          I = ForwardReferences.begin(), E = ForwardReferences.end();
1690        I != E; ++I)
1691     ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
1692                                             false);
1693
1694   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1695     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1696       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1697         if (Value* V = I->getOperand(i))
1698           if (Argument *A = dyn_cast<Argument>(V)) {
1699             std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
1700             if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
1701           }
1702
1703   while (!ForwardReferences.empty()) {
1704     std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
1705       ForwardReferences.begin();
1706     Value *PlaceHolder = I->second;
1707     ForwardReferences.erase(I);
1708
1709     // Now that all the uses are gone, delete the placeholder...
1710     // If we couldn't find a def (error case), then leak a little
1711     // memory, because otherwise we can't remove all uses!
1712     delete PlaceHolder;
1713   }
1714
1715   // Clear out function-level types...
1716   FunctionTypes.clear();
1717   CompactionTypes.clear();
1718   CompactionValues.clear();
1719   freeTable(FunctionValues);
1720
1721   if (Handler) Handler->handleFunctionEnd(F);
1722 }
1723
1724 /// This function parses LLVM functions lazily. It obtains the type of the
1725 /// function and records where the body of the function is in the bytecode
1726 /// buffer. The caller can then use the ParseNextFunction and 
1727 /// ParseAllFunctionBodies to get handler events for the functions.
1728 void BytecodeReader::ParseFunctionLazily() {
1729   if (FunctionSignatureList.empty())
1730     error("FunctionSignatureList empty!");
1731
1732   Function *Func = FunctionSignatureList.back();
1733   FunctionSignatureList.pop_back();
1734
1735   // Save the information for future reading of the function
1736   LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1737
1738   // This function has a body but it's not loaded so it appears `External'.
1739   // Mark it as a `Ghost' instead to notify the users that it has a body.
1740   Func->setLinkage(GlobalValue::GhostLinkage);
1741
1742   // Pretend we've `parsed' this function
1743   At = BlockEnd;
1744 }
1745
1746 /// The ParserFunction method lazily parses one function. Use this method to 
1747 /// casue the parser to parse a specific function in the module. Note that 
1748 /// this will remove the function from what is to be included by 
1749 /// ParseAllFunctionBodies.
1750 /// @see ParseAllFunctionBodies
1751 /// @see ParseBytecode
1752 void BytecodeReader::ParseFunction(Function* Func) {
1753   // Find {start, end} pointers and slot in the map. If not there, we're done.
1754   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1755
1756   // Make sure we found it
1757   if (Fi == LazyFunctionLoadMap.end()) {
1758     error("Unrecognized function of type " + Func->getType()->getDescription());
1759     return;
1760   }
1761
1762   BlockStart = At = Fi->second.Buf;
1763   BlockEnd = Fi->second.EndBuf;
1764   assert(Fi->first == Func && "Found wrong function?");
1765
1766   LazyFunctionLoadMap.erase(Fi);
1767
1768   this->ParseFunctionBody(Func);
1769 }
1770
1771 /// The ParseAllFunctionBodies method parses through all the previously
1772 /// unparsed functions in the bytecode file. If you want to completely parse
1773 /// a bytecode file, this method should be called after Parsebytecode because
1774 /// Parsebytecode only records the locations in the bytecode file of where
1775 /// the function definitions are located. This function uses that information
1776 /// to materialize the functions.
1777 /// @see ParseBytecode
1778 void BytecodeReader::ParseAllFunctionBodies() {
1779   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1780   LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1781
1782   while (Fi != Fe) {
1783     Function* Func = Fi->first;
1784     BlockStart = At = Fi->second.Buf;
1785     BlockEnd = Fi->second.EndBuf;
1786     this->ParseFunctionBody(Func);
1787     ++Fi;
1788   }
1789 }
1790
1791 /// Parse the global type list
1792 void BytecodeReader::ParseGlobalTypes() {
1793   // Read the number of types
1794   unsigned NumEntries = read_vbr_uint();
1795
1796   // Ignore the type plane identifier for types if the bc file is pre 1.3
1797   if (hasTypeDerivedFromValue)
1798     read_vbr_uint();
1799
1800   ParseTypes(ModuleTypes, NumEntries);
1801 }
1802
1803 /// Parse the Global info (types, global vars, constants)
1804 void BytecodeReader::ParseModuleGlobalInfo() {
1805
1806   if (Handler) Handler->handleModuleGlobalsBegin();
1807
1808   // Read global variables...
1809   unsigned VarType = read_vbr_uint();
1810   while (VarType != Type::VoidTyID) { // List is terminated by Void
1811     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1812     // Linkage, bit4+ = slot#
1813     unsigned SlotNo = VarType >> 5;
1814     if (sanitizeTypeId(SlotNo))
1815       error("Invalid type (type type) for global var!");
1816     unsigned LinkageID = (VarType >> 2) & 7;
1817     bool isConstant = VarType & 1;
1818     bool hasInitializer = VarType & 2;
1819     GlobalValue::LinkageTypes Linkage;
1820
1821     switch (LinkageID) {
1822     case 0: Linkage = GlobalValue::ExternalLinkage;  break;
1823     case 1: Linkage = GlobalValue::WeakLinkage;      break;
1824     case 2: Linkage = GlobalValue::AppendingLinkage; break;
1825     case 3: Linkage = GlobalValue::InternalLinkage;  break;
1826     case 4: Linkage = GlobalValue::LinkOnceLinkage;  break;
1827     default: 
1828       error("Unknown linkage type: " + utostr(LinkageID));
1829       Linkage = GlobalValue::InternalLinkage;
1830       break;
1831     }
1832
1833     const Type *Ty = getType(SlotNo);
1834     if (!Ty) {
1835       error("Global has no type! SlotNo=" + utostr(SlotNo));
1836     }
1837
1838     if (!isa<PointerType>(Ty)) {
1839       error("Global not a pointer type! Ty= " + Ty->getDescription());
1840     }
1841
1842     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1843
1844     // Create the global variable...
1845     GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1846                                             0, "", TheModule);
1847     insertValue(GV, SlotNo, ModuleValues);
1848
1849     unsigned initSlot = 0;
1850     if (hasInitializer) {   
1851       initSlot = read_vbr_uint();
1852       GlobalInits.push_back(std::make_pair(GV, initSlot));
1853     }
1854
1855     // Notify handler about the global value.
1856     if (Handler)
1857       Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1858
1859     // Get next item
1860     VarType = read_vbr_uint();
1861   }
1862
1863   // Read the function objects for all of the functions that are coming
1864   unsigned FnSignature = read_vbr_uint();
1865
1866   if (hasNoFlagsForFunctions)
1867     FnSignature = (FnSignature << 5) + 1;
1868
1869   // List is terminated by VoidTy.
1870   while ((FnSignature >> 5) != Type::VoidTyID) {
1871     const Type *Ty = getType(FnSignature >> 5);
1872     if (!isa<PointerType>(Ty) ||
1873         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1874       error("Function not a pointer to function type! Ty = " + 
1875             Ty->getDescription());
1876     }
1877
1878     // We create functions by passing the underlying FunctionType to create...
1879     const FunctionType* FTy = 
1880       cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1881
1882
1883     // Insert the place hodler
1884     Function* Func = new Function(FTy, GlobalValue::InternalLinkage, 
1885                                   "", TheModule);
1886     insertValue(Func, FnSignature >> 5, ModuleValues);
1887
1888     // Flags are not used yet.
1889     //unsigned Flags = FnSignature & 31;
1890
1891     // Save this for later so we know type of lazily instantiated functions
1892     FunctionSignatureList.push_back(Func);
1893
1894     if (Handler) Handler->handleFunctionDeclaration(Func);
1895
1896     // Get the next function signature.
1897     FnSignature = read_vbr_uint();
1898     if (hasNoFlagsForFunctions)
1899       FnSignature = (FnSignature << 5) + 1;
1900   }
1901
1902   // Now that the function signature list is set up, reverse it so that we can 
1903   // remove elements efficiently from the back of the vector.
1904   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1905
1906   // If this bytecode format has dependent library information in it ..
1907   if (!hasNoDependentLibraries) {
1908     // Read in the number of dependent library items that follow
1909     unsigned num_dep_libs = read_vbr_uint();
1910     std::string dep_lib;
1911     while( num_dep_libs-- ) {
1912       dep_lib = read_str();
1913       TheModule->addLibrary(dep_lib);
1914       if (Handler)
1915         Handler->handleDependentLibrary(dep_lib);
1916     }
1917
1918
1919     // Read target triple and place into the module
1920     std::string triple = read_str();
1921     TheModule->setTargetTriple(triple);
1922     if (Handler)
1923       Handler->handleTargetTriple(triple);
1924   }
1925
1926   if (hasInconsistentModuleGlobalInfo)
1927     align32();
1928
1929   // This is for future proofing... in the future extra fields may be added that
1930   // we don't understand, so we transparently ignore them.
1931   //
1932   At = BlockEnd;
1933
1934   if (Handler) Handler->handleModuleGlobalsEnd();
1935 }
1936
1937 /// Parse the version information and decode it by setting flags on the
1938 /// Reader that enable backward compatibility of the reader.
1939 void BytecodeReader::ParseVersionInfo() {
1940   unsigned Version = read_vbr_uint();
1941
1942   // Unpack version number: low four bits are for flags, top bits = version
1943   Module::Endianness  Endianness;
1944   Module::PointerSize PointerSize;
1945   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
1946   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
1947
1948   bool hasNoEndianness = Version & 4;
1949   bool hasNoPointerSize = Version & 8;
1950   
1951   RevisionNum = Version >> 4;
1952
1953   // Default values for the current bytecode version
1954   hasInconsistentModuleGlobalInfo = false;
1955   hasExplicitPrimitiveZeros = false;
1956   hasRestrictedGEPTypes = false;
1957   hasTypeDerivedFromValue = false;
1958   hasLongBlockHeaders = false;
1959   has32BitTypes = false;
1960   hasNoDependentLibraries = false;
1961   hasAlignment = false;
1962   hasInconsistentBBSlotNums = false;
1963   hasVBRByteTypes = false;
1964   hasUnnecessaryModuleBlockId = false;
1965   hasNoUndefValue = false;
1966   hasNoFlagsForFunctions = false;
1967   hasNoUnreachableInst = false;
1968
1969   switch (RevisionNum) {
1970   case 0:               //  LLVM 1.0, 1.1 (Released)
1971     // Base LLVM 1.0 bytecode format.
1972     hasInconsistentModuleGlobalInfo = true;
1973     hasExplicitPrimitiveZeros = true;
1974
1975     // FALL THROUGH
1976
1977   case 1:               // LLVM 1.2 (Released)
1978     // LLVM 1.2 added explicit support for emitting strings efficiently.
1979
1980     // Also, it fixed the problem where the size of the ModuleGlobalInfo block
1981     // included the size for the alignment at the end, where the rest of the
1982     // blocks did not.
1983
1984     // LLVM 1.2 and before required that GEP indices be ubyte constants for
1985     // structures and longs for sequential types.
1986     hasRestrictedGEPTypes = true;
1987
1988     // LLVM 1.2 and before had the Type class derive from Value class. This
1989     // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
1990     // written differently because Types can no longer be part of the 
1991     // type planes for Values.
1992     hasTypeDerivedFromValue = true;
1993
1994     // FALL THROUGH
1995     
1996   case 2:                // 1.2.5 (Not Released)
1997
1998     // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
1999     // especially for small files where the 8 bytes per block is a large
2000     // fraction of the total block size. In LLVM 1.3, the block type and length
2001     // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2002     // 5 bits for block type.
2003     hasLongBlockHeaders = true;
2004
2005     // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
2006     // this has been reduced to vbr_uint24. It shouldn't make much difference
2007     // since we haven't run into a module with > 24 million types, but for
2008     // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2009     // in various places and to ensure consistency.
2010     has32BitTypes = true;
2011
2012     // LLVM 1.2 and earlier did not provide a target triple nor a list of 
2013     // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2014     // features, for use in future versions of LLVM.
2015     hasNoDependentLibraries = true;
2016
2017     // FALL THROUGH
2018
2019   case 3:               // LLVM 1.3 (Released)
2020     // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2021     // boundaries and at the end of some strings. In extreme cases (e.g. lots 
2022     // of GEP references to a constant array), this can increase the file size
2023     // by 30% or more. In version 1.4 alignment is done away with completely.
2024     hasAlignment = true;
2025
2026     // FALL THROUGH
2027     
2028   case 4:               // 1.3.1 (Not Released)
2029     // In version 4, we did not support the 'undef' constant.
2030     hasNoUndefValue = true;
2031
2032     // In version 4 and above, we did not include space for flags for functions
2033     // in the module info block.
2034     hasNoFlagsForFunctions = true;
2035
2036     // In version 4 and above, we did not include the 'unreachable' instruction
2037     // in the opcode numbering in the bytecode file.
2038     hasNoUnreachableInst = true;
2039     break;
2040
2041     // FALL THROUGH
2042
2043   case 5:               // 1.x.x (Not Released)
2044     break;
2045     // FIXME: NONE of this is implemented yet!
2046
2047     // In version 5, basic blocks have a minimum index of 0 whereas all the 
2048     // other primitives have a minimum index of 1 (because 0 is the "null" 
2049     // value. In version 5, we made this consistent.
2050     hasInconsistentBBSlotNums = true;
2051
2052     // In version 5, the types SByte and UByte were encoded as vbr_uint so that
2053     // signed values > 63 and unsigned values >127 would be encoded as two
2054     // bytes. In version 5, they are encoded directly in a single byte.
2055     hasVBRByteTypes = true;
2056
2057     // In version 5, modules begin with a "Module Block" which encodes a 4-byte
2058     // integer value 0x01 to identify the module block. This is unnecessary and
2059     // removed in version 5.
2060     hasUnnecessaryModuleBlockId = true;
2061
2062   default:
2063     error("Unknown bytecode version number: " + itostr(RevisionNum));
2064   }
2065
2066   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
2067   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2068
2069   TheModule->setEndianness(Endianness);
2070   TheModule->setPointerSize(PointerSize);
2071
2072   if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2073 }
2074
2075 /// Parse a whole module.
2076 void BytecodeReader::ParseModule() {
2077   unsigned Type, Size;
2078
2079   FunctionSignatureList.clear(); // Just in case...
2080
2081   // Read into instance variables...
2082   ParseVersionInfo();
2083   align32();
2084
2085   bool SeenModuleGlobalInfo = false;
2086   bool SeenGlobalTypePlane = false;
2087   BufPtr MyEnd = BlockEnd;
2088   while (At < MyEnd) {
2089     BufPtr OldAt = At;
2090     read_block(Type, Size);
2091
2092     switch (Type) {
2093
2094     case BytecodeFormat::GlobalTypePlaneBlockID:
2095       if (SeenGlobalTypePlane)
2096         error("Two GlobalTypePlane Blocks Encountered!");
2097
2098       if (Size > 0)
2099         ParseGlobalTypes();
2100       SeenGlobalTypePlane = true;
2101       break;
2102
2103     case BytecodeFormat::ModuleGlobalInfoBlockID: 
2104       if (SeenModuleGlobalInfo)
2105         error("Two ModuleGlobalInfo Blocks Encountered!");
2106       ParseModuleGlobalInfo();
2107       SeenModuleGlobalInfo = true;
2108       break;
2109
2110     case BytecodeFormat::ConstantPoolBlockID:
2111       ParseConstantPool(ModuleValues, ModuleTypes,false);
2112       break;
2113
2114     case BytecodeFormat::FunctionBlockID:
2115       ParseFunctionLazily();
2116       break;
2117
2118     case BytecodeFormat::SymbolTableBlockID:
2119       ParseSymbolTable(0, &TheModule->getSymbolTable());
2120       break;
2121
2122     default:
2123       At += Size;
2124       if (OldAt > At) {
2125         error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2126       }
2127       break;
2128     }
2129     BlockEnd = MyEnd;
2130     align32();
2131   }
2132
2133   // After the module constant pool has been read, we can safely initialize
2134   // global variables...
2135   while (!GlobalInits.empty()) {
2136     GlobalVariable *GV = GlobalInits.back().first;
2137     unsigned Slot = GlobalInits.back().second;
2138     GlobalInits.pop_back();
2139
2140     // Look up the initializer value...
2141     // FIXME: Preserve this type ID!
2142
2143     const llvm::PointerType* GVType = GV->getType();
2144     unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2145     if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2146       if (GV->hasInitializer()) 
2147         error("Global *already* has an initializer?!");
2148       if (Handler) Handler->handleGlobalInitializer(GV,CV);
2149       GV->setInitializer(CV);
2150     } else
2151       error("Cannot find initializer value.");
2152   }
2153
2154   /// Make sure we pulled them all out. If we didn't then there's a declaration
2155   /// but a missing body. That's not allowed.
2156   if (!FunctionSignatureList.empty())
2157     error("Function declared, but bytecode stream ended before definition");
2158 }
2159
2160 /// This function completely parses a bytecode buffer given by the \p Buf
2161 /// and \p Length parameters.
2162 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length, 
2163                                    const std::string &ModuleID) {
2164
2165   try {
2166     At = MemStart = BlockStart = Buf;
2167     MemEnd = BlockEnd = Buf + Length;
2168
2169     // Create the module
2170     TheModule = new Module(ModuleID);
2171
2172     if (Handler) Handler->handleStart(TheModule, Length);
2173
2174     // Read the four bytes of the signature.
2175     unsigned Sig = read_uint();
2176
2177     // If this is a compressed file
2178     if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2179
2180       // Invoke the decompression of the bytecode. Note that we have to skip the
2181       // file's magic number which is not part of the compressed block. Hence,
2182       // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2183       // member for retention until BytecodeReader is destructed.
2184       unsigned decompressedLength = Compressor::decompressToNewBuffer(
2185           (char*)Buf+4,Length-4,decompressedBlock);
2186
2187       // We must adjust the buffer pointers used by the bytecode reader to point
2188       // into the new decompressed block. After decompression, the
2189       // decompressedBlock will point to a contiguous memory area that has
2190       // the decompressed data.
2191       At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2192       MemEnd = BlockEnd = Buf + decompressedLength;
2193
2194     // else if this isn't a regular (uncompressed) bytecode file, then its
2195     // and error, generate that now.
2196     } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2197       error("Invalid bytecode signature: " + utohexstr(Sig));
2198     }
2199
2200     // Tell the handler we're starting a module
2201     if (Handler) Handler->handleModuleBegin(ModuleID);
2202
2203     // Get the module block and size and verify. This is handled specially
2204     // because the module block/size is always written in long format. Other
2205     // blocks are written in short format so the read_block method is used.
2206     unsigned Type, Size;
2207     Type = read_uint();
2208     Size = read_uint();
2209     if (Type != BytecodeFormat::ModuleBlockID) {
2210       error("Expected Module Block! Type:" + utostr(Type) + ", Size:" 
2211             + utostr(Size));
2212     }
2213
2214     // It looks like the darwin ranlib program is broken, and adds trailing
2215     // garbage to the end of some bytecode files.  This hack allows the bc
2216     // reader to ignore trailing garbage on bytecode files.
2217     if (At + Size < MemEnd)
2218       MemEnd = BlockEnd = At+Size;
2219
2220     if (At + Size != MemEnd)
2221       error("Invalid Top Level Block Length! Type:" + utostr(Type)
2222             + ", Size:" + utostr(Size));
2223
2224     // Parse the module contents
2225     this->ParseModule();
2226
2227     // Check for missing functions
2228     if (hasFunctions())
2229       error("Function expected, but bytecode stream ended!");
2230
2231     // Tell the handler we're done with the module
2232     if (Handler) 
2233       Handler->handleModuleEnd(ModuleID);
2234
2235     // Tell the handler we're finished the parse
2236     if (Handler) Handler->handleFinish();
2237
2238   } catch (std::string& errstr) {
2239     if (Handler) Handler->handleError(errstr);
2240     freeState();
2241     delete TheModule;
2242     TheModule = 0;
2243     if (decompressedBlock != 0 )
2244       ::free(decompressedBlock);
2245     throw;
2246   } catch (...) {
2247     std::string msg("Unknown Exception Occurred");
2248     if (Handler) Handler->handleError(msg);
2249     freeState();
2250     delete TheModule;
2251     TheModule = 0;
2252     if (decompressedBlock != 0 )
2253       ::free(decompressedBlock);
2254     throw msg;
2255   }
2256 }
2257
2258 //===----------------------------------------------------------------------===//
2259 //=== Default Implementations of Handler Methods
2260 //===----------------------------------------------------------------------===//
2261
2262 BytecodeHandler::~BytecodeHandler() {}
2263
2264 // vim: sw=2