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