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