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