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