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