fix off-by-one that caused the llvm2cpp test to fail
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License.  See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitcodeReader class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/ParameterAttributes.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 using namespace llvm;
26
27 BitcodeReader::~BitcodeReader() {
28   delete Buffer;
29 }
30
31 //===----------------------------------------------------------------------===//
32 //  Helper functions to implement forward reference resolution, etc.
33 //===----------------------------------------------------------------------===//
34
35 /// ConvertToString - Convert a string from a record into an std::string, return
36 /// true on failure.
37 template<typename StrTy>
38 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
39                             StrTy &Result) {
40   if (Idx > Record.size())
41     return true;
42   
43   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
44     Result += (char)Record[i];
45   return false;
46 }
47
48 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
49   switch (Val) {
50   default: // Map unknown/new linkages to external
51   case 0: return GlobalValue::ExternalLinkage;
52   case 1: return GlobalValue::WeakLinkage;
53   case 2: return GlobalValue::AppendingLinkage;
54   case 3: return GlobalValue::InternalLinkage;
55   case 4: return GlobalValue::LinkOnceLinkage;
56   case 5: return GlobalValue::DLLImportLinkage;
57   case 6: return GlobalValue::DLLExportLinkage;
58   case 7: return GlobalValue::ExternalWeakLinkage;
59   }
60 }
61
62 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
63   switch (Val) {
64   default: // Map unknown visibilities to default.
65   case 0: return GlobalValue::DefaultVisibility;
66   case 1: return GlobalValue::HiddenVisibility;
67   case 2: return GlobalValue::ProtectedVisibility;
68   }
69 }
70
71 static int GetDecodedCastOpcode(unsigned Val) {
72   switch (Val) {
73   default: return -1;
74   case bitc::CAST_TRUNC   : return Instruction::Trunc;
75   case bitc::CAST_ZEXT    : return Instruction::ZExt;
76   case bitc::CAST_SEXT    : return Instruction::SExt;
77   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
78   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
79   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
80   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
81   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
82   case bitc::CAST_FPEXT   : return Instruction::FPExt;
83   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
84   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
85   case bitc::CAST_BITCAST : return Instruction::BitCast;
86   }
87 }
88 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
89   switch (Val) {
90   default: return -1;
91   case bitc::BINOP_ADD:  return Instruction::Add;
92   case bitc::BINOP_SUB:  return Instruction::Sub;
93   case bitc::BINOP_MUL:  return Instruction::Mul;
94   case bitc::BINOP_UDIV: return Instruction::UDiv;
95   case bitc::BINOP_SDIV:
96     return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
97   case bitc::BINOP_UREM: return Instruction::URem;
98   case bitc::BINOP_SREM:
99     return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
100   case bitc::BINOP_SHL:  return Instruction::Shl;
101   case bitc::BINOP_LSHR: return Instruction::LShr;
102   case bitc::BINOP_ASHR: return Instruction::AShr;
103   case bitc::BINOP_AND:  return Instruction::And;
104   case bitc::BINOP_OR:   return Instruction::Or;
105   case bitc::BINOP_XOR:  return Instruction::Xor;
106   }
107 }
108
109
110 namespace {
111   /// @brief A class for maintaining the slot number definition
112   /// as a placeholder for the actual definition for forward constants defs.
113   class ConstantPlaceHolder : public ConstantExpr {
114     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
115     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
116   public:
117     Use Op;
118     ConstantPlaceHolder(const Type *Ty)
119       : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
120         Op(UndefValue::get(Type::Int32Ty), this) {
121     }
122   };
123 }
124
125 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
126                                                     const Type *Ty) {
127   if (Idx >= size()) {
128     // Insert a bunch of null values.
129     Uses.resize(Idx+1);
130     OperandList = &Uses[0];
131     NumOperands = Idx+1;
132   }
133
134   if (Value *V = Uses[Idx]) {
135     assert(Ty == V->getType() && "Type mismatch in constant table!");
136     return cast<Constant>(V);
137   }
138
139   // Create and return a placeholder, which will later be RAUW'd.
140   Constant *C = new ConstantPlaceHolder(Ty);
141   Uses[Idx].init(C, this);
142   return C;
143 }
144
145 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
146   if (Idx >= size()) {
147     // Insert a bunch of null values.
148     Uses.resize(Idx+1);
149     OperandList = &Uses[0];
150     NumOperands = Idx+1;
151   }
152   
153   if (Value *V = Uses[Idx]) {
154     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
155     return V;
156   }
157   
158   // No type specified, must be invalid reference.
159   if (Ty == 0) return 0;
160   
161   // Create and return a placeholder, which will later be RAUW'd.
162   Value *V = new Argument(Ty);
163   Uses[Idx].init(V, this);
164   return V;
165 }
166
167
168 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
169   // If the TypeID is in range, return it.
170   if (ID < TypeList.size())
171     return TypeList[ID].get();
172   if (!isTypeTable) return 0;
173   
174   // The type table allows forward references.  Push as many Opaque types as
175   // needed to get up to ID.
176   while (TypeList.size() <= ID)
177     TypeList.push_back(OpaqueType::get());
178   return TypeList.back().get();
179 }
180
181 //===----------------------------------------------------------------------===//
182 //  Functions for parsing blocks from the bitcode file
183 //===----------------------------------------------------------------------===//
184
185 bool BitcodeReader::ParseParamAttrBlock() {
186   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
187     return Error("Malformed block record");
188   
189   if (!ParamAttrs.empty())
190     return Error("Multiple PARAMATTR blocks found!");
191   
192   SmallVector<uint64_t, 64> Record;
193   
194   ParamAttrsVector Attrs;
195   
196   // Read all the records.
197   while (1) {
198     unsigned Code = Stream.ReadCode();
199     if (Code == bitc::END_BLOCK) {
200       if (Stream.ReadBlockEnd())
201         return Error("Error at end of PARAMATTR block");
202       return false;
203     }
204     
205     if (Code == bitc::ENTER_SUBBLOCK) {
206       // No known subblocks, always skip them.
207       Stream.ReadSubBlockID();
208       if (Stream.SkipBlock())
209         return Error("Malformed block record");
210       continue;
211     }
212     
213     if (Code == bitc::DEFINE_ABBREV) {
214       Stream.ReadAbbrevRecord();
215       continue;
216     }
217     
218     // Read a record.
219     Record.clear();
220     switch (Stream.ReadRecord(Code, Record)) {
221     default:  // Default behavior: ignore.
222       break;
223     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
224       if (Record.size() & 1)
225         return Error("Invalid ENTRY record");
226
227       ParamAttrsWithIndex PAWI;
228       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
229         PAWI.index = Record[i];
230         PAWI.attrs = Record[i+1];
231         Attrs.push_back(PAWI);
232       }
233       ParamAttrs.push_back(ParamAttrsList::get(Attrs));
234       Attrs.clear();
235       break;
236     }
237     }    
238   }
239 }
240
241
242 bool BitcodeReader::ParseTypeTable() {
243   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
244     return Error("Malformed block record");
245   
246   if (!TypeList.empty())
247     return Error("Multiple TYPE_BLOCKs found!");
248
249   SmallVector<uint64_t, 64> Record;
250   unsigned NumRecords = 0;
251
252   // Read all the records for this type table.
253   while (1) {
254     unsigned Code = Stream.ReadCode();
255     if (Code == bitc::END_BLOCK) {
256       if (NumRecords != TypeList.size())
257         return Error("Invalid type forward reference in TYPE_BLOCK");
258       if (Stream.ReadBlockEnd())
259         return Error("Error at end of type table block");
260       return false;
261     }
262     
263     if (Code == bitc::ENTER_SUBBLOCK) {
264       // No known subblocks, always skip them.
265       Stream.ReadSubBlockID();
266       if (Stream.SkipBlock())
267         return Error("Malformed block record");
268       continue;
269     }
270     
271     if (Code == bitc::DEFINE_ABBREV) {
272       Stream.ReadAbbrevRecord();
273       continue;
274     }
275     
276     // Read a record.
277     Record.clear();
278     const Type *ResultTy = 0;
279     switch (Stream.ReadRecord(Code, Record)) {
280     default:  // Default behavior: unknown type.
281       ResultTy = 0;
282       break;
283     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
284       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
285       // type list.  This allows us to reserve space.
286       if (Record.size() < 1)
287         return Error("Invalid TYPE_CODE_NUMENTRY record");
288       TypeList.reserve(Record[0]);
289       continue;
290     case bitc::TYPE_CODE_VOID:      // VOID
291       ResultTy = Type::VoidTy;
292       break;
293     case bitc::TYPE_CODE_FLOAT:     // FLOAT
294       ResultTy = Type::FloatTy;
295       break;
296     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
297       ResultTy = Type::DoubleTy;
298       break;
299     case bitc::TYPE_CODE_LABEL:     // LABEL
300       ResultTy = Type::LabelTy;
301       break;
302     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
303       ResultTy = 0;
304       break;
305     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
306       if (Record.size() < 1)
307         return Error("Invalid Integer type record");
308       
309       ResultTy = IntegerType::get(Record[0]);
310       break;
311     case bitc::TYPE_CODE_POINTER:   // POINTER: [pointee type]
312       if (Record.size() < 1)
313         return Error("Invalid POINTER type record");
314       ResultTy = PointerType::get(getTypeByID(Record[0], true));
315       break;
316     case bitc::TYPE_CODE_FUNCTION: {
317       // FUNCTION: [vararg, attrid, retty, paramty x N]
318       if (Record.size() < 3)
319         return Error("Invalid FUNCTION type record");
320       std::vector<const Type*> ArgTys;
321       for (unsigned i = 3, e = Record.size(); i != e; ++i)
322         ArgTys.push_back(getTypeByID(Record[i], true));
323       
324       ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
325                                    Record[0], getParamAttrs(Record[1]));
326       break;
327     }
328     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
329       if (Record.size() < 1)
330         return Error("Invalid STRUCT type record");
331       std::vector<const Type*> EltTys;
332       for (unsigned i = 1, e = Record.size(); i != e; ++i)
333         EltTys.push_back(getTypeByID(Record[i], true));
334       ResultTy = StructType::get(EltTys, Record[0]);
335       break;
336     }
337     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
338       if (Record.size() < 2)
339         return Error("Invalid ARRAY type record");
340       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
341       break;
342     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
343       if (Record.size() < 2)
344         return Error("Invalid VECTOR type record");
345       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
346       break;
347     }
348     
349     if (NumRecords == TypeList.size()) {
350       // If this is a new type slot, just append it.
351       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
352       ++NumRecords;
353     } else if (ResultTy == 0) {
354       // Otherwise, this was forward referenced, so an opaque type was created,
355       // but the result type is actually just an opaque.  Leave the one we
356       // created previously.
357       ++NumRecords;
358     } else {
359       // Otherwise, this was forward referenced, so an opaque type was created.
360       // Resolve the opaque type to the real type now.
361       assert(NumRecords < TypeList.size() && "Typelist imbalance");
362       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
363      
364       // Don't directly push the new type on the Tab. Instead we want to replace
365       // the opaque type we previously inserted with the new concrete value. The
366       // refinement from the abstract (opaque) type to the new type causes all
367       // uses of the abstract type to use the concrete type (NewTy). This will
368       // also cause the opaque type to be deleted.
369       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
370       
371       // This should have replaced the old opaque type with the new type in the
372       // value table... or with a preexisting type that was already in the
373       // system.  Let's just make sure it did.
374       assert(TypeList[NumRecords-1].get() != OldTy &&
375              "refineAbstractType didn't work!");
376     }
377   }
378 }
379
380
381 bool BitcodeReader::ParseTypeSymbolTable() {
382   if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
383     return Error("Malformed block record");
384   
385   SmallVector<uint64_t, 64> Record;
386   
387   // Read all the records for this type table.
388   std::string TypeName;
389   while (1) {
390     unsigned Code = Stream.ReadCode();
391     if (Code == bitc::END_BLOCK) {
392       if (Stream.ReadBlockEnd())
393         return Error("Error at end of type symbol table block");
394       return false;
395     }
396     
397     if (Code == bitc::ENTER_SUBBLOCK) {
398       // No known subblocks, always skip them.
399       Stream.ReadSubBlockID();
400       if (Stream.SkipBlock())
401         return Error("Malformed block record");
402       continue;
403     }
404     
405     if (Code == bitc::DEFINE_ABBREV) {
406       Stream.ReadAbbrevRecord();
407       continue;
408     }
409     
410     // Read a record.
411     Record.clear();
412     switch (Stream.ReadRecord(Code, Record)) {
413     default:  // Default behavior: unknown type.
414       break;
415     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
416       if (ConvertToString(Record, 1, TypeName))
417         return Error("Invalid TST_ENTRY record");
418       unsigned TypeID = Record[0];
419       if (TypeID >= TypeList.size())
420         return Error("Invalid Type ID in TST_ENTRY record");
421
422       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
423       TypeName.clear();
424       break;
425     }
426   }
427 }
428
429 bool BitcodeReader::ParseValueSymbolTable() {
430   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
431     return Error("Malformed block record");
432
433   SmallVector<uint64_t, 64> Record;
434   
435   // Read all the records for this value table.
436   SmallString<128> ValueName;
437   while (1) {
438     unsigned Code = Stream.ReadCode();
439     if (Code == bitc::END_BLOCK) {
440       if (Stream.ReadBlockEnd())
441         return Error("Error at end of value symbol table block");
442       return false;
443     }    
444     if (Code == bitc::ENTER_SUBBLOCK) {
445       // No known subblocks, always skip them.
446       Stream.ReadSubBlockID();
447       if (Stream.SkipBlock())
448         return Error("Malformed block record");
449       continue;
450     }
451     
452     if (Code == bitc::DEFINE_ABBREV) {
453       Stream.ReadAbbrevRecord();
454       continue;
455     }
456     
457     // Read a record.
458     Record.clear();
459     switch (Stream.ReadRecord(Code, Record)) {
460     default:  // Default behavior: unknown type.
461       break;
462     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
463       if (ConvertToString(Record, 1, ValueName))
464         return Error("Invalid TST_ENTRY record");
465       unsigned ValueID = Record[0];
466       if (ValueID >= ValueList.size())
467         return Error("Invalid Value ID in VST_ENTRY record");
468       Value *V = ValueList[ValueID];
469       
470       V->setName(&ValueName[0], ValueName.size());
471       ValueName.clear();
472       break;
473     }
474     case bitc::VST_CODE_BBENTRY: {
475       if (ConvertToString(Record, 1, ValueName))
476         return Error("Invalid VST_BBENTRY record");
477       BasicBlock *BB = getBasicBlock(Record[0]);
478       if (BB == 0)
479         return Error("Invalid BB ID in VST_BBENTRY record");
480       
481       BB->setName(&ValueName[0], ValueName.size());
482       ValueName.clear();
483       break;
484     }
485     }
486   }
487 }
488
489 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
490 /// the LSB for dense VBR encoding.
491 static uint64_t DecodeSignRotatedValue(uint64_t V) {
492   if ((V & 1) == 0)
493     return V >> 1;
494   if (V != 1) 
495     return -(V >> 1);
496   // There is no such thing as -0 with integers.  "-0" really means MININT.
497   return 1ULL << 63;
498 }
499
500 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
501 /// values and aliases that we can.
502 bool BitcodeReader::ResolveGlobalAndAliasInits() {
503   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
504   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
505   
506   GlobalInitWorklist.swap(GlobalInits);
507   AliasInitWorklist.swap(AliasInits);
508
509   while (!GlobalInitWorklist.empty()) {
510     unsigned ValID = GlobalInitWorklist.back().second;
511     if (ValID >= ValueList.size()) {
512       // Not ready to resolve this yet, it requires something later in the file.
513       GlobalInits.push_back(GlobalInitWorklist.back());
514     } else {
515       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
516         GlobalInitWorklist.back().first->setInitializer(C);
517       else
518         return Error("Global variable initializer is not a constant!");
519     }
520     GlobalInitWorklist.pop_back(); 
521   }
522
523   while (!AliasInitWorklist.empty()) {
524     unsigned ValID = AliasInitWorklist.back().second;
525     if (ValID >= ValueList.size()) {
526       AliasInits.push_back(AliasInitWorklist.back());
527     } else {
528       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
529         AliasInitWorklist.back().first->setAliasee(C);
530       else
531         return Error("Alias initializer is not a constant!");
532     }
533     AliasInitWorklist.pop_back(); 
534   }
535   return false;
536 }
537
538
539 bool BitcodeReader::ParseConstants() {
540   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
541     return Error("Malformed block record");
542
543   SmallVector<uint64_t, 64> Record;
544   
545   // Read all the records for this value table.
546   const Type *CurTy = Type::Int32Ty;
547   unsigned NextCstNo = ValueList.size();
548   while (1) {
549     unsigned Code = Stream.ReadCode();
550     if (Code == bitc::END_BLOCK) {
551       if (NextCstNo != ValueList.size())
552         return Error("Invalid constant reference!");
553       
554       if (Stream.ReadBlockEnd())
555         return Error("Error at end of constants block");
556       return false;
557     }
558     
559     if (Code == bitc::ENTER_SUBBLOCK) {
560       // No known subblocks, always skip them.
561       Stream.ReadSubBlockID();
562       if (Stream.SkipBlock())
563         return Error("Malformed block record");
564       continue;
565     }
566     
567     if (Code == bitc::DEFINE_ABBREV) {
568       Stream.ReadAbbrevRecord();
569       continue;
570     }
571     
572     // Read a record.
573     Record.clear();
574     Value *V = 0;
575     switch (Stream.ReadRecord(Code, Record)) {
576     default:  // Default behavior: unknown constant
577     case bitc::CST_CODE_UNDEF:     // UNDEF
578       V = UndefValue::get(CurTy);
579       break;
580     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
581       if (Record.empty())
582         return Error("Malformed CST_SETTYPE record");
583       if (Record[0] >= TypeList.size())
584         return Error("Invalid Type ID in CST_SETTYPE record");
585       CurTy = TypeList[Record[0]];
586       continue;  // Skip the ValueList manipulation.
587     case bitc::CST_CODE_NULL:      // NULL
588       V = Constant::getNullValue(CurTy);
589       break;
590     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
591       if (!isa<IntegerType>(CurTy) || Record.empty())
592         return Error("Invalid CST_INTEGER record");
593       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
594       break;
595     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
596       if (!isa<IntegerType>(CurTy) || Record.empty())
597         return Error("Invalid WIDE_INTEGER record");
598       
599       unsigned NumWords = Record.size();
600       SmallVector<uint64_t, 8> Words;
601       Words.resize(NumWords);
602       for (unsigned i = 0; i != NumWords; ++i)
603         Words[i] = DecodeSignRotatedValue(Record[i]);
604       V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
605                                  NumWords, &Words[0]));
606       break;
607     }
608     case bitc::CST_CODE_FLOAT:     // FLOAT: [fpval]
609       if (Record.empty())
610         return Error("Invalid FLOAT record");
611       if (CurTy == Type::FloatTy)
612         V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
613       else if (CurTy == Type::DoubleTy)
614         V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
615       else
616         V = UndefValue::get(CurTy);
617       break;
618       
619     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
620       if (Record.empty())
621         return Error("Invalid CST_AGGREGATE record");
622       
623       unsigned Size = Record.size();
624       std::vector<Constant*> Elts;
625       
626       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
627         for (unsigned i = 0; i != Size; ++i)
628           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
629                                                      STy->getElementType(i)));
630         V = ConstantStruct::get(STy, Elts);
631       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
632         const Type *EltTy = ATy->getElementType();
633         for (unsigned i = 0; i != Size; ++i)
634           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
635         V = ConstantArray::get(ATy, Elts);
636       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
637         const Type *EltTy = VTy->getElementType();
638         for (unsigned i = 0; i != Size; ++i)
639           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
640         V = ConstantVector::get(Elts);
641       } else {
642         V = UndefValue::get(CurTy);
643       }
644       break;
645     }
646     case bitc::CST_CODE_STRING: { // STRING: [values]
647       if (Record.empty())
648         return Error("Invalid CST_AGGREGATE record");
649
650       const ArrayType *ATy = cast<ArrayType>(CurTy);
651       const Type *EltTy = ATy->getElementType();
652       
653       unsigned Size = Record.size();
654       std::vector<Constant*> Elts;
655       for (unsigned i = 0; i != Size; ++i)
656         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
657       V = ConstantArray::get(ATy, Elts);
658       break;
659     }
660     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
661       if (Record.empty())
662         return Error("Invalid CST_AGGREGATE record");
663       
664       const ArrayType *ATy = cast<ArrayType>(CurTy);
665       const Type *EltTy = ATy->getElementType();
666       
667       unsigned Size = Record.size();
668       std::vector<Constant*> Elts;
669       for (unsigned i = 0; i != Size; ++i)
670         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
671       Elts.push_back(Constant::getNullValue(EltTy));
672       V = ConstantArray::get(ATy, Elts);
673       break;
674     }
675     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
676       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
677       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
678       if (Opc < 0) {
679         V = UndefValue::get(CurTy);  // Unknown binop.
680       } else {
681         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
682         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
683         V = ConstantExpr::get(Opc, LHS, RHS);
684       }
685       break;
686     }  
687     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
688       if (Record.size() < 3) return Error("Invalid CE_CAST record");
689       int Opc = GetDecodedCastOpcode(Record[0]);
690       if (Opc < 0) {
691         V = UndefValue::get(CurTy);  // Unknown cast.
692       } else {
693         const Type *OpTy = getTypeByID(Record[1]);
694         if (!OpTy) return Error("Invalid CE_CAST record");
695         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
696         V = ConstantExpr::getCast(Opc, Op, CurTy);
697       }
698       break;
699     }  
700     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
701       if (Record.size() & 1) return Error("Invalid CE_GEP record");
702       SmallVector<Constant*, 16> Elts;
703       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
704         const Type *ElTy = getTypeByID(Record[i]);
705         if (!ElTy) return Error("Invalid CE_GEP record");
706         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
707       }
708       V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
709       break;
710     }
711     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
712       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
713       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
714                                                               Type::Int1Ty),
715                                   ValueList.getConstantFwdRef(Record[1],CurTy),
716                                   ValueList.getConstantFwdRef(Record[2],CurTy));
717       break;
718     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
719       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
720       const VectorType *OpTy = 
721         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
722       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
723       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
724       Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
725                                                   OpTy->getElementType());
726       V = ConstantExpr::getExtractElement(Op0, Op1);
727       break;
728     }
729     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
730       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
731       if (Record.size() < 3 || OpTy == 0)
732         return Error("Invalid CE_INSERTELT record");
733       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
734       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
735                                                   OpTy->getElementType());
736       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
737       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
738       break;
739     }
740     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
741       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
742       if (Record.size() < 3 || OpTy == 0)
743         return Error("Invalid CE_INSERTELT record");
744       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
745       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
746       const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
747       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
748       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
749       break;
750     }
751     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
752       if (Record.size() < 4) return Error("Invalid CE_CMP record");
753       const Type *OpTy = getTypeByID(Record[0]);
754       if (OpTy == 0) return Error("Invalid CE_CMP record");
755       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
756       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
757
758       if (OpTy->isFloatingPoint())
759         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
760       else
761         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
762       break;
763     }
764     case bitc::CST_CODE_INLINEASM: {
765       if (Record.size() < 2) return Error("Invalid INLINEASM record");
766       std::string AsmStr, ConstrStr;
767       bool HasSideEffects = Record[0];
768       unsigned AsmStrSize = Record[1];
769       if (2+AsmStrSize >= Record.size())
770         return Error("Invalid INLINEASM record");
771       unsigned ConstStrSize = Record[2+AsmStrSize];
772       if (3+AsmStrSize+ConstStrSize > Record.size())
773         return Error("Invalid INLINEASM record");
774       
775       for (unsigned i = 0; i != AsmStrSize; ++i)
776         AsmStr += (char)Record[2+i];
777       for (unsigned i = 0; i != ConstStrSize; ++i)
778         ConstrStr += (char)Record[3+AsmStrSize+i];
779       const PointerType *PTy = cast<PointerType>(CurTy);
780       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
781                          AsmStr, ConstrStr, HasSideEffects);
782       break;
783     }
784     }
785     
786     ValueList.AssignValue(V, NextCstNo);
787     ++NextCstNo;
788   }
789 }
790
791 /// RememberAndSkipFunctionBody - When we see the block for a function body,
792 /// remember where it is and then skip it.  This lets us lazily deserialize the
793 /// functions.
794 bool BitcodeReader::RememberAndSkipFunctionBody() {
795   // Get the function we are talking about.
796   if (FunctionsWithBodies.empty())
797     return Error("Insufficient function protos");
798   
799   Function *Fn = FunctionsWithBodies.back();
800   FunctionsWithBodies.pop_back();
801   
802   // Save the current stream state.
803   uint64_t CurBit = Stream.GetCurrentBitNo();
804   DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
805   
806   // Set the functions linkage to GhostLinkage so we know it is lazily
807   // deserialized.
808   Fn->setLinkage(GlobalValue::GhostLinkage);
809   
810   // Skip over the function block for now.
811   if (Stream.SkipBlock())
812     return Error("Malformed block record");
813   return false;
814 }
815
816 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
817   // Reject multiple MODULE_BLOCK's in a single bitstream.
818   if (TheModule)
819     return Error("Multiple MODULE_BLOCKs in same stream");
820   
821   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
822     return Error("Malformed block record");
823
824   // Otherwise, create the module.
825   TheModule = new Module(ModuleID);
826   
827   SmallVector<uint64_t, 64> Record;
828   std::vector<std::string> SectionTable;
829
830   // Read all the records for this module.
831   while (!Stream.AtEndOfStream()) {
832     unsigned Code = Stream.ReadCode();
833     if (Code == bitc::END_BLOCK) {
834       if (Stream.ReadBlockEnd())
835         return Error("Error at end of module block");
836
837       // Patch the initializers for globals and aliases up.
838       ResolveGlobalAndAliasInits();
839       if (!GlobalInits.empty() || !AliasInits.empty())
840         return Error("Malformed global initializer set");
841       if (!FunctionsWithBodies.empty())
842         return Error("Too few function bodies found");
843
844       // Force deallocation of memory for these vectors to favor the client that
845       // want lazy deserialization.
846       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
847       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
848       std::vector<Function*>().swap(FunctionsWithBodies);
849       return false;
850     }
851     
852     if (Code == bitc::ENTER_SUBBLOCK) {
853       switch (Stream.ReadSubBlockID()) {
854       default:  // Skip unknown content.
855         if (Stream.SkipBlock())
856           return Error("Malformed block record");
857         break;
858       case bitc::BLOCKINFO_BLOCK_ID:
859         if (Stream.ReadBlockInfoBlock())
860           return Error("Malformed BlockInfoBlock");
861         break;
862       case bitc::PARAMATTR_BLOCK_ID:
863         if (ParseParamAttrBlock())
864           return true;
865         break;
866       case bitc::TYPE_BLOCK_ID:
867         if (ParseTypeTable())
868           return true;
869         break;
870       case bitc::TYPE_SYMTAB_BLOCK_ID:
871         if (ParseTypeSymbolTable())
872           return true;
873         break;
874       case bitc::VALUE_SYMTAB_BLOCK_ID:
875         if (ParseValueSymbolTable())
876           return true;
877         break;
878       case bitc::CONSTANTS_BLOCK_ID:
879         if (ParseConstants() || ResolveGlobalAndAliasInits())
880           return true;
881         break;
882       case bitc::FUNCTION_BLOCK_ID:
883         // If this is the first function body we've seen, reverse the
884         // FunctionsWithBodies list.
885         if (!HasReversedFunctionsWithBodies) {
886           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
887           HasReversedFunctionsWithBodies = true;
888         }
889         
890         if (RememberAndSkipFunctionBody())
891           return true;
892         break;
893       }
894       continue;
895     }
896     
897     if (Code == bitc::DEFINE_ABBREV) {
898       Stream.ReadAbbrevRecord();
899       continue;
900     }
901     
902     // Read a record.
903     switch (Stream.ReadRecord(Code, Record)) {
904     default: break;  // Default behavior, ignore unknown content.
905     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
906       if (Record.size() < 1)
907         return Error("Malformed MODULE_CODE_VERSION");
908       // Only version #0 is supported so far.
909       if (Record[0] != 0)
910         return Error("Unknown bitstream version!");
911       break;
912     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
913       std::string S;
914       if (ConvertToString(Record, 0, S))
915         return Error("Invalid MODULE_CODE_TRIPLE record");
916       TheModule->setTargetTriple(S);
917       break;
918     }
919     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
920       std::string S;
921       if (ConvertToString(Record, 0, S))
922         return Error("Invalid MODULE_CODE_DATALAYOUT record");
923       TheModule->setDataLayout(S);
924       break;
925     }
926     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
927       std::string S;
928       if (ConvertToString(Record, 0, S))
929         return Error("Invalid MODULE_CODE_ASM record");
930       TheModule->setModuleInlineAsm(S);
931       break;
932     }
933     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
934       std::string S;
935       if (ConvertToString(Record, 0, S))
936         return Error("Invalid MODULE_CODE_DEPLIB record");
937       TheModule->addLibrary(S);
938       break;
939     }
940     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
941       std::string S;
942       if (ConvertToString(Record, 0, S))
943         return Error("Invalid MODULE_CODE_SECTIONNAME record");
944       SectionTable.push_back(S);
945       break;
946     }
947     // GLOBALVAR: [type, isconst, initid, 
948     //             linkage, alignment, section, visibility, threadlocal]
949     case bitc::MODULE_CODE_GLOBALVAR: {
950       if (Record.size() < 6)
951         return Error("Invalid MODULE_CODE_GLOBALVAR record");
952       const Type *Ty = getTypeByID(Record[0]);
953       if (!isa<PointerType>(Ty))
954         return Error("Global not a pointer type!");
955       Ty = cast<PointerType>(Ty)->getElementType();
956       
957       bool isConstant = Record[1];
958       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
959       unsigned Alignment = (1 << Record[4]) >> 1;
960       std::string Section;
961       if (Record[5]) {
962         if (Record[5]-1 >= SectionTable.size())
963           return Error("Invalid section ID");
964         Section = SectionTable[Record[5]-1];
965       }
966       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
967       if (Record.size() > 6)
968         Visibility = GetDecodedVisibility(Record[6]);
969       bool isThreadLocal = false;
970       if (Record.size() > 7)
971         isThreadLocal = Record[7];
972
973       GlobalVariable *NewGV =
974         new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
975       NewGV->setAlignment(Alignment);
976       if (!Section.empty())
977         NewGV->setSection(Section);
978       NewGV->setVisibility(Visibility);
979       NewGV->setThreadLocal(isThreadLocal);
980       
981       ValueList.push_back(NewGV);
982       
983       // Remember which value to use for the global initializer.
984       if (unsigned InitID = Record[2])
985         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
986       break;
987     }
988     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
989     //             visibility]
990     case bitc::MODULE_CODE_FUNCTION: {
991       if (Record.size() < 7)
992         return Error("Invalid MODULE_CODE_FUNCTION record");
993       const Type *Ty = getTypeByID(Record[0]);
994       if (!isa<PointerType>(Ty))
995         return Error("Function not a pointer type!");
996       const FunctionType *FTy =
997         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
998       if (!FTy)
999         return Error("Function not a pointer to function type!");
1000
1001       Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1002                                     "", TheModule);
1003
1004       Func->setCallingConv(Record[1]);
1005       bool isProto = Record[2];
1006       Func->setLinkage(GetDecodedLinkage(Record[3]));
1007       Func->setAlignment((1 << Record[4]) >> 1);
1008       if (Record[5]) {
1009         if (Record[5]-1 >= SectionTable.size())
1010           return Error("Invalid section ID");
1011         Func->setSection(SectionTable[Record[5]-1]);
1012       }
1013       Func->setVisibility(GetDecodedVisibility(Record[6]));
1014       
1015       ValueList.push_back(Func);
1016       
1017       // If this is a function with a body, remember the prototype we are
1018       // creating now, so that we can match up the body with them later.
1019       if (!isProto)
1020         FunctionsWithBodies.push_back(Func);
1021       break;
1022     }
1023     // ALIAS: [alias type, aliasee val#, linkage]
1024     case bitc::MODULE_CODE_ALIAS: {
1025       if (Record.size() < 3)
1026         return Error("Invalid MODULE_ALIAS record");
1027       const Type *Ty = getTypeByID(Record[0]);
1028       if (!isa<PointerType>(Ty))
1029         return Error("Function not a pointer type!");
1030       
1031       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1032                                            "", 0, TheModule);
1033       ValueList.push_back(NewGA);
1034       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1035       break;
1036     }
1037     /// MODULE_CODE_PURGEVALS: [numvals]
1038     case bitc::MODULE_CODE_PURGEVALS:
1039       // Trim down the value list to the specified size.
1040       if (Record.size() < 1 || Record[0] > ValueList.size())
1041         return Error("Invalid MODULE_PURGEVALS record");
1042       ValueList.shrinkTo(Record[0]);
1043       break;
1044     }
1045     Record.clear();
1046   }
1047   
1048   return Error("Premature end of bitstream");
1049 }
1050
1051
1052 bool BitcodeReader::ParseBitcode() {
1053   TheModule = 0;
1054   
1055   if (Buffer->getBufferSize() & 3)
1056     return Error("Bitcode stream should be a multiple of 4 bytes in length");
1057   
1058   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1059   Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1060   
1061   // Sniff for the signature.
1062   if (Stream.Read(8) != 'B' ||
1063       Stream.Read(8) != 'C' ||
1064       Stream.Read(4) != 0x0 ||
1065       Stream.Read(4) != 0xC ||
1066       Stream.Read(4) != 0xE ||
1067       Stream.Read(4) != 0xD)
1068     return Error("Invalid bitcode signature");
1069   
1070   // We expect a number of well-defined blocks, though we don't necessarily
1071   // need to understand them all.
1072   while (!Stream.AtEndOfStream()) {
1073     unsigned Code = Stream.ReadCode();
1074     
1075     if (Code != bitc::ENTER_SUBBLOCK)
1076       return Error("Invalid record at top-level");
1077     
1078     unsigned BlockID = Stream.ReadSubBlockID();
1079     
1080     // We only know the MODULE subblock ID.
1081     switch (BlockID) {
1082     case bitc::BLOCKINFO_BLOCK_ID:
1083       if (Stream.ReadBlockInfoBlock())
1084         return Error("Malformed BlockInfoBlock");
1085       break;
1086     case bitc::MODULE_BLOCK_ID:
1087       if (ParseModule(Buffer->getBufferIdentifier()))
1088         return true;
1089       break;
1090     default:
1091       if (Stream.SkipBlock())
1092         return Error("Malformed block record");
1093       break;
1094     }
1095   }
1096   
1097   return false;
1098 }
1099
1100
1101 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1102   // If it already is material, ignore the request.
1103   if (!F->hasNotBeenReadFromBytecode()) return false;
1104
1105   DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 
1106     DeferredFunctionInfo.find(F);
1107   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1108   
1109   // Move the bit stream to the saved position of the deferred function body and
1110   // restore the real linkage type for the function.
1111   Stream.JumpToBit(DFII->second.first);
1112   F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1113   DeferredFunctionInfo.erase(DFII);
1114   
1115   if (ParseFunctionBody(F)) {
1116     if (ErrInfo) *ErrInfo = ErrorString;
1117     return true;
1118   }
1119   
1120   return false;
1121 }
1122
1123 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1124   DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 
1125     DeferredFunctionInfo.begin();
1126   while (!DeferredFunctionInfo.empty()) {
1127     Function *F = (*I++).first;
1128     assert(F->hasNotBeenReadFromBytecode() &&
1129            "Deserialized function found in map!");
1130     if (materializeFunction(F, ErrInfo))
1131       return 0;
1132   }
1133   return TheModule;
1134 }
1135
1136
1137 /// ParseFunctionBody - Lazily parse the specified function body block.
1138 bool BitcodeReader::ParseFunctionBody(Function *F) {
1139   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1140     return Error("Malformed block record");
1141   
1142   unsigned ModuleValueListSize = ValueList.size();
1143   
1144   // Add all the function arguments to the value table.
1145   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1146     ValueList.push_back(I);
1147   
1148   unsigned NextValueNo = ValueList.size();
1149   BasicBlock *CurBB = 0;
1150   unsigned CurBBNo = 0;
1151
1152   // Read all the records.
1153   SmallVector<uint64_t, 64> Record;
1154   while (1) {
1155     unsigned Code = Stream.ReadCode();
1156     if (Code == bitc::END_BLOCK) {
1157       if (Stream.ReadBlockEnd())
1158         return Error("Error at end of function block");
1159       break;
1160     }
1161     
1162     if (Code == bitc::ENTER_SUBBLOCK) {
1163       switch (Stream.ReadSubBlockID()) {
1164       default:  // Skip unknown content.
1165         if (Stream.SkipBlock())
1166           return Error("Malformed block record");
1167         break;
1168       case bitc::CONSTANTS_BLOCK_ID:
1169         if (ParseConstants()) return true;
1170         NextValueNo = ValueList.size();
1171         break;
1172       case bitc::VALUE_SYMTAB_BLOCK_ID:
1173         if (ParseValueSymbolTable()) return true;
1174         break;
1175       }
1176       continue;
1177     }
1178     
1179     if (Code == bitc::DEFINE_ABBREV) {
1180       Stream.ReadAbbrevRecord();
1181       continue;
1182     }
1183     
1184     // Read a record.
1185     Record.clear();
1186     Instruction *I = 0;
1187     switch (Stream.ReadRecord(Code, Record)) {
1188     default: // Default behavior: reject
1189       return Error("Unknown instruction");
1190     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1191       if (Record.size() < 1 || Record[0] == 0)
1192         return Error("Invalid DECLAREBLOCKS record");
1193       // Create all the basic blocks for the function.
1194       FunctionBBs.resize(Record[0]);
1195       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1196         FunctionBBs[i] = new BasicBlock("", F);
1197       CurBB = FunctionBBs[0];
1198       continue;
1199       
1200     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1201       unsigned OpNum = 0;
1202       Value *LHS, *RHS;
1203       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1204           getValue(Record, OpNum, LHS->getType(), RHS) ||
1205           OpNum+1 != Record.size())
1206         return Error("Invalid BINOP record");
1207       
1208       int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1209       if (Opc == -1) return Error("Invalid BINOP record");
1210       I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1211       break;
1212     }
1213     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1214       unsigned OpNum = 0;
1215       Value *Op;
1216       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1217           OpNum+2 != Record.size())
1218         return Error("Invalid CAST record");
1219       
1220       const Type *ResTy = getTypeByID(Record[OpNum]);
1221       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1222       if (Opc == -1 || ResTy == 0)
1223         return Error("Invalid CAST record");
1224       I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1225       break;
1226     }
1227     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1228       unsigned OpNum = 0;
1229       Value *BasePtr;
1230       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1231         return Error("Invalid GEP record");
1232
1233       SmallVector<Value*, 16> GEPIdx;
1234       while (OpNum != Record.size()) {
1235         Value *Op;
1236         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1237           return Error("Invalid GEP record");
1238         GEPIdx.push_back(Op);
1239       }
1240
1241       I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
1242       break;
1243     }
1244       
1245     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1246       unsigned OpNum = 0;
1247       Value *TrueVal, *FalseVal, *Cond;
1248       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1249           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1250           getValue(Record, OpNum, Type::Int1Ty, Cond))
1251         return Error("Invalid SELECT record");
1252       
1253       I = new SelectInst(Cond, TrueVal, FalseVal);
1254       break;
1255     }
1256       
1257     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1258       unsigned OpNum = 0;
1259       Value *Vec, *Idx;
1260       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1261           getValue(Record, OpNum, Type::Int32Ty, Idx))
1262         return Error("Invalid EXTRACTELT record");
1263       I = new ExtractElementInst(Vec, Idx);
1264       break;
1265     }
1266       
1267     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1268       unsigned OpNum = 0;
1269       Value *Vec, *Elt, *Idx;
1270       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1271           getValue(Record, OpNum, 
1272                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1273           getValue(Record, OpNum, Type::Int32Ty, Idx))
1274         return Error("Invalid INSERTELT record");
1275       I = new InsertElementInst(Vec, Elt, Idx);
1276       break;
1277     }
1278       
1279     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1280       unsigned OpNum = 0;
1281       Value *Vec1, *Vec2, *Mask;
1282       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1283           getValue(Record, OpNum, Vec1->getType(), Vec2))
1284         return Error("Invalid SHUFFLEVEC record");
1285
1286       const Type *MaskTy =
1287         VectorType::get(Type::Int32Ty, 
1288                         cast<VectorType>(Vec1->getType())->getNumElements());
1289
1290       if (getValue(Record, OpNum, MaskTy, Mask))
1291         return Error("Invalid SHUFFLEVEC record");
1292       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1293       break;
1294     }
1295       
1296     case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1297       unsigned OpNum = 0;
1298       Value *LHS, *RHS;
1299       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1300           getValue(Record, OpNum, LHS->getType(), RHS) ||
1301           OpNum+1 != Record.size())
1302         return Error("Invalid CMP record");
1303       
1304       if (LHS->getType()->isFPOrFPVector())
1305         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1306       else
1307         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1308       break;
1309     }
1310     
1311     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1312       if (Record.size() == 0) {
1313         I = new ReturnInst();
1314         break;
1315       } else {
1316         unsigned OpNum = 0;
1317         Value *Op;
1318         if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1319             OpNum != Record.size())
1320           return Error("Invalid RET record");
1321         I = new ReturnInst(Op);
1322         break;
1323       }
1324     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1325       if (Record.size() != 1 && Record.size() != 3)
1326         return Error("Invalid BR record");
1327       BasicBlock *TrueDest = getBasicBlock(Record[0]);
1328       if (TrueDest == 0)
1329         return Error("Invalid BR record");
1330
1331       if (Record.size() == 1)
1332         I = new BranchInst(TrueDest);
1333       else {
1334         BasicBlock *FalseDest = getBasicBlock(Record[1]);
1335         Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1336         if (FalseDest == 0 || Cond == 0)
1337           return Error("Invalid BR record");
1338         I = new BranchInst(TrueDest, FalseDest, Cond);
1339       }
1340       break;
1341     }
1342     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1343       if (Record.size() < 3 || (Record.size() & 1) == 0)
1344         return Error("Invalid SWITCH record");
1345       const Type *OpTy = getTypeByID(Record[0]);
1346       Value *Cond = getFnValueByID(Record[1], OpTy);
1347       BasicBlock *Default = getBasicBlock(Record[2]);
1348       if (OpTy == 0 || Cond == 0 || Default == 0)
1349         return Error("Invalid SWITCH record");
1350       unsigned NumCases = (Record.size()-3)/2;
1351       SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1352       for (unsigned i = 0, e = NumCases; i != e; ++i) {
1353         ConstantInt *CaseVal = 
1354           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1355         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1356         if (CaseVal == 0 || DestBB == 0) {
1357           delete SI;
1358           return Error("Invalid SWITCH record!");
1359         }
1360         SI->addCase(CaseVal, DestBB);
1361       }
1362       I = SI;
1363       break;
1364     }
1365       
1366     case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1367       if (Record.size() < 3) return Error("Invalid INVOKE record");
1368       unsigned CCInfo = Record[0];
1369       BasicBlock *NormalBB = getBasicBlock(Record[1]);
1370       BasicBlock *UnwindBB = getBasicBlock(Record[2]);
1371       
1372       unsigned OpNum = 3;
1373       Value *Callee;
1374       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1375         return Error("Invalid INVOKE record");
1376       
1377       const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1378       const FunctionType *FTy = !CalleeTy ? 0 :
1379         dyn_cast<FunctionType>(CalleeTy->getElementType());
1380
1381       // Check that the right number of fixed parameters are here.
1382       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1383           Record.size() < OpNum+FTy->getNumParams())
1384         return Error("Invalid INVOKE record");
1385       
1386       SmallVector<Value*, 16> Ops;
1387       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1388         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1389         if (Ops.back() == 0) return Error("Invalid INVOKE record");
1390       }
1391       
1392       if (!FTy->isVarArg()) {
1393         if (Record.size() != OpNum)
1394           return Error("Invalid INVOKE record");
1395       } else {
1396         // Read type/value pairs for varargs params.
1397         while (OpNum != Record.size()) {
1398           Value *Op;
1399           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1400             return Error("Invalid INVOKE record");
1401           Ops.push_back(Op);
1402         }
1403       }
1404       
1405       I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1406       cast<InvokeInst>(I)->setCallingConv(CCInfo);
1407       break;
1408     }
1409     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1410       I = new UnwindInst();
1411       break;
1412     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1413       I = new UnreachableInst();
1414       break;
1415     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1416       if (Record.size() < 1 || ((Record.size()-1)&1))
1417         return Error("Invalid PHI record");
1418       const Type *Ty = getTypeByID(Record[0]);
1419       if (!Ty) return Error("Invalid PHI record");
1420       
1421       PHINode *PN = new PHINode(Ty);
1422       PN->reserveOperandSpace(Record.size()-1);
1423       
1424       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1425         Value *V = getFnValueByID(Record[1+i], Ty);
1426         BasicBlock *BB = getBasicBlock(Record[2+i]);
1427         if (!V || !BB) return Error("Invalid PHI record");
1428         PN->addIncoming(V, BB);
1429       }
1430       I = PN;
1431       break;
1432     }
1433       
1434     case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1435       if (Record.size() < 3)
1436         return Error("Invalid MALLOC record");
1437       const PointerType *Ty =
1438         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1439       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1440       unsigned Align = Record[2];
1441       if (!Ty || !Size) return Error("Invalid MALLOC record");
1442       I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1443       break;
1444     }
1445     case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1446       unsigned OpNum = 0;
1447       Value *Op;
1448       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1449           OpNum != Record.size())
1450         return Error("Invalid FREE record");
1451       I = new FreeInst(Op);
1452       break;
1453     }
1454     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1455       if (Record.size() < 3)
1456         return Error("Invalid ALLOCA record");
1457       const PointerType *Ty =
1458         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1459       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1460       unsigned Align = Record[2];
1461       if (!Ty || !Size) return Error("Invalid ALLOCA record");
1462       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1463       break;
1464     }
1465     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1466       unsigned OpNum = 0;
1467       Value *Op;
1468       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1469           OpNum+2 != Record.size())
1470         return Error("Invalid LOAD record");
1471       
1472       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1473       break;
1474     }
1475     case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1476       unsigned OpNum = 0;
1477       Value *Val, *Ptr;
1478       if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1479           getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1480           OpNum+2 != Record.size())
1481         return Error("Invalid STORE record");
1482       
1483       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1484       break;
1485     }
1486     case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1487       if (Record.size() < 1)
1488         return Error("Invalid CALL record");
1489       unsigned CCInfo = Record[0];
1490       
1491       unsigned OpNum = 1;
1492       Value *Callee;
1493       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1494         return Error("Invalid CALL record");
1495       
1496       const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1497       const FunctionType *FTy = 0;
1498       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1499       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1500         return Error("Invalid CALL record");
1501       
1502       SmallVector<Value*, 16> Args;
1503       // Read the fixed params.
1504       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1505         Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1506         if (Args.back() == 0) return Error("Invalid CALL record");
1507       }
1508       
1509       // Read type/value pairs for varargs params.
1510       if (!FTy->isVarArg()) {
1511         if (OpNum != Record.size())
1512           return Error("Invalid CALL record");
1513       } else {
1514         while (OpNum != Record.size()) {
1515           Value *Op;
1516           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1517             return Error("Invalid CALL record");
1518           Args.push_back(Op);
1519         }
1520       }
1521       
1522       I = new CallInst(Callee, &Args[0], Args.size());
1523       cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1524       cast<CallInst>(I)->setTailCall(CCInfo & 1);
1525       break;
1526     }
1527     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1528       if (Record.size() < 3)
1529         return Error("Invalid VAARG record");
1530       const Type *OpTy = getTypeByID(Record[0]);
1531       Value *Op = getFnValueByID(Record[1], OpTy);
1532       const Type *ResTy = getTypeByID(Record[2]);
1533       if (!OpTy || !Op || !ResTy)
1534         return Error("Invalid VAARG record");
1535       I = new VAArgInst(Op, ResTy);
1536       break;
1537     }
1538     }
1539
1540     // Add instruction to end of current BB.  If there is no current BB, reject
1541     // this file.
1542     if (CurBB == 0) {
1543       delete I;
1544       return Error("Invalid instruction with no BB");
1545     }
1546     CurBB->getInstList().push_back(I);
1547     
1548     // If this was a terminator instruction, move to the next block.
1549     if (isa<TerminatorInst>(I)) {
1550       ++CurBBNo;
1551       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1552     }
1553     
1554     // Non-void values get registered in the value table for future use.
1555     if (I && I->getType() != Type::VoidTy)
1556       ValueList.AssignValue(I, NextValueNo++);
1557   }
1558   
1559   // Check the function list for unresolved values.
1560   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1561     if (A->getParent() == 0) {
1562       // We found at least one unresolved value.  Nuke them all to avoid leaks.
1563       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1564         if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1565           A->replaceAllUsesWith(UndefValue::get(A->getType()));
1566           delete A;
1567         }
1568       }
1569       return Error("Never resolved value found in function!");
1570     }
1571   }
1572   
1573   // Trim the value list down to the size it was before we parsed this function.
1574   ValueList.shrinkTo(ModuleValueListSize);
1575   std::vector<BasicBlock*>().swap(FunctionBBs);
1576   
1577   return false;
1578 }
1579
1580
1581 //===----------------------------------------------------------------------===//
1582 // External interface
1583 //===----------------------------------------------------------------------===//
1584
1585 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1586 ///
1587 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1588                                                std::string *ErrMsg) {
1589   BitcodeReader *R = new BitcodeReader(Buffer);
1590   if (R->ParseBitcode()) {
1591     if (ErrMsg)
1592       *ErrMsg = R->getErrorString();
1593     
1594     // Don't let the BitcodeReader dtor delete 'Buffer'.
1595     R->releaseMemoryBuffer();
1596     delete R;
1597     return 0;
1598   }
1599   return R;
1600 }
1601
1602 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1603 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1604 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1605   BitcodeReader *R;
1606   R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1607   if (!R) return 0;
1608   
1609   // Read the whole module, get a pointer to it, tell ModuleProvider not to
1610   // delete it when its dtor is run.
1611   Module *M = R->releaseModule(ErrMsg);
1612   
1613   // Don't let the BitcodeReader dtor delete 'Buffer'.
1614   R->releaseMemoryBuffer();
1615   delete R;
1616   return M;
1617 }