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