xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 3d5450d809a553872e3c931b5312352889b8e80c)
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
28 using namespace llvm;
29 
30 void BitcodeReader::FreeState() {
31   if (BufferOwned)
32     delete Buffer;
33   Buffer = 0;
34   std::vector<PATypeHolder>().swap(TypeList);
35   ValueList.clear();
36   MDValueList.clear();
37 
38   std::vector<AttrListPtr>().swap(MAttributes);
39   std::vector<BasicBlock*>().swap(FunctionBBs);
40   std::vector<Function*>().swap(FunctionsWithBodies);
41   DeferredFunctionInfo.clear();
42   MDKindMap.clear();
43 }
44 
45 //===----------------------------------------------------------------------===//
46 //  Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
48 
49 /// ConvertToString - Convert a string from a record into an std::string, return
50 /// true on failure.
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
53                             StrTy &Result) {
54   if (Idx > Record.size())
55     return true;
56 
57   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58     Result += (char)Record[i];
59   return false;
60 }
61 
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63   switch (Val) {
64   default: // Map unknown/new linkages to external
65   case 0:  return GlobalValue::ExternalLinkage;
66   case 1:  return GlobalValue::WeakAnyLinkage;
67   case 2:  return GlobalValue::AppendingLinkage;
68   case 3:  return GlobalValue::InternalLinkage;
69   case 4:  return GlobalValue::LinkOnceAnyLinkage;
70   case 5:  return GlobalValue::DLLImportLinkage;
71   case 6:  return GlobalValue::DLLExportLinkage;
72   case 7:  return GlobalValue::ExternalWeakLinkage;
73   case 8:  return GlobalValue::CommonLinkage;
74   case 9:  return GlobalValue::PrivateLinkage;
75   case 10: return GlobalValue::WeakODRLinkage;
76   case 11: return GlobalValue::LinkOnceODRLinkage;
77   case 12: return GlobalValue::AvailableExternallyLinkage;
78   case 13: return GlobalValue::LinkerPrivateLinkage;
79   case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80   case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
81   }
82 }
83 
84 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
85   switch (Val) {
86   default: // Map unknown visibilities to default.
87   case 0: return GlobalValue::DefaultVisibility;
88   case 1: return GlobalValue::HiddenVisibility;
89   case 2: return GlobalValue::ProtectedVisibility;
90   }
91 }
92 
93 static int GetDecodedCastOpcode(unsigned Val) {
94   switch (Val) {
95   default: return -1;
96   case bitc::CAST_TRUNC   : return Instruction::Trunc;
97   case bitc::CAST_ZEXT    : return Instruction::ZExt;
98   case bitc::CAST_SEXT    : return Instruction::SExt;
99   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
100   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
101   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
102   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
103   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104   case bitc::CAST_FPEXT   : return Instruction::FPExt;
105   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107   case bitc::CAST_BITCAST : return Instruction::BitCast;
108   }
109 }
110 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
111   switch (Val) {
112   default: return -1;
113   case bitc::BINOP_ADD:
114     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115   case bitc::BINOP_SUB:
116     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117   case bitc::BINOP_MUL:
118     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119   case bitc::BINOP_UDIV: return Instruction::UDiv;
120   case bitc::BINOP_SDIV:
121     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122   case bitc::BINOP_UREM: return Instruction::URem;
123   case bitc::BINOP_SREM:
124     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125   case bitc::BINOP_SHL:  return Instruction::Shl;
126   case bitc::BINOP_LSHR: return Instruction::LShr;
127   case bitc::BINOP_ASHR: return Instruction::AShr;
128   case bitc::BINOP_AND:  return Instruction::And;
129   case bitc::BINOP_OR:   return Instruction::Or;
130   case bitc::BINOP_XOR:  return Instruction::Xor;
131   }
132 }
133 
134 namespace llvm {
135 namespace {
136   /// @brief A class for maintaining the slot number definition
137   /// as a placeholder for the actual definition for forward constants defs.
138   class ConstantPlaceHolder : public ConstantExpr {
139     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
140   public:
141     // allocate space for exactly one operand
142     void *operator new(size_t s) {
143       return User::operator new(s, 1);
144     }
145     explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
146       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
147       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
148     }
149 
150     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
151     //static inline bool classof(const ConstantPlaceHolder *) { return true; }
152     static bool classof(const Value *V) {
153       return isa<ConstantExpr>(V) &&
154              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
155     }
156 
157 
158     /// Provide fast operand accessors
159     //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
160   };
161 }
162 
163 // FIXME: can we inherit this from ConstantExpr?
164 template <>
165 struct OperandTraits<ConstantPlaceHolder> :
166   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
167 };
168 }
169 
170 
171 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
172   if (Idx == size()) {
173     push_back(V);
174     return;
175   }
176 
177   if (Idx >= size())
178     resize(Idx+1);
179 
180   WeakVH &OldV = ValuePtrs[Idx];
181   if (OldV == 0) {
182     OldV = V;
183     return;
184   }
185 
186   // Handle constants and non-constants (e.g. instrs) differently for
187   // efficiency.
188   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
189     ResolveConstants.push_back(std::make_pair(PHC, Idx));
190     OldV = V;
191   } else {
192     // If there was a forward reference to this value, replace it.
193     Value *PrevVal = OldV;
194     OldV->replaceAllUsesWith(V);
195     delete PrevVal;
196   }
197 }
198 
199 
200 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
201                                                     const Type *Ty) {
202   if (Idx >= size())
203     resize(Idx + 1);
204 
205   if (Value *V = ValuePtrs[Idx]) {
206     assert(Ty == V->getType() && "Type mismatch in constant table!");
207     return cast<Constant>(V);
208   }
209 
210   // Create and return a placeholder, which will later be RAUW'd.
211   Constant *C = new ConstantPlaceHolder(Ty, Context);
212   ValuePtrs[Idx] = C;
213   return C;
214 }
215 
216 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
217   if (Idx >= size())
218     resize(Idx + 1);
219 
220   if (Value *V = ValuePtrs[Idx]) {
221     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
222     return V;
223   }
224 
225   // No type specified, must be invalid reference.
226   if (Ty == 0) return 0;
227 
228   // Create and return a placeholder, which will later be RAUW'd.
229   Value *V = new Argument(Ty);
230   ValuePtrs[Idx] = V;
231   return V;
232 }
233 
234 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
235 /// resolves any forward references.  The idea behind this is that we sometimes
236 /// get constants (such as large arrays) which reference *many* forward ref
237 /// constants.  Replacing each of these causes a lot of thrashing when
238 /// building/reuniquing the constant.  Instead of doing this, we look at all the
239 /// uses and rewrite all the place holders at once for any constant that uses
240 /// a placeholder.
241 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
242   // Sort the values by-pointer so that they are efficient to look up with a
243   // binary search.
244   std::sort(ResolveConstants.begin(), ResolveConstants.end());
245 
246   SmallVector<Constant*, 64> NewOps;
247 
248   while (!ResolveConstants.empty()) {
249     Value *RealVal = operator[](ResolveConstants.back().second);
250     Constant *Placeholder = ResolveConstants.back().first;
251     ResolveConstants.pop_back();
252 
253     // Loop over all users of the placeholder, updating them to reference the
254     // new value.  If they reference more than one placeholder, update them all
255     // at once.
256     while (!Placeholder->use_empty()) {
257       Value::use_iterator UI = Placeholder->use_begin();
258       User *U = *UI;
259 
260       // If the using object isn't uniqued, just update the operands.  This
261       // handles instructions and initializers for global variables.
262       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
263         UI.getUse().set(RealVal);
264         continue;
265       }
266 
267       // Otherwise, we have a constant that uses the placeholder.  Replace that
268       // constant with a new constant that has *all* placeholder uses updated.
269       Constant *UserC = cast<Constant>(U);
270       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
271            I != E; ++I) {
272         Value *NewOp;
273         if (!isa<ConstantPlaceHolder>(*I)) {
274           // Not a placeholder reference.
275           NewOp = *I;
276         } else if (*I == Placeholder) {
277           // Common case is that it just references this one placeholder.
278           NewOp = RealVal;
279         } else {
280           // Otherwise, look up the placeholder in ResolveConstants.
281           ResolveConstantsTy::iterator It =
282             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
283                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
284                                                             0));
285           assert(It != ResolveConstants.end() && It->first == *I);
286           NewOp = operator[](It->second);
287         }
288 
289         NewOps.push_back(cast<Constant>(NewOp));
290       }
291 
292       // Make the new constant.
293       Constant *NewC;
294       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
295         NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
296                                         NewOps.size());
297       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
298         NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
299                                          UserCS->getType()->isPacked());
300       } else if (isa<ConstantVector>(UserC)) {
301         NewC = ConstantVector::get(NewOps);
302       } else {
303         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
304         NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
305                                                           NewOps.size());
306       }
307 
308       UserC->replaceAllUsesWith(NewC);
309       UserC->destroyConstant();
310       NewOps.clear();
311     }
312 
313     // Update all ValueHandles, they should be the only users at this point.
314     Placeholder->replaceAllUsesWith(RealVal);
315     delete Placeholder;
316   }
317 }
318 
319 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
320   if (Idx == size()) {
321     push_back(V);
322     return;
323   }
324 
325   if (Idx >= size())
326     resize(Idx+1);
327 
328   WeakVH &OldV = MDValuePtrs[Idx];
329   if (OldV == 0) {
330     OldV = V;
331     return;
332   }
333 
334   // If there was a forward reference to this value, replace it.
335   MDNode *PrevVal = cast<MDNode>(OldV);
336   OldV->replaceAllUsesWith(V);
337   MDNode::deleteTemporary(PrevVal);
338   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
339   // value for Idx.
340   MDValuePtrs[Idx] = V;
341 }
342 
343 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
344   if (Idx >= size())
345     resize(Idx + 1);
346 
347   if (Value *V = MDValuePtrs[Idx]) {
348     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
349     return V;
350   }
351 
352   // Create and return a placeholder, which will later be RAUW'd.
353   Value *V = MDNode::getTemporary(Context, 0, 0);
354   MDValuePtrs[Idx] = V;
355   return V;
356 }
357 
358 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
359   // If the TypeID is in range, return it.
360   if (ID < TypeList.size())
361     return TypeList[ID].get();
362   if (!isTypeTable) return 0;
363 
364   // The type table allows forward references.  Push as many Opaque types as
365   // needed to get up to ID.
366   while (TypeList.size() <= ID)
367     TypeList.push_back(OpaqueType::get(Context));
368   return TypeList.back().get();
369 }
370 
371 //===----------------------------------------------------------------------===//
372 //  Functions for parsing blocks from the bitcode file
373 //===----------------------------------------------------------------------===//
374 
375 bool BitcodeReader::ParseAttributeBlock() {
376   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
377     return Error("Malformed block record");
378 
379   if (!MAttributes.empty())
380     return Error("Multiple PARAMATTR blocks found!");
381 
382   SmallVector<uint64_t, 64> Record;
383 
384   SmallVector<AttributeWithIndex, 8> Attrs;
385 
386   // Read all the records.
387   while (1) {
388     unsigned Code = Stream.ReadCode();
389     if (Code == bitc::END_BLOCK) {
390       if (Stream.ReadBlockEnd())
391         return Error("Error at end of PARAMATTR block");
392       return false;
393     }
394 
395     if (Code == bitc::ENTER_SUBBLOCK) {
396       // No known subblocks, always skip them.
397       Stream.ReadSubBlockID();
398       if (Stream.SkipBlock())
399         return Error("Malformed block record");
400       continue;
401     }
402 
403     if (Code == bitc::DEFINE_ABBREV) {
404       Stream.ReadAbbrevRecord();
405       continue;
406     }
407 
408     // Read a record.
409     Record.clear();
410     switch (Stream.ReadRecord(Code, Record)) {
411     default:  // Default behavior: ignore.
412       break;
413     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
414       if (Record.size() & 1)
415         return Error("Invalid ENTRY record");
416 
417       // FIXME : Remove this autoupgrade code in LLVM 3.0.
418       // If Function attributes are using index 0 then transfer them
419       // to index ~0. Index 0 is used for return value attributes but used to be
420       // used for function attributes.
421       Attributes RetAttribute = Attribute::None;
422       Attributes FnAttribute = Attribute::None;
423       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
424         // FIXME: remove in LLVM 3.0
425         // The alignment is stored as a 16-bit raw value from bits 31--16.
426         // We shift the bits above 31 down by 11 bits.
427 
428         unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
429         if (Alignment && !isPowerOf2_32(Alignment))
430           return Error("Alignment is not a power of two.");
431 
432         Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
433         if (Alignment)
434           ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
435         ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
436         Record[i+1] = ReconstitutedAttr;
437 
438         if (Record[i] == 0)
439           RetAttribute = Record[i+1];
440         else if (Record[i] == ~0U)
441           FnAttribute = Record[i+1];
442       }
443 
444       unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
445                               Attribute::ReadOnly|Attribute::ReadNone);
446 
447       if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
448           (RetAttribute & OldRetAttrs) != 0) {
449         if (FnAttribute == Attribute::None) { // add a slot so they get added.
450           Record.push_back(~0U);
451           Record.push_back(0);
452         }
453 
454         FnAttribute  |= RetAttribute & OldRetAttrs;
455         RetAttribute &= ~OldRetAttrs;
456       }
457 
458       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
459         if (Record[i] == 0) {
460           if (RetAttribute != Attribute::None)
461             Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
462         } else if (Record[i] == ~0U) {
463           if (FnAttribute != Attribute::None)
464             Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
465         } else if (Record[i+1] != Attribute::None)
466           Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
467       }
468 
469       MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
470       Attrs.clear();
471       break;
472     }
473     }
474   }
475 }
476 
477 
478 bool BitcodeReader::ParseTypeTable() {
479   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
480     return Error("Malformed block record");
481 
482   if (!TypeList.empty())
483     return Error("Multiple TYPE_BLOCKs found!");
484 
485   SmallVector<uint64_t, 64> Record;
486   unsigned NumRecords = 0;
487 
488   // Read all the records for this type table.
489   while (1) {
490     unsigned Code = Stream.ReadCode();
491     if (Code == bitc::END_BLOCK) {
492       if (NumRecords != TypeList.size())
493         return Error("Invalid type forward reference in TYPE_BLOCK");
494       if (Stream.ReadBlockEnd())
495         return Error("Error at end of type table block");
496       return false;
497     }
498 
499     if (Code == bitc::ENTER_SUBBLOCK) {
500       // No known subblocks, always skip them.
501       Stream.ReadSubBlockID();
502       if (Stream.SkipBlock())
503         return Error("Malformed block record");
504       continue;
505     }
506 
507     if (Code == bitc::DEFINE_ABBREV) {
508       Stream.ReadAbbrevRecord();
509       continue;
510     }
511 
512     // Read a record.
513     Record.clear();
514     const Type *ResultTy = 0;
515     switch (Stream.ReadRecord(Code, Record)) {
516     default:  // Default behavior: unknown type.
517       ResultTy = 0;
518       break;
519     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
520       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
521       // type list.  This allows us to reserve space.
522       if (Record.size() < 1)
523         return Error("Invalid TYPE_CODE_NUMENTRY record");
524       TypeList.reserve(Record[0]);
525       continue;
526     case bitc::TYPE_CODE_VOID:      // VOID
527       ResultTy = Type::getVoidTy(Context);
528       break;
529     case bitc::TYPE_CODE_FLOAT:     // FLOAT
530       ResultTy = Type::getFloatTy(Context);
531       break;
532     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
533       ResultTy = Type::getDoubleTy(Context);
534       break;
535     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
536       ResultTy = Type::getX86_FP80Ty(Context);
537       break;
538     case bitc::TYPE_CODE_FP128:     // FP128
539       ResultTy = Type::getFP128Ty(Context);
540       break;
541     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
542       ResultTy = Type::getPPC_FP128Ty(Context);
543       break;
544     case bitc::TYPE_CODE_LABEL:     // LABEL
545       ResultTy = Type::getLabelTy(Context);
546       break;
547     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
548       ResultTy = 0;
549       break;
550     case bitc::TYPE_CODE_METADATA:  // METADATA
551       ResultTy = Type::getMetadataTy(Context);
552       break;
553     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
554       ResultTy = Type::getX86_MMXTy(Context);
555       break;
556     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
557       if (Record.size() < 1)
558         return Error("Invalid Integer type record");
559 
560       ResultTy = IntegerType::get(Context, Record[0]);
561       break;
562     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
563                                     //          [pointee type, address space]
564       if (Record.size() < 1)
565         return Error("Invalid POINTER type record");
566       unsigned AddressSpace = 0;
567       if (Record.size() == 2)
568         AddressSpace = Record[1];
569       ResultTy = PointerType::get(getTypeByID(Record[0], true),
570                                         AddressSpace);
571       break;
572     }
573     case bitc::TYPE_CODE_FUNCTION: {
574       // FIXME: attrid is dead, remove it in LLVM 3.0
575       // FUNCTION: [vararg, attrid, retty, paramty x N]
576       if (Record.size() < 3)
577         return Error("Invalid FUNCTION type record");
578       std::vector<const Type*> ArgTys;
579       for (unsigned i = 3, e = Record.size(); i != e; ++i)
580         ArgTys.push_back(getTypeByID(Record[i], true));
581 
582       ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
583                                    Record[0]);
584       break;
585     }
586     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
587       if (Record.size() < 1)
588         return Error("Invalid STRUCT type record");
589       std::vector<const Type*> EltTys;
590       for (unsigned i = 1, e = Record.size(); i != e; ++i)
591         EltTys.push_back(getTypeByID(Record[i], true));
592       ResultTy = StructType::get(Context, EltTys, Record[0]);
593       break;
594     }
595     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
596       if (Record.size() < 2)
597         return Error("Invalid ARRAY type record");
598       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
599       break;
600     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
601       if (Record.size() < 2)
602         return Error("Invalid VECTOR type record");
603       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
604       break;
605     }
606 
607     if (NumRecords == TypeList.size()) {
608       // If this is a new type slot, just append it.
609       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
610       ++NumRecords;
611     } else if (ResultTy == 0) {
612       // Otherwise, this was forward referenced, so an opaque type was created,
613       // but the result type is actually just an opaque.  Leave the one we
614       // created previously.
615       ++NumRecords;
616     } else {
617       // Otherwise, this was forward referenced, so an opaque type was created.
618       // Resolve the opaque type to the real type now.
619       assert(NumRecords < TypeList.size() && "Typelist imbalance");
620       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
621 
622       // Don't directly push the new type on the Tab. Instead we want to replace
623       // the opaque type we previously inserted with the new concrete value. The
624       // refinement from the abstract (opaque) type to the new type causes all
625       // uses of the abstract type to use the concrete type (NewTy). This will
626       // also cause the opaque type to be deleted.
627       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
628 
629       // This should have replaced the old opaque type with the new type in the
630       // value table... or with a preexisting type that was already in the
631       // system.  Let's just make sure it did.
632       assert(TypeList[NumRecords-1].get() != OldTy &&
633              "refineAbstractType didn't work!");
634     }
635   }
636 }
637 
638 
639 bool BitcodeReader::ParseTypeSymbolTable() {
640   if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
641     return Error("Malformed block record");
642 
643   SmallVector<uint64_t, 64> Record;
644 
645   // Read all the records for this type table.
646   std::string TypeName;
647   while (1) {
648     unsigned Code = Stream.ReadCode();
649     if (Code == bitc::END_BLOCK) {
650       if (Stream.ReadBlockEnd())
651         return Error("Error at end of type symbol table block");
652       return false;
653     }
654 
655     if (Code == bitc::ENTER_SUBBLOCK) {
656       // No known subblocks, always skip them.
657       Stream.ReadSubBlockID();
658       if (Stream.SkipBlock())
659         return Error("Malformed block record");
660       continue;
661     }
662 
663     if (Code == bitc::DEFINE_ABBREV) {
664       Stream.ReadAbbrevRecord();
665       continue;
666     }
667 
668     // Read a record.
669     Record.clear();
670     switch (Stream.ReadRecord(Code, Record)) {
671     default:  // Default behavior: unknown type.
672       break;
673     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
674       if (ConvertToString(Record, 1, TypeName))
675         return Error("Invalid TST_ENTRY record");
676       unsigned TypeID = Record[0];
677       if (TypeID >= TypeList.size())
678         return Error("Invalid Type ID in TST_ENTRY record");
679 
680       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
681       TypeName.clear();
682       break;
683     }
684   }
685 }
686 
687 bool BitcodeReader::ParseValueSymbolTable() {
688   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
689     return Error("Malformed block record");
690 
691   SmallVector<uint64_t, 64> Record;
692 
693   // Read all the records for this value table.
694   SmallString<128> ValueName;
695   while (1) {
696     unsigned Code = Stream.ReadCode();
697     if (Code == bitc::END_BLOCK) {
698       if (Stream.ReadBlockEnd())
699         return Error("Error at end of value symbol table block");
700       return false;
701     }
702     if (Code == bitc::ENTER_SUBBLOCK) {
703       // No known subblocks, always skip them.
704       Stream.ReadSubBlockID();
705       if (Stream.SkipBlock())
706         return Error("Malformed block record");
707       continue;
708     }
709 
710     if (Code == bitc::DEFINE_ABBREV) {
711       Stream.ReadAbbrevRecord();
712       continue;
713     }
714 
715     // Read a record.
716     Record.clear();
717     unsigned VSTCode = Stream.ReadRecord(Code, Record);
718     switch (VSTCode) {
719     default:  // Default behavior: unknown type.
720       break;
721     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
722       if (ConvertToString(Record, 1, ValueName))
723         return Error("Invalid VST_ENTRY record");
724       unsigned ValueID = Record[0];
725       if (ValueID >= ValueList.size())
726         return Error("Invalid Value ID in VST_ENTRY record");
727       Value *V = ValueList[ValueID];
728 
729       V->setName(StringRef(ValueName.data(), ValueName.size()));
730       ValueName.clear();
731       break;
732     }
733     case bitc::VST_CODE_BBENTRY:
734     case bitc::VST_CODE_LPADENTRY: {
735       if (ConvertToString(Record, 1, ValueName))
736         return Error("Invalid VST_BBENTRY record");
737       BasicBlock *BB = getBasicBlock(Record[0]);
738       if (BB == 0)
739         return Error("Invalid BB ID in VST_BBENTRY record");
740 
741       if (VSTCode == bitc::VST_CODE_LPADENTRY)
742         BB->setIsLandingPad(true);
743 
744       BB->setName(StringRef(ValueName.data(), ValueName.size()));
745       ValueName.clear();
746       break;
747     }
748     }
749   }
750 }
751 
752 bool BitcodeReader::ParseMetadata() {
753   unsigned NextMDValueNo = MDValueList.size();
754 
755   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
756     return Error("Malformed block record");
757 
758   SmallVector<uint64_t, 64> Record;
759 
760   // Read all the records.
761   while (1) {
762     unsigned Code = Stream.ReadCode();
763     if (Code == bitc::END_BLOCK) {
764       if (Stream.ReadBlockEnd())
765         return Error("Error at end of PARAMATTR block");
766       return false;
767     }
768 
769     if (Code == bitc::ENTER_SUBBLOCK) {
770       // No known subblocks, always skip them.
771       Stream.ReadSubBlockID();
772       if (Stream.SkipBlock())
773         return Error("Malformed block record");
774       continue;
775     }
776 
777     if (Code == bitc::DEFINE_ABBREV) {
778       Stream.ReadAbbrevRecord();
779       continue;
780     }
781 
782     bool IsFunctionLocal = false;
783     // Read a record.
784     Record.clear();
785     Code = Stream.ReadRecord(Code, Record);
786     switch (Code) {
787     default:  // Default behavior: ignore.
788       break;
789     case bitc::METADATA_NAME: {
790       // Read named of the named metadata.
791       unsigned NameLength = Record.size();
792       SmallString<8> Name;
793       Name.resize(NameLength);
794       for (unsigned i = 0; i != NameLength; ++i)
795         Name[i] = Record[i];
796       Record.clear();
797       Code = Stream.ReadCode();
798 
799       // METADATA_NAME is always followed by METADATA_NAMED_NODE2.
800       // Or METADATA_NAMED_NODE in LLVM 2.7. FIXME: Remove this in LLVM 3.0.
801       unsigned NextBitCode = Stream.ReadRecord(Code, Record);
802       if (NextBitCode == bitc::METADATA_NAMED_NODE) {
803         LLVM2_7MetadataDetected = true;
804       } else if (NextBitCode != bitc::METADATA_NAMED_NODE2)
805         assert ( 0 && "Invalid Named Metadata record");
806 
807       // Read named metadata elements.
808       unsigned Size = Record.size();
809       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
810       for (unsigned i = 0; i != Size; ++i) {
811         MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
812         if (MD == 0)
813           return Error("Malformed metadata record");
814         NMD->addOperand(MD);
815       }
816       // Backwards compatibility hack: NamedMDValues used to be Values,
817       // and they got their own slots in the value numbering. They are no
818       // longer Values, however we still need to account for them in the
819       // numbering in order to be able to read old bitcode files.
820       // FIXME: Remove this in LLVM 3.0.
821       if (LLVM2_7MetadataDetected)
822         MDValueList.AssignValue(0, NextMDValueNo++);
823       break;
824     }
825     case bitc::METADATA_FN_NODE: // FIXME: Remove in LLVM 3.0.
826     case bitc::METADATA_FN_NODE2:
827       IsFunctionLocal = true;
828       // fall-through
829     case bitc::METADATA_NODE:    // FIXME: Remove in LLVM 3.0.
830     case bitc::METADATA_NODE2: {
831 
832       // Detect 2.7-era metadata.
833       // FIXME: Remove in LLVM 3.0.
834       if (Code == bitc::METADATA_FN_NODE || Code == bitc::METADATA_NODE)
835         LLVM2_7MetadataDetected = true;
836 
837       if (Record.size() % 2 == 1)
838         return Error("Invalid METADATA_NODE2 record");
839 
840       unsigned Size = Record.size();
841       SmallVector<Value*, 8> Elts;
842       for (unsigned i = 0; i != Size; i += 2) {
843         const Type *Ty = getTypeByID(Record[i]);
844         if (!Ty) return Error("Invalid METADATA_NODE2 record");
845         if (Ty->isMetadataTy())
846           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
847         else if (!Ty->isVoidTy())
848           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
849         else
850           Elts.push_back(NULL);
851       }
852       Value *V = MDNode::getWhenValsUnresolved(Context,
853                                                Elts.data(), Elts.size(),
854                                                IsFunctionLocal);
855       IsFunctionLocal = false;
856       MDValueList.AssignValue(V, NextMDValueNo++);
857       break;
858     }
859     case bitc::METADATA_STRING: {
860       unsigned MDStringLength = Record.size();
861       SmallString<8> String;
862       String.resize(MDStringLength);
863       for (unsigned i = 0; i != MDStringLength; ++i)
864         String[i] = Record[i];
865       Value *V = MDString::get(Context,
866                                StringRef(String.data(), String.size()));
867       MDValueList.AssignValue(V, NextMDValueNo++);
868       break;
869     }
870     case bitc::METADATA_KIND: {
871       unsigned RecordLength = Record.size();
872       if (Record.empty() || RecordLength < 2)
873         return Error("Invalid METADATA_KIND record");
874       SmallString<8> Name;
875       Name.resize(RecordLength-1);
876       unsigned Kind = Record[0];
877       for (unsigned i = 1; i != RecordLength; ++i)
878         Name[i-1] = Record[i];
879 
880       unsigned NewKind = TheModule->getMDKindID(Name.str());
881       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
882         return Error("Conflicting METADATA_KIND records");
883       break;
884     }
885     }
886   }
887 }
888 
889 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
890 /// the LSB for dense VBR encoding.
891 static uint64_t DecodeSignRotatedValue(uint64_t V) {
892   if ((V & 1) == 0)
893     return V >> 1;
894   if (V != 1)
895     return -(V >> 1);
896   // There is no such thing as -0 with integers.  "-0" really means MININT.
897   return 1ULL << 63;
898 }
899 
900 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
901 /// values and aliases that we can.
902 bool BitcodeReader::ResolveGlobalAndAliasInits() {
903   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
904   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
905 
906   GlobalInitWorklist.swap(GlobalInits);
907   AliasInitWorklist.swap(AliasInits);
908 
909   while (!GlobalInitWorklist.empty()) {
910     unsigned ValID = GlobalInitWorklist.back().second;
911     if (ValID >= ValueList.size()) {
912       // Not ready to resolve this yet, it requires something later in the file.
913       GlobalInits.push_back(GlobalInitWorklist.back());
914     } else {
915       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
916         GlobalInitWorklist.back().first->setInitializer(C);
917       else
918         return Error("Global variable initializer is not a constant!");
919     }
920     GlobalInitWorklist.pop_back();
921   }
922 
923   while (!AliasInitWorklist.empty()) {
924     unsigned ValID = AliasInitWorklist.back().second;
925     if (ValID >= ValueList.size()) {
926       AliasInits.push_back(AliasInitWorklist.back());
927     } else {
928       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
929         AliasInitWorklist.back().first->setAliasee(C);
930       else
931         return Error("Alias initializer is not a constant!");
932     }
933     AliasInitWorklist.pop_back();
934   }
935   return false;
936 }
937 
938 bool BitcodeReader::ParseConstants() {
939   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
940     return Error("Malformed block record");
941 
942   SmallVector<uint64_t, 64> Record;
943 
944   // Read all the records for this value table.
945   const Type *CurTy = Type::getInt32Ty(Context);
946   unsigned NextCstNo = ValueList.size();
947   while (1) {
948     unsigned Code = Stream.ReadCode();
949     if (Code == bitc::END_BLOCK)
950       break;
951 
952     if (Code == bitc::ENTER_SUBBLOCK) {
953       // No known subblocks, always skip them.
954       Stream.ReadSubBlockID();
955       if (Stream.SkipBlock())
956         return Error("Malformed block record");
957       continue;
958     }
959 
960     if (Code == bitc::DEFINE_ABBREV) {
961       Stream.ReadAbbrevRecord();
962       continue;
963     }
964 
965     // Read a record.
966     Record.clear();
967     Value *V = 0;
968     unsigned BitCode = Stream.ReadRecord(Code, Record);
969     switch (BitCode) {
970     default:  // Default behavior: unknown constant
971     case bitc::CST_CODE_UNDEF:     // UNDEF
972       V = UndefValue::get(CurTy);
973       break;
974     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
975       if (Record.empty())
976         return Error("Malformed CST_SETTYPE record");
977       if (Record[0] >= TypeList.size())
978         return Error("Invalid Type ID in CST_SETTYPE record");
979       CurTy = TypeList[Record[0]];
980       continue;  // Skip the ValueList manipulation.
981     case bitc::CST_CODE_NULL:      // NULL
982       V = Constant::getNullValue(CurTy);
983       break;
984     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
985       if (!CurTy->isIntegerTy() || Record.empty())
986         return Error("Invalid CST_INTEGER record");
987       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
988       break;
989     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
990       if (!CurTy->isIntegerTy() || Record.empty())
991         return Error("Invalid WIDE_INTEGER record");
992 
993       unsigned NumWords = Record.size();
994       SmallVector<uint64_t, 8> Words;
995       Words.resize(NumWords);
996       for (unsigned i = 0; i != NumWords; ++i)
997         Words[i] = DecodeSignRotatedValue(Record[i]);
998       V = ConstantInt::get(Context,
999                            APInt(cast<IntegerType>(CurTy)->getBitWidth(),
1000                            NumWords, &Words[0]));
1001       break;
1002     }
1003     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1004       if (Record.empty())
1005         return Error("Invalid FLOAT record");
1006       if (CurTy->isFloatTy())
1007         V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1008       else if (CurTy->isDoubleTy())
1009         V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1010       else if (CurTy->isX86_FP80Ty()) {
1011         // Bits are not stored the same way as a normal i80 APInt, compensate.
1012         uint64_t Rearrange[2];
1013         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1014         Rearrange[1] = Record[0] >> 48;
1015         V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
1016       } else if (CurTy->isFP128Ty())
1017         V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
1018       else if (CurTy->isPPC_FP128Ty())
1019         V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
1020       else
1021         V = UndefValue::get(CurTy);
1022       break;
1023     }
1024 
1025     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1026       if (Record.empty())
1027         return Error("Invalid CST_AGGREGATE record");
1028 
1029       unsigned Size = Record.size();
1030       std::vector<Constant*> Elts;
1031 
1032       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
1033         for (unsigned i = 0; i != Size; ++i)
1034           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1035                                                      STy->getElementType(i)));
1036         V = ConstantStruct::get(STy, Elts);
1037       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1038         const Type *EltTy = ATy->getElementType();
1039         for (unsigned i = 0; i != Size; ++i)
1040           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1041         V = ConstantArray::get(ATy, Elts);
1042       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1043         const Type *EltTy = VTy->getElementType();
1044         for (unsigned i = 0; i != Size; ++i)
1045           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1046         V = ConstantVector::get(Elts);
1047       } else {
1048         V = UndefValue::get(CurTy);
1049       }
1050       break;
1051     }
1052     case bitc::CST_CODE_STRING: { // STRING: [values]
1053       if (Record.empty())
1054         return Error("Invalid CST_AGGREGATE record");
1055 
1056       const ArrayType *ATy = cast<ArrayType>(CurTy);
1057       const Type *EltTy = ATy->getElementType();
1058 
1059       unsigned Size = Record.size();
1060       std::vector<Constant*> Elts;
1061       for (unsigned i = 0; i != Size; ++i)
1062         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1063       V = ConstantArray::get(ATy, Elts);
1064       break;
1065     }
1066     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1067       if (Record.empty())
1068         return Error("Invalid CST_AGGREGATE record");
1069 
1070       const ArrayType *ATy = cast<ArrayType>(CurTy);
1071       const Type *EltTy = ATy->getElementType();
1072 
1073       unsigned Size = Record.size();
1074       std::vector<Constant*> Elts;
1075       for (unsigned i = 0; i != Size; ++i)
1076         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1077       Elts.push_back(Constant::getNullValue(EltTy));
1078       V = ConstantArray::get(ATy, Elts);
1079       break;
1080     }
1081     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1082       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1083       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1084       if (Opc < 0) {
1085         V = UndefValue::get(CurTy);  // Unknown binop.
1086       } else {
1087         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1088         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1089         unsigned Flags = 0;
1090         if (Record.size() >= 4) {
1091           if (Opc == Instruction::Add ||
1092               Opc == Instruction::Sub ||
1093               Opc == Instruction::Mul ||
1094               Opc == Instruction::Shl) {
1095             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1096               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1097             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1098               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1099           } else if (Opc == Instruction::SDiv ||
1100                      Opc == Instruction::UDiv ||
1101                      Opc == Instruction::LShr ||
1102                      Opc == Instruction::AShr) {
1103             if (Record[3] & (1 << bitc::PEO_EXACT))
1104               Flags |= SDivOperator::IsExact;
1105           }
1106         }
1107         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1108       }
1109       break;
1110     }
1111     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1112       if (Record.size() < 3) return Error("Invalid CE_CAST record");
1113       int Opc = GetDecodedCastOpcode(Record[0]);
1114       if (Opc < 0) {
1115         V = UndefValue::get(CurTy);  // Unknown cast.
1116       } else {
1117         const Type *OpTy = getTypeByID(Record[1]);
1118         if (!OpTy) return Error("Invalid CE_CAST record");
1119         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1120         V = ConstantExpr::getCast(Opc, Op, CurTy);
1121       }
1122       break;
1123     }
1124     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1125     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1126       if (Record.size() & 1) return Error("Invalid CE_GEP record");
1127       SmallVector<Constant*, 16> Elts;
1128       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1129         const Type *ElTy = getTypeByID(Record[i]);
1130         if (!ElTy) return Error("Invalid CE_GEP record");
1131         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1132       }
1133       if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1134         V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1135                                                    Elts.size()-1);
1136       else
1137         V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1138                                            Elts.size()-1);
1139       break;
1140     }
1141     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1142       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1143       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1144                                                               Type::getInt1Ty(Context)),
1145                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1146                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1147       break;
1148     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1149       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1150       const VectorType *OpTy =
1151         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1152       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1153       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1154       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1155       V = ConstantExpr::getExtractElement(Op0, Op1);
1156       break;
1157     }
1158     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1159       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1160       if (Record.size() < 3 || OpTy == 0)
1161         return Error("Invalid CE_INSERTELT record");
1162       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1163       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1164                                                   OpTy->getElementType());
1165       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1166       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1167       break;
1168     }
1169     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1170       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1171       if (Record.size() < 3 || OpTy == 0)
1172         return Error("Invalid CE_SHUFFLEVEC record");
1173       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1174       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1175       const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1176                                                  OpTy->getNumElements());
1177       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1178       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1179       break;
1180     }
1181     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1182       const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1183       const VectorType *OpTy =
1184         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1185       if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1186         return Error("Invalid CE_SHUFVEC_EX record");
1187       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1188       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1189       const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1190                                                  RTy->getNumElements());
1191       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1192       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1193       break;
1194     }
1195     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1196       if (Record.size() < 4) return Error("Invalid CE_CMP record");
1197       const Type *OpTy = getTypeByID(Record[0]);
1198       if (OpTy == 0) return Error("Invalid CE_CMP record");
1199       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1200       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1201 
1202       if (OpTy->isFPOrFPVectorTy())
1203         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1204       else
1205         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1206       break;
1207     }
1208     case bitc::CST_CODE_INLINEASM: {
1209       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1210       std::string AsmStr, ConstrStr;
1211       bool HasSideEffects = Record[0] & 1;
1212       bool IsAlignStack = Record[0] >> 1;
1213       unsigned AsmStrSize = Record[1];
1214       if (2+AsmStrSize >= Record.size())
1215         return Error("Invalid INLINEASM record");
1216       unsigned ConstStrSize = Record[2+AsmStrSize];
1217       if (3+AsmStrSize+ConstStrSize > Record.size())
1218         return Error("Invalid INLINEASM record");
1219 
1220       for (unsigned i = 0; i != AsmStrSize; ++i)
1221         AsmStr += (char)Record[2+i];
1222       for (unsigned i = 0; i != ConstStrSize; ++i)
1223         ConstrStr += (char)Record[3+AsmStrSize+i];
1224       const PointerType *PTy = cast<PointerType>(CurTy);
1225       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1226                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1227       break;
1228     }
1229     case bitc::CST_CODE_BLOCKADDRESS:{
1230       if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1231       const Type *FnTy = getTypeByID(Record[0]);
1232       if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1233       Function *Fn =
1234         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1235       if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1236 
1237       GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1238                                                   Type::getInt8Ty(Context),
1239                                             false, GlobalValue::InternalLinkage,
1240                                                   0, "");
1241       BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1242       V = FwdRef;
1243       break;
1244     }
1245     }
1246 
1247     ValueList.AssignValue(V, NextCstNo);
1248     ++NextCstNo;
1249   }
1250 
1251   if (NextCstNo != ValueList.size())
1252     return Error("Invalid constant reference!");
1253 
1254   if (Stream.ReadBlockEnd())
1255     return Error("Error at end of constants block");
1256 
1257   // Once all the constants have been read, go through and resolve forward
1258   // references.
1259   ValueList.ResolveConstantForwardRefs();
1260   return false;
1261 }
1262 
1263 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1264 /// remember where it is and then skip it.  This lets us lazily deserialize the
1265 /// functions.
1266 bool BitcodeReader::RememberAndSkipFunctionBody() {
1267   // Get the function we are talking about.
1268   if (FunctionsWithBodies.empty())
1269     return Error("Insufficient function protos");
1270 
1271   Function *Fn = FunctionsWithBodies.back();
1272   FunctionsWithBodies.pop_back();
1273 
1274   // Save the current stream state.
1275   uint64_t CurBit = Stream.GetCurrentBitNo();
1276   DeferredFunctionInfo[Fn] = CurBit;
1277 
1278   // Skip over the function block for now.
1279   if (Stream.SkipBlock())
1280     return Error("Malformed block record");
1281   return false;
1282 }
1283 
1284 bool BitcodeReader::ParseModule() {
1285   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1286     return Error("Malformed block record");
1287 
1288   SmallVector<uint64_t, 64> Record;
1289   std::vector<std::string> SectionTable;
1290   std::vector<std::string> GCTable;
1291 
1292   // Read all the records for this module.
1293   while (!Stream.AtEndOfStream()) {
1294     unsigned Code = Stream.ReadCode();
1295     if (Code == bitc::END_BLOCK) {
1296       if (Stream.ReadBlockEnd())
1297         return Error("Error at end of module block");
1298 
1299       // Patch the initializers for globals and aliases up.
1300       ResolveGlobalAndAliasInits();
1301       if (!GlobalInits.empty() || !AliasInits.empty())
1302         return Error("Malformed global initializer set");
1303       if (!FunctionsWithBodies.empty())
1304         return Error("Too few function bodies found");
1305 
1306       // Look for intrinsic functions which need to be upgraded at some point
1307       for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1308            FI != FE; ++FI) {
1309         Function* NewFn;
1310         if (UpgradeIntrinsicFunction(FI, NewFn))
1311           UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1312       }
1313 
1314       // Look for global variables which need to be renamed.
1315       for (Module::global_iterator
1316              GI = TheModule->global_begin(), GE = TheModule->global_end();
1317            GI != GE; ++GI)
1318         UpgradeGlobalVariable(GI);
1319 
1320       // Force deallocation of memory for these vectors to favor the client that
1321       // want lazy deserialization.
1322       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1323       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1324       std::vector<Function*>().swap(FunctionsWithBodies);
1325       return false;
1326     }
1327 
1328     if (Code == bitc::ENTER_SUBBLOCK) {
1329       switch (Stream.ReadSubBlockID()) {
1330       default:  // Skip unknown content.
1331         if (Stream.SkipBlock())
1332           return Error("Malformed block record");
1333         break;
1334       case bitc::BLOCKINFO_BLOCK_ID:
1335         if (Stream.ReadBlockInfoBlock())
1336           return Error("Malformed BlockInfoBlock");
1337         break;
1338       case bitc::PARAMATTR_BLOCK_ID:
1339         if (ParseAttributeBlock())
1340           return true;
1341         break;
1342       case bitc::TYPE_BLOCK_ID:
1343         if (ParseTypeTable())
1344           return true;
1345         break;
1346       case bitc::TYPE_SYMTAB_BLOCK_ID:
1347         if (ParseTypeSymbolTable())
1348           return true;
1349         break;
1350       case bitc::VALUE_SYMTAB_BLOCK_ID:
1351         if (ParseValueSymbolTable())
1352           return true;
1353         break;
1354       case bitc::CONSTANTS_BLOCK_ID:
1355         if (ParseConstants() || ResolveGlobalAndAliasInits())
1356           return true;
1357         break;
1358       case bitc::METADATA_BLOCK_ID:
1359         if (ParseMetadata())
1360           return true;
1361         break;
1362       case bitc::FUNCTION_BLOCK_ID:
1363         // If this is the first function body we've seen, reverse the
1364         // FunctionsWithBodies list.
1365         if (!HasReversedFunctionsWithBodies) {
1366           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1367           HasReversedFunctionsWithBodies = true;
1368         }
1369 
1370         if (RememberAndSkipFunctionBody())
1371           return true;
1372         break;
1373       }
1374       continue;
1375     }
1376 
1377     if (Code == bitc::DEFINE_ABBREV) {
1378       Stream.ReadAbbrevRecord();
1379       continue;
1380     }
1381 
1382     // Read a record.
1383     switch (Stream.ReadRecord(Code, Record)) {
1384     default: break;  // Default behavior, ignore unknown content.
1385     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1386       if (Record.size() < 1)
1387         return Error("Malformed MODULE_CODE_VERSION");
1388       // Only version #0 is supported so far.
1389       if (Record[0] != 0)
1390         return Error("Unknown bitstream version!");
1391       break;
1392     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1393       std::string S;
1394       if (ConvertToString(Record, 0, S))
1395         return Error("Invalid MODULE_CODE_TRIPLE record");
1396       TheModule->setTargetTriple(S);
1397       break;
1398     }
1399     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1400       std::string S;
1401       if (ConvertToString(Record, 0, S))
1402         return Error("Invalid MODULE_CODE_DATALAYOUT record");
1403       TheModule->setDataLayout(S);
1404       break;
1405     }
1406     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1407       std::string S;
1408       if (ConvertToString(Record, 0, S))
1409         return Error("Invalid MODULE_CODE_ASM record");
1410       TheModule->setModuleInlineAsm(S);
1411       break;
1412     }
1413     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1414       std::string S;
1415       if (ConvertToString(Record, 0, S))
1416         return Error("Invalid MODULE_CODE_DEPLIB record");
1417       TheModule->addLibrary(S);
1418       break;
1419     }
1420     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1421       std::string S;
1422       if (ConvertToString(Record, 0, S))
1423         return Error("Invalid MODULE_CODE_SECTIONNAME record");
1424       SectionTable.push_back(S);
1425       break;
1426     }
1427     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1428       std::string S;
1429       if (ConvertToString(Record, 0, S))
1430         return Error("Invalid MODULE_CODE_GCNAME record");
1431       GCTable.push_back(S);
1432       break;
1433     }
1434     // GLOBALVAR: [pointer type, isconst, initid,
1435     //             linkage, alignment, section, visibility, threadlocal,
1436     //             unnamed_addr]
1437     case bitc::MODULE_CODE_GLOBALVAR: {
1438       if (Record.size() < 6)
1439         return Error("Invalid MODULE_CODE_GLOBALVAR record");
1440       const Type *Ty = getTypeByID(Record[0]);
1441       if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1442       if (!Ty->isPointerTy())
1443         return Error("Global not a pointer type!");
1444       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1445       Ty = cast<PointerType>(Ty)->getElementType();
1446 
1447       bool isConstant = Record[1];
1448       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1449       unsigned Alignment = (1 << Record[4]) >> 1;
1450       std::string Section;
1451       if (Record[5]) {
1452         if (Record[5]-1 >= SectionTable.size())
1453           return Error("Invalid section ID");
1454         Section = SectionTable[Record[5]-1];
1455       }
1456       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1457       if (Record.size() > 6)
1458         Visibility = GetDecodedVisibility(Record[6]);
1459       bool isThreadLocal = false;
1460       if (Record.size() > 7)
1461         isThreadLocal = Record[7];
1462 
1463       bool UnnamedAddr = false;
1464       if (Record.size() > 8)
1465         UnnamedAddr = Record[8];
1466 
1467       GlobalVariable *NewGV =
1468         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1469                            isThreadLocal, AddressSpace);
1470       NewGV->setAlignment(Alignment);
1471       if (!Section.empty())
1472         NewGV->setSection(Section);
1473       NewGV->setVisibility(Visibility);
1474       NewGV->setThreadLocal(isThreadLocal);
1475       NewGV->setUnnamedAddr(UnnamedAddr);
1476 
1477       ValueList.push_back(NewGV);
1478 
1479       // Remember which value to use for the global initializer.
1480       if (unsigned InitID = Record[2])
1481         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1482       break;
1483     }
1484     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1485     //             alignment, section, visibility, gc, unnamed_addr]
1486     case bitc::MODULE_CODE_FUNCTION: {
1487       if (Record.size() < 8)
1488         return Error("Invalid MODULE_CODE_FUNCTION record");
1489       const Type *Ty = getTypeByID(Record[0]);
1490       if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1491       if (!Ty->isPointerTy())
1492         return Error("Function not a pointer type!");
1493       const FunctionType *FTy =
1494         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1495       if (!FTy)
1496         return Error("Function not a pointer to function type!");
1497 
1498       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1499                                         "", TheModule);
1500 
1501       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1502       bool isProto = Record[2];
1503       Func->setLinkage(GetDecodedLinkage(Record[3]));
1504       Func->setAttributes(getAttributes(Record[4]));
1505 
1506       Func->setAlignment((1 << Record[5]) >> 1);
1507       if (Record[6]) {
1508         if (Record[6]-1 >= SectionTable.size())
1509           return Error("Invalid section ID");
1510         Func->setSection(SectionTable[Record[6]-1]);
1511       }
1512       Func->setVisibility(GetDecodedVisibility(Record[7]));
1513       if (Record.size() > 8 && Record[8]) {
1514         if (Record[8]-1 > GCTable.size())
1515           return Error("Invalid GC ID");
1516         Func->setGC(GCTable[Record[8]-1].c_str());
1517       }
1518       bool UnnamedAddr = false;
1519       if (Record.size() > 9)
1520         UnnamedAddr = Record[9];
1521       Func->setUnnamedAddr(UnnamedAddr);
1522       ValueList.push_back(Func);
1523 
1524       // If this is a function with a body, remember the prototype we are
1525       // creating now, so that we can match up the body with them later.
1526       if (!isProto)
1527         FunctionsWithBodies.push_back(Func);
1528       break;
1529     }
1530     // ALIAS: [alias type, aliasee val#, linkage]
1531     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1532     case bitc::MODULE_CODE_ALIAS: {
1533       if (Record.size() < 3)
1534         return Error("Invalid MODULE_ALIAS record");
1535       const Type *Ty = getTypeByID(Record[0]);
1536       if (!Ty) return Error("Invalid MODULE_ALIAS record");
1537       if (!Ty->isPointerTy())
1538         return Error("Function not a pointer type!");
1539 
1540       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1541                                            "", 0, TheModule);
1542       // Old bitcode files didn't have visibility field.
1543       if (Record.size() > 3)
1544         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1545       ValueList.push_back(NewGA);
1546       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1547       break;
1548     }
1549     /// MODULE_CODE_PURGEVALS: [numvals]
1550     case bitc::MODULE_CODE_PURGEVALS:
1551       // Trim down the value list to the specified size.
1552       if (Record.size() < 1 || Record[0] > ValueList.size())
1553         return Error("Invalid MODULE_PURGEVALS record");
1554       ValueList.shrinkTo(Record[0]);
1555       break;
1556     }
1557     Record.clear();
1558   }
1559 
1560   return Error("Premature end of bitstream");
1561 }
1562 
1563 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1564   TheModule = 0;
1565 
1566   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1567   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1568 
1569   if (Buffer->getBufferSize() & 3) {
1570     if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1571       return Error("Invalid bitcode signature");
1572     else
1573       return Error("Bitcode stream should be a multiple of 4 bytes in length");
1574   }
1575 
1576   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1577   // The magic number is 0x0B17C0DE stored in little endian.
1578   if (isBitcodeWrapper(BufPtr, BufEnd))
1579     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1580       return Error("Invalid bitcode wrapper header");
1581 
1582   StreamFile.init(BufPtr, BufEnd);
1583   Stream.init(StreamFile);
1584 
1585   // Sniff for the signature.
1586   if (Stream.Read(8) != 'B' ||
1587       Stream.Read(8) != 'C' ||
1588       Stream.Read(4) != 0x0 ||
1589       Stream.Read(4) != 0xC ||
1590       Stream.Read(4) != 0xE ||
1591       Stream.Read(4) != 0xD)
1592     return Error("Invalid bitcode signature");
1593 
1594   // We expect a number of well-defined blocks, though we don't necessarily
1595   // need to understand them all.
1596   while (!Stream.AtEndOfStream()) {
1597     unsigned Code = Stream.ReadCode();
1598 
1599     if (Code != bitc::ENTER_SUBBLOCK)
1600       return Error("Invalid record at top-level");
1601 
1602     unsigned BlockID = Stream.ReadSubBlockID();
1603 
1604     // We only know the MODULE subblock ID.
1605     switch (BlockID) {
1606     case bitc::BLOCKINFO_BLOCK_ID:
1607       if (Stream.ReadBlockInfoBlock())
1608         return Error("Malformed BlockInfoBlock");
1609       break;
1610     case bitc::MODULE_BLOCK_ID:
1611       // Reject multiple MODULE_BLOCK's in a single bitstream.
1612       if (TheModule)
1613         return Error("Multiple MODULE_BLOCKs in same stream");
1614       TheModule = M;
1615       if (ParseModule())
1616         return true;
1617       break;
1618     default:
1619       if (Stream.SkipBlock())
1620         return Error("Malformed block record");
1621       break;
1622     }
1623   }
1624 
1625   return false;
1626 }
1627 
1628 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1629   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1630     return Error("Malformed block record");
1631 
1632   SmallVector<uint64_t, 64> Record;
1633 
1634   // Read all the records for this module.
1635   while (!Stream.AtEndOfStream()) {
1636     unsigned Code = Stream.ReadCode();
1637     if (Code == bitc::END_BLOCK) {
1638       if (Stream.ReadBlockEnd())
1639         return Error("Error at end of module block");
1640 
1641       return false;
1642     }
1643 
1644     if (Code == bitc::ENTER_SUBBLOCK) {
1645       switch (Stream.ReadSubBlockID()) {
1646       default:  // Skip unknown content.
1647         if (Stream.SkipBlock())
1648           return Error("Malformed block record");
1649         break;
1650       }
1651       continue;
1652     }
1653 
1654     if (Code == bitc::DEFINE_ABBREV) {
1655       Stream.ReadAbbrevRecord();
1656       continue;
1657     }
1658 
1659     // Read a record.
1660     switch (Stream.ReadRecord(Code, Record)) {
1661     default: break;  // Default behavior, ignore unknown content.
1662     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1663       if (Record.size() < 1)
1664         return Error("Malformed MODULE_CODE_VERSION");
1665       // Only version #0 is supported so far.
1666       if (Record[0] != 0)
1667         return Error("Unknown bitstream version!");
1668       break;
1669     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1670       std::string S;
1671       if (ConvertToString(Record, 0, S))
1672         return Error("Invalid MODULE_CODE_TRIPLE record");
1673       Triple = S;
1674       break;
1675     }
1676     }
1677     Record.clear();
1678   }
1679 
1680   return Error("Premature end of bitstream");
1681 }
1682 
1683 bool BitcodeReader::ParseTriple(std::string &Triple) {
1684   if (Buffer->getBufferSize() & 3)
1685     return Error("Bitcode stream should be a multiple of 4 bytes in length");
1686 
1687   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1688   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1689 
1690   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1691   // The magic number is 0x0B17C0DE stored in little endian.
1692   if (isBitcodeWrapper(BufPtr, BufEnd))
1693     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1694       return Error("Invalid bitcode wrapper header");
1695 
1696   StreamFile.init(BufPtr, BufEnd);
1697   Stream.init(StreamFile);
1698 
1699   // Sniff for the signature.
1700   if (Stream.Read(8) != 'B' ||
1701       Stream.Read(8) != 'C' ||
1702       Stream.Read(4) != 0x0 ||
1703       Stream.Read(4) != 0xC ||
1704       Stream.Read(4) != 0xE ||
1705       Stream.Read(4) != 0xD)
1706     return Error("Invalid bitcode signature");
1707 
1708   // We expect a number of well-defined blocks, though we don't necessarily
1709   // need to understand them all.
1710   while (!Stream.AtEndOfStream()) {
1711     unsigned Code = Stream.ReadCode();
1712 
1713     if (Code != bitc::ENTER_SUBBLOCK)
1714       return Error("Invalid record at top-level");
1715 
1716     unsigned BlockID = Stream.ReadSubBlockID();
1717 
1718     // We only know the MODULE subblock ID.
1719     switch (BlockID) {
1720     case bitc::MODULE_BLOCK_ID:
1721       if (ParseModuleTriple(Triple))
1722         return true;
1723       break;
1724     default:
1725       if (Stream.SkipBlock())
1726         return Error("Malformed block record");
1727       break;
1728     }
1729   }
1730 
1731   return false;
1732 }
1733 
1734 /// ParseMetadataAttachment - Parse metadata attachments.
1735 bool BitcodeReader::ParseMetadataAttachment() {
1736   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1737     return Error("Malformed block record");
1738 
1739   SmallVector<uint64_t, 64> Record;
1740   while(1) {
1741     unsigned Code = Stream.ReadCode();
1742     if (Code == bitc::END_BLOCK) {
1743       if (Stream.ReadBlockEnd())
1744         return Error("Error at end of PARAMATTR block");
1745       break;
1746     }
1747     if (Code == bitc::DEFINE_ABBREV) {
1748       Stream.ReadAbbrevRecord();
1749       continue;
1750     }
1751     // Read a metadata attachment record.
1752     Record.clear();
1753     switch (Stream.ReadRecord(Code, Record)) {
1754     default:  // Default behavior: ignore.
1755       break;
1756     // FIXME: Remove in LLVM 3.0.
1757     case bitc::METADATA_ATTACHMENT:
1758       LLVM2_7MetadataDetected = true;
1759     case bitc::METADATA_ATTACHMENT2: {
1760       unsigned RecordLength = Record.size();
1761       if (Record.empty() || (RecordLength - 1) % 2 == 1)
1762         return Error ("Invalid METADATA_ATTACHMENT reader!");
1763       Instruction *Inst = InstructionList[Record[0]];
1764       for (unsigned i = 1; i != RecordLength; i = i+2) {
1765         unsigned Kind = Record[i];
1766         DenseMap<unsigned, unsigned>::iterator I =
1767           MDKindMap.find(Kind);
1768         if (I == MDKindMap.end())
1769           return Error("Invalid metadata kind ID");
1770         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1771         Inst->setMetadata(I->second, cast<MDNode>(Node));
1772       }
1773       break;
1774     }
1775     }
1776   }
1777   return false;
1778 }
1779 
1780 /// ParseFunctionBody - Lazily parse the specified function body block.
1781 bool BitcodeReader::ParseFunctionBody(Function *F) {
1782   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1783     return Error("Malformed block record");
1784 
1785   InstructionList.clear();
1786   unsigned ModuleValueListSize = ValueList.size();
1787   unsigned ModuleMDValueListSize = MDValueList.size();
1788 
1789   // Add all the function arguments to the value table.
1790   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1791     ValueList.push_back(I);
1792 
1793   unsigned NextValueNo = ValueList.size();
1794   BasicBlock *CurBB = 0;
1795   unsigned CurBBNo = 0;
1796 
1797   DebugLoc LastLoc;
1798 
1799   // Read all the records.
1800   SmallVector<uint64_t, 64> Record;
1801   while (1) {
1802     unsigned Code = Stream.ReadCode();
1803     if (Code == bitc::END_BLOCK) {
1804       if (Stream.ReadBlockEnd())
1805         return Error("Error at end of function block");
1806       break;
1807     }
1808 
1809     if (Code == bitc::ENTER_SUBBLOCK) {
1810       switch (Stream.ReadSubBlockID()) {
1811       default:  // Skip unknown content.
1812         if (Stream.SkipBlock())
1813           return Error("Malformed block record");
1814         break;
1815       case bitc::CONSTANTS_BLOCK_ID:
1816         if (ParseConstants()) return true;
1817         NextValueNo = ValueList.size();
1818         break;
1819       case bitc::VALUE_SYMTAB_BLOCK_ID:
1820         if (ParseValueSymbolTable()) return true;
1821         break;
1822       case bitc::METADATA_ATTACHMENT_ID:
1823         if (ParseMetadataAttachment()) return true;
1824         break;
1825       case bitc::METADATA_BLOCK_ID:
1826         if (ParseMetadata()) return true;
1827         break;
1828       }
1829       continue;
1830     }
1831 
1832     if (Code == bitc::DEFINE_ABBREV) {
1833       Stream.ReadAbbrevRecord();
1834       continue;
1835     }
1836 
1837     // Read a record.
1838     Record.clear();
1839     Instruction *I = 0;
1840     unsigned BitCode = Stream.ReadRecord(Code, Record);
1841     switch (BitCode) {
1842     default: // Default behavior: reject
1843       return Error("Unknown instruction");
1844     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1845       if (Record.size() < 1 || Record[0] == 0)
1846         return Error("Invalid DECLAREBLOCKS record");
1847       // Create all the basic blocks for the function.
1848       FunctionBBs.resize(Record[0]);
1849       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1850         FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1851       CurBB = FunctionBBs[0];
1852       continue;
1853 
1854 
1855     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
1856       // This record indicates that the last instruction is at the same
1857       // location as the previous instruction with a location.
1858       I = 0;
1859 
1860       // Get the last instruction emitted.
1861       if (CurBB && !CurBB->empty())
1862         I = &CurBB->back();
1863       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1864                !FunctionBBs[CurBBNo-1]->empty())
1865         I = &FunctionBBs[CurBBNo-1]->back();
1866 
1867       if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1868       I->setDebugLoc(LastLoc);
1869       I = 0;
1870       continue;
1871 
1872     // FIXME: Remove this in LLVM 3.0.
1873     case bitc::FUNC_CODE_DEBUG_LOC:
1874       LLVM2_7MetadataDetected = true;
1875     case bitc::FUNC_CODE_DEBUG_LOC2: {      // DEBUG_LOC: [line, col, scope, ia]
1876       I = 0;     // Get the last instruction emitted.
1877       if (CurBB && !CurBB->empty())
1878         I = &CurBB->back();
1879       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1880                !FunctionBBs[CurBBNo-1]->empty())
1881         I = &FunctionBBs[CurBBNo-1]->back();
1882       if (I == 0 || Record.size() < 4)
1883         return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1884 
1885       unsigned Line = Record[0], Col = Record[1];
1886       unsigned ScopeID = Record[2], IAID = Record[3];
1887 
1888       MDNode *Scope = 0, *IA = 0;
1889       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1890       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1891       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1892       I->setDebugLoc(LastLoc);
1893       I = 0;
1894       continue;
1895     }
1896 
1897     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1898       unsigned OpNum = 0;
1899       Value *LHS, *RHS;
1900       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1901           getValue(Record, OpNum, LHS->getType(), RHS) ||
1902           OpNum+1 > Record.size())
1903         return Error("Invalid BINOP record");
1904 
1905       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1906       if (Opc == -1) return Error("Invalid BINOP record");
1907       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1908       InstructionList.push_back(I);
1909       if (OpNum < Record.size()) {
1910         if (Opc == Instruction::Add ||
1911             Opc == Instruction::Sub ||
1912             Opc == Instruction::Mul ||
1913             Opc == Instruction::Shl) {
1914           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1915             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1916           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1917             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1918         } else if (Opc == Instruction::SDiv ||
1919                    Opc == Instruction::UDiv ||
1920                    Opc == Instruction::LShr ||
1921                    Opc == Instruction::AShr) {
1922           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
1923             cast<BinaryOperator>(I)->setIsExact(true);
1924         }
1925       }
1926       break;
1927     }
1928     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1929       unsigned OpNum = 0;
1930       Value *Op;
1931       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1932           OpNum+2 != Record.size())
1933         return Error("Invalid CAST record");
1934 
1935       const Type *ResTy = getTypeByID(Record[OpNum]);
1936       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1937       if (Opc == -1 || ResTy == 0)
1938         return Error("Invalid CAST record");
1939       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1940       InstructionList.push_back(I);
1941       break;
1942     }
1943     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1944     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1945       unsigned OpNum = 0;
1946       Value *BasePtr;
1947       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1948         return Error("Invalid GEP record");
1949 
1950       SmallVector<Value*, 16> GEPIdx;
1951       while (OpNum != Record.size()) {
1952         Value *Op;
1953         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1954           return Error("Invalid GEP record");
1955         GEPIdx.push_back(Op);
1956       }
1957 
1958       I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1959       InstructionList.push_back(I);
1960       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1961         cast<GetElementPtrInst>(I)->setIsInBounds(true);
1962       break;
1963     }
1964 
1965     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1966                                        // EXTRACTVAL: [opty, opval, n x indices]
1967       unsigned OpNum = 0;
1968       Value *Agg;
1969       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1970         return Error("Invalid EXTRACTVAL record");
1971 
1972       SmallVector<unsigned, 4> EXTRACTVALIdx;
1973       for (unsigned RecSize = Record.size();
1974            OpNum != RecSize; ++OpNum) {
1975         uint64_t Index = Record[OpNum];
1976         if ((unsigned)Index != Index)
1977           return Error("Invalid EXTRACTVAL index");
1978         EXTRACTVALIdx.push_back((unsigned)Index);
1979       }
1980 
1981       I = ExtractValueInst::Create(Agg,
1982                                    EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1983       InstructionList.push_back(I);
1984       break;
1985     }
1986 
1987     case bitc::FUNC_CODE_INST_INSERTVAL: {
1988                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
1989       unsigned OpNum = 0;
1990       Value *Agg;
1991       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1992         return Error("Invalid INSERTVAL record");
1993       Value *Val;
1994       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1995         return Error("Invalid INSERTVAL record");
1996 
1997       SmallVector<unsigned, 4> INSERTVALIdx;
1998       for (unsigned RecSize = Record.size();
1999            OpNum != RecSize; ++OpNum) {
2000         uint64_t Index = Record[OpNum];
2001         if ((unsigned)Index != Index)
2002           return Error("Invalid INSERTVAL index");
2003         INSERTVALIdx.push_back((unsigned)Index);
2004       }
2005 
2006       I = InsertValueInst::Create(Agg, Val,
2007                                   INSERTVALIdx.begin(), INSERTVALIdx.end());
2008       InstructionList.push_back(I);
2009       break;
2010     }
2011 
2012     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2013       // obsolete form of select
2014       // handles select i1 ... in old bitcode
2015       unsigned OpNum = 0;
2016       Value *TrueVal, *FalseVal, *Cond;
2017       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2018           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2019           getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2020         return Error("Invalid SELECT record");
2021 
2022       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2023       InstructionList.push_back(I);
2024       break;
2025     }
2026 
2027     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2028       // new form of select
2029       // handles select i1 or select [N x i1]
2030       unsigned OpNum = 0;
2031       Value *TrueVal, *FalseVal, *Cond;
2032       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2033           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2034           getValueTypePair(Record, OpNum, NextValueNo, Cond))
2035         return Error("Invalid SELECT record");
2036 
2037       // select condition can be either i1 or [N x i1]
2038       if (const VectorType* vector_type =
2039           dyn_cast<const VectorType>(Cond->getType())) {
2040         // expect <n x i1>
2041         if (vector_type->getElementType() != Type::getInt1Ty(Context))
2042           return Error("Invalid SELECT condition type");
2043       } else {
2044         // expect i1
2045         if (Cond->getType() != Type::getInt1Ty(Context))
2046           return Error("Invalid SELECT condition type");
2047       }
2048 
2049       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2050       InstructionList.push_back(I);
2051       break;
2052     }
2053 
2054     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2055       unsigned OpNum = 0;
2056       Value *Vec, *Idx;
2057       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2058           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2059         return Error("Invalid EXTRACTELT record");
2060       I = ExtractElementInst::Create(Vec, Idx);
2061       InstructionList.push_back(I);
2062       break;
2063     }
2064 
2065     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2066       unsigned OpNum = 0;
2067       Value *Vec, *Elt, *Idx;
2068       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2069           getValue(Record, OpNum,
2070                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2071           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2072         return Error("Invalid INSERTELT record");
2073       I = InsertElementInst::Create(Vec, Elt, Idx);
2074       InstructionList.push_back(I);
2075       break;
2076     }
2077 
2078     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2079       unsigned OpNum = 0;
2080       Value *Vec1, *Vec2, *Mask;
2081       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2082           getValue(Record, OpNum, Vec1->getType(), Vec2))
2083         return Error("Invalid SHUFFLEVEC record");
2084 
2085       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2086         return Error("Invalid SHUFFLEVEC record");
2087       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2088       InstructionList.push_back(I);
2089       break;
2090     }
2091 
2092     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2093       // Old form of ICmp/FCmp returning bool
2094       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2095       // both legal on vectors but had different behaviour.
2096     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2097       // FCmp/ICmp returning bool or vector of bool
2098 
2099       unsigned OpNum = 0;
2100       Value *LHS, *RHS;
2101       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2102           getValue(Record, OpNum, LHS->getType(), RHS) ||
2103           OpNum+1 != Record.size())
2104         return Error("Invalid CMP record");
2105 
2106       if (LHS->getType()->isFPOrFPVectorTy())
2107         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2108       else
2109         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2110       InstructionList.push_back(I);
2111       break;
2112     }
2113 
2114     case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
2115       if (Record.size() != 2)
2116         return Error("Invalid GETRESULT record");
2117       unsigned OpNum = 0;
2118       Value *Op;
2119       getValueTypePair(Record, OpNum, NextValueNo, Op);
2120       unsigned Index = Record[1];
2121       I = ExtractValueInst::Create(Op, Index);
2122       InstructionList.push_back(I);
2123       break;
2124     }
2125 
2126     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2127       {
2128         unsigned Size = Record.size();
2129         if (Size == 0) {
2130           I = ReturnInst::Create(Context);
2131           InstructionList.push_back(I);
2132           break;
2133         }
2134 
2135         unsigned OpNum = 0;
2136         SmallVector<Value *,4> Vs;
2137         do {
2138           Value *Op = NULL;
2139           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2140             return Error("Invalid RET record");
2141           Vs.push_back(Op);
2142         } while(OpNum != Record.size());
2143 
2144         const Type *ReturnType = F->getReturnType();
2145         // Handle multiple return values. FIXME: Remove in LLVM 3.0.
2146         if (Vs.size() > 1 ||
2147             (ReturnType->isStructTy() &&
2148              (Vs.empty() || Vs[0]->getType() != ReturnType))) {
2149           Value *RV = UndefValue::get(ReturnType);
2150           for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
2151             I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
2152             InstructionList.push_back(I);
2153             CurBB->getInstList().push_back(I);
2154             ValueList.AssignValue(I, NextValueNo++);
2155             RV = I;
2156           }
2157           I = ReturnInst::Create(Context, RV);
2158           InstructionList.push_back(I);
2159           break;
2160         }
2161 
2162         I = ReturnInst::Create(Context, Vs[0]);
2163         InstructionList.push_back(I);
2164         break;
2165       }
2166     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2167       if (Record.size() != 1 && Record.size() != 3)
2168         return Error("Invalid BR record");
2169       BasicBlock *TrueDest = getBasicBlock(Record[0]);
2170       if (TrueDest == 0)
2171         return Error("Invalid BR record");
2172 
2173       if (Record.size() == 1) {
2174         I = BranchInst::Create(TrueDest);
2175         InstructionList.push_back(I);
2176       }
2177       else {
2178         BasicBlock *FalseDest = getBasicBlock(Record[1]);
2179         Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2180         if (FalseDest == 0 || Cond == 0)
2181           return Error("Invalid BR record");
2182         I = BranchInst::Create(TrueDest, FalseDest, Cond);
2183         InstructionList.push_back(I);
2184       }
2185       break;
2186     }
2187     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2188       if (Record.size() < 3 || (Record.size() & 1) == 0)
2189         return Error("Invalid SWITCH record");
2190       const Type *OpTy = getTypeByID(Record[0]);
2191       Value *Cond = getFnValueByID(Record[1], OpTy);
2192       BasicBlock *Default = getBasicBlock(Record[2]);
2193       if (OpTy == 0 || Cond == 0 || Default == 0)
2194         return Error("Invalid SWITCH record");
2195       unsigned NumCases = (Record.size()-3)/2;
2196       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2197       InstructionList.push_back(SI);
2198       for (unsigned i = 0, e = NumCases; i != e; ++i) {
2199         ConstantInt *CaseVal =
2200           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2201         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2202         if (CaseVal == 0 || DestBB == 0) {
2203           delete SI;
2204           return Error("Invalid SWITCH record!");
2205         }
2206         SI->addCase(CaseVal, DestBB);
2207       }
2208       I = SI;
2209       break;
2210     }
2211     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2212       if (Record.size() < 2)
2213         return Error("Invalid INDIRECTBR record");
2214       const Type *OpTy = getTypeByID(Record[0]);
2215       Value *Address = getFnValueByID(Record[1], OpTy);
2216       if (OpTy == 0 || Address == 0)
2217         return Error("Invalid INDIRECTBR record");
2218       unsigned NumDests = Record.size()-2;
2219       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2220       InstructionList.push_back(IBI);
2221       for (unsigned i = 0, e = NumDests; i != e; ++i) {
2222         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2223           IBI->addDestination(DestBB);
2224         } else {
2225           delete IBI;
2226           return Error("Invalid INDIRECTBR record!");
2227         }
2228       }
2229       I = IBI;
2230       break;
2231     }
2232 
2233     case bitc::FUNC_CODE_INST_INVOKE: {
2234       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2235       if (Record.size() < 4) return Error("Invalid INVOKE record");
2236       AttrListPtr PAL = getAttributes(Record[0]);
2237       unsigned CCInfo = Record[1];
2238       BasicBlock *NormalBB = getBasicBlock(Record[2]);
2239       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2240 
2241       unsigned OpNum = 4;
2242       Value *Callee;
2243       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2244         return Error("Invalid INVOKE record");
2245 
2246       const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2247       const FunctionType *FTy = !CalleeTy ? 0 :
2248         dyn_cast<FunctionType>(CalleeTy->getElementType());
2249 
2250       // Check that the right number of fixed parameters are here.
2251       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2252           Record.size() < OpNum+FTy->getNumParams())
2253         return Error("Invalid INVOKE record");
2254 
2255       SmallVector<Value*, 16> Ops;
2256       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2257         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2258         if (Ops.back() == 0) return Error("Invalid INVOKE record");
2259       }
2260 
2261       if (!FTy->isVarArg()) {
2262         if (Record.size() != OpNum)
2263           return Error("Invalid INVOKE record");
2264       } else {
2265         // Read type/value pairs for varargs params.
2266         while (OpNum != Record.size()) {
2267           Value *Op;
2268           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2269             return Error("Invalid INVOKE record");
2270           Ops.push_back(Op);
2271         }
2272       }
2273 
2274       I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2275                              Ops.begin(), Ops.end());
2276       InstructionList.push_back(I);
2277       cast<InvokeInst>(I)->setCallingConv(
2278         static_cast<CallingConv::ID>(CCInfo));
2279       cast<InvokeInst>(I)->setAttributes(PAL);
2280       break;
2281     }
2282     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2283       I = new UnwindInst(Context);
2284       InstructionList.push_back(I);
2285       break;
2286     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2287       I = new UnreachableInst(Context);
2288       InstructionList.push_back(I);
2289       break;
2290     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2291       if (Record.size() < 1 || ((Record.size()-1)&1))
2292         return Error("Invalid PHI record");
2293       const Type *Ty = getTypeByID(Record[0]);
2294       if (!Ty) return Error("Invalid PHI record");
2295 
2296       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2297       InstructionList.push_back(PN);
2298 
2299       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2300         Value *V = getFnValueByID(Record[1+i], Ty);
2301         BasicBlock *BB = getBasicBlock(Record[2+i]);
2302         if (!V || !BB) return Error("Invalid PHI record");
2303         PN->addIncoming(V, BB);
2304       }
2305       I = PN;
2306       break;
2307     }
2308 
2309     case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
2310       // Autoupgrade malloc instruction to malloc call.
2311       // FIXME: Remove in LLVM 3.0.
2312       if (Record.size() < 3)
2313         return Error("Invalid MALLOC record");
2314       const PointerType *Ty =
2315         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2316       Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2317       if (!Ty || !Size) return Error("Invalid MALLOC record");
2318       if (!CurBB) return Error("Invalid malloc instruction with no BB");
2319       const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
2320       Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
2321       AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
2322       I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
2323                                  AllocSize, Size, NULL);
2324       InstructionList.push_back(I);
2325       break;
2326     }
2327     case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
2328       unsigned OpNum = 0;
2329       Value *Op;
2330       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2331           OpNum != Record.size())
2332         return Error("Invalid FREE record");
2333       if (!CurBB) return Error("Invalid free instruction with no BB");
2334       I = CallInst::CreateFree(Op, CurBB);
2335       InstructionList.push_back(I);
2336       break;
2337     }
2338     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2339       // For backward compatibility, tolerate a lack of an opty, and use i32.
2340       // Remove this in LLVM 3.0.
2341       if (Record.size() < 3 || Record.size() > 4)
2342         return Error("Invalid ALLOCA record");
2343       unsigned OpNum = 0;
2344       const PointerType *Ty =
2345         dyn_cast_or_null<PointerType>(getTypeByID(Record[OpNum++]));
2346       const Type *OpTy = Record.size() == 4 ? getTypeByID(Record[OpNum++]) :
2347                                               Type::getInt32Ty(Context);
2348       Value *Size = getFnValueByID(Record[OpNum++], OpTy);
2349       unsigned Align = Record[OpNum++];
2350       if (!Ty || !Size) return Error("Invalid ALLOCA record");
2351       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2352       InstructionList.push_back(I);
2353       break;
2354     }
2355     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2356       unsigned OpNum = 0;
2357       Value *Op;
2358       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2359           OpNum+2 != Record.size())
2360         return Error("Invalid LOAD record");
2361 
2362       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2363       InstructionList.push_back(I);
2364       break;
2365     }
2366     case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
2367       unsigned OpNum = 0;
2368       Value *Val, *Ptr;
2369       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2370           getValue(Record, OpNum,
2371                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2372           OpNum+2 != Record.size())
2373         return Error("Invalid STORE record");
2374 
2375       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2376       InstructionList.push_back(I);
2377       break;
2378     }
2379     case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
2380       // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
2381       unsigned OpNum = 0;
2382       Value *Val, *Ptr;
2383       if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
2384           getValue(Record, OpNum,
2385                    PointerType::getUnqual(Val->getType()), Ptr)||
2386           OpNum+2 != Record.size())
2387         return Error("Invalid STORE record");
2388 
2389       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2390       InstructionList.push_back(I);
2391       break;
2392     }
2393     // FIXME: Remove this in LLVM 3.0.
2394     case bitc::FUNC_CODE_INST_CALL:
2395       LLVM2_7MetadataDetected = true;
2396     case bitc::FUNC_CODE_INST_CALL2: {
2397       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2398       if (Record.size() < 3)
2399         return Error("Invalid CALL record");
2400 
2401       AttrListPtr PAL = getAttributes(Record[0]);
2402       unsigned CCInfo = Record[1];
2403 
2404       unsigned OpNum = 2;
2405       Value *Callee;
2406       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2407         return Error("Invalid CALL record");
2408 
2409       const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2410       const FunctionType *FTy = 0;
2411       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2412       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2413         return Error("Invalid CALL record");
2414 
2415       SmallVector<Value*, 16> Args;
2416       // Read the fixed params.
2417       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2418         if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2419           Args.push_back(getBasicBlock(Record[OpNum]));
2420         else
2421           Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2422         if (Args.back() == 0) return Error("Invalid CALL record");
2423       }
2424 
2425       // Read type/value pairs for varargs params.
2426       if (!FTy->isVarArg()) {
2427         if (OpNum != Record.size())
2428           return Error("Invalid CALL record");
2429       } else {
2430         while (OpNum != Record.size()) {
2431           Value *Op;
2432           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2433             return Error("Invalid CALL record");
2434           Args.push_back(Op);
2435         }
2436       }
2437 
2438       I = CallInst::Create(Callee, Args.begin(), Args.end());
2439       InstructionList.push_back(I);
2440       cast<CallInst>(I)->setCallingConv(
2441         static_cast<CallingConv::ID>(CCInfo>>1));
2442       cast<CallInst>(I)->setTailCall(CCInfo & 1);
2443       cast<CallInst>(I)->setAttributes(PAL);
2444       break;
2445     }
2446     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2447       if (Record.size() < 3)
2448         return Error("Invalid VAARG record");
2449       const Type *OpTy = getTypeByID(Record[0]);
2450       Value *Op = getFnValueByID(Record[1], OpTy);
2451       const Type *ResTy = getTypeByID(Record[2]);
2452       if (!OpTy || !Op || !ResTy)
2453         return Error("Invalid VAARG record");
2454       I = new VAArgInst(Op, ResTy);
2455       InstructionList.push_back(I);
2456       break;
2457     }
2458     }
2459 
2460     // Add instruction to end of current BB.  If there is no current BB, reject
2461     // this file.
2462     if (CurBB == 0) {
2463       delete I;
2464       return Error("Invalid instruction with no BB");
2465     }
2466     CurBB->getInstList().push_back(I);
2467 
2468     // If this was a terminator instruction, move to the next block.
2469     if (isa<TerminatorInst>(I)) {
2470       ++CurBBNo;
2471       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2472     }
2473 
2474     // Non-void values get registered in the value table for future use.
2475     if (I && !I->getType()->isVoidTy())
2476       ValueList.AssignValue(I, NextValueNo++);
2477   }
2478 
2479   // Check the function list for unresolved values.
2480   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2481     if (A->getParent() == 0) {
2482       // We found at least one unresolved value.  Nuke them all to avoid leaks.
2483       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2484         if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2485           A->replaceAllUsesWith(UndefValue::get(A->getType()));
2486           delete A;
2487         }
2488       }
2489       return Error("Never resolved value found in function!");
2490     }
2491   }
2492 
2493   // FIXME: Check for unresolved forward-declared metadata references
2494   // and clean up leaks.
2495 
2496   // See if anything took the address of blocks in this function.  If so,
2497   // resolve them now.
2498   DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2499     BlockAddrFwdRefs.find(F);
2500   if (BAFRI != BlockAddrFwdRefs.end()) {
2501     std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2502     for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2503       unsigned BlockIdx = RefList[i].first;
2504       if (BlockIdx >= FunctionBBs.size())
2505         return Error("Invalid blockaddress block #");
2506 
2507       GlobalVariable *FwdRef = RefList[i].second;
2508       FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2509       FwdRef->eraseFromParent();
2510     }
2511 
2512     BlockAddrFwdRefs.erase(BAFRI);
2513   }
2514 
2515   // FIXME: Remove this in LLVM 3.0.
2516   unsigned NewMDValueListSize = MDValueList.size();
2517 
2518   // Trim the value list down to the size it was before we parsed this function.
2519   ValueList.shrinkTo(ModuleValueListSize);
2520   MDValueList.shrinkTo(ModuleMDValueListSize);
2521 
2522   // Backwards compatibility hack: Function-local metadata numbers
2523   // were previously not reset between functions. This is now fixed,
2524   // however we still need to understand the old numbering in order
2525   // to be able to read old bitcode files.
2526   // FIXME: Remove this in LLVM 3.0.
2527   if (LLVM2_7MetadataDetected)
2528     MDValueList.resize(NewMDValueListSize);
2529 
2530   std::vector<BasicBlock*>().swap(FunctionBBs);
2531 
2532   return false;
2533 }
2534 
2535 //===----------------------------------------------------------------------===//
2536 // GVMaterializer implementation
2537 //===----------------------------------------------------------------------===//
2538 
2539 
2540 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2541   if (const Function *F = dyn_cast<Function>(GV)) {
2542     return F->isDeclaration() &&
2543       DeferredFunctionInfo.count(const_cast<Function*>(F));
2544   }
2545   return false;
2546 }
2547 
2548 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2549   Function *F = dyn_cast<Function>(GV);
2550   // If it's not a function or is already material, ignore the request.
2551   if (!F || !F->isMaterializable()) return false;
2552 
2553   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2554   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2555 
2556   // Move the bit stream to the saved position of the deferred function body.
2557   Stream.JumpToBit(DFII->second);
2558 
2559   if (ParseFunctionBody(F)) {
2560     if (ErrInfo) *ErrInfo = ErrorString;
2561     return true;
2562   }
2563 
2564   // Upgrade any old intrinsic calls in the function.
2565   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2566        E = UpgradedIntrinsics.end(); I != E; ++I) {
2567     if (I->first != I->second) {
2568       for (Value::use_iterator UI = I->first->use_begin(),
2569            UE = I->first->use_end(); UI != UE; ) {
2570         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2571           UpgradeIntrinsicCall(CI, I->second);
2572       }
2573     }
2574   }
2575 
2576   return false;
2577 }
2578 
2579 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2580   const Function *F = dyn_cast<Function>(GV);
2581   if (!F || F->isDeclaration())
2582     return false;
2583   return DeferredFunctionInfo.count(const_cast<Function*>(F));
2584 }
2585 
2586 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2587   Function *F = dyn_cast<Function>(GV);
2588   // If this function isn't dematerializable, this is a noop.
2589   if (!F || !isDematerializable(F))
2590     return;
2591 
2592   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2593 
2594   // Just forget the function body, we can remat it later.
2595   F->deleteBody();
2596 }
2597 
2598 
2599 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2600   assert(M == TheModule &&
2601          "Can only Materialize the Module this BitcodeReader is attached to.");
2602   // Iterate over the module, deserializing any functions that are still on
2603   // disk.
2604   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2605        F != E; ++F)
2606     if (F->isMaterializable() &&
2607         Materialize(F, ErrInfo))
2608       return true;
2609 
2610   // Upgrade any intrinsic calls that slipped through (should not happen!) and
2611   // delete the old functions to clean up. We can't do this unless the entire
2612   // module is materialized because there could always be another function body
2613   // with calls to the old function.
2614   for (std::vector<std::pair<Function*, Function*> >::iterator I =
2615        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2616     if (I->first != I->second) {
2617       for (Value::use_iterator UI = I->first->use_begin(),
2618            UE = I->first->use_end(); UI != UE; ) {
2619         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2620           UpgradeIntrinsicCall(CI, I->second);
2621       }
2622       if (!I->first->use_empty())
2623         I->first->replaceAllUsesWith(I->second);
2624       I->first->eraseFromParent();
2625     }
2626   }
2627   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2628 
2629   // Check debug info intrinsics.
2630   CheckDebugInfoIntrinsics(TheModule);
2631 
2632   return false;
2633 }
2634 
2635 
2636 //===----------------------------------------------------------------------===//
2637 // External interface
2638 //===----------------------------------------------------------------------===//
2639 
2640 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2641 ///
2642 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2643                                    LLVMContext& Context,
2644                                    std::string *ErrMsg) {
2645   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2646   BitcodeReader *R = new BitcodeReader(Buffer, Context);
2647   M->setMaterializer(R);
2648   if (R->ParseBitcodeInto(M)) {
2649     if (ErrMsg)
2650       *ErrMsg = R->getErrorString();
2651 
2652     delete M;  // Also deletes R.
2653     return 0;
2654   }
2655   // Have the BitcodeReader dtor delete 'Buffer'.
2656   R->setBufferOwned(true);
2657   return M;
2658 }
2659 
2660 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2661 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2662 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2663                                std::string *ErrMsg){
2664   Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2665   if (!M) return 0;
2666 
2667   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2668   // there was an error.
2669   static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2670 
2671   // Read in the entire module, and destroy the BitcodeReader.
2672   if (M->MaterializeAllPermanently(ErrMsg)) {
2673     delete M;
2674     return 0;
2675   }
2676 
2677   return M;
2678 }
2679 
2680 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2681                                          LLVMContext& Context,
2682                                          std::string *ErrMsg) {
2683   BitcodeReader *R = new BitcodeReader(Buffer, Context);
2684   // Don't let the BitcodeReader dtor delete 'Buffer'.
2685   R->setBufferOwned(false);
2686 
2687   std::string Triple("");
2688   if (R->ParseTriple(Triple))
2689     if (ErrMsg)
2690       *ErrMsg = R->getErrorString();
2691 
2692   delete R;
2693   return Triple;
2694 }
2695