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