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