Add accessor marcos to ConstantPlaceHolder, similar to those in the base class.
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
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 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Bitcode/LLVMBitCodes.h"
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/ManagedStatic.h"
29
30 using namespace llvm;
31
32 enum {
33   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
34 };
35
36 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
37   if (WillMaterializeAllForwardRefs)
38     return std::error_code();
39
40   // Prevent recursion.
41   WillMaterializeAllForwardRefs = true;
42
43   while (!BasicBlockFwdRefQueue.empty()) {
44     Function *F = BasicBlockFwdRefQueue.front();
45     BasicBlockFwdRefQueue.pop_front();
46     assert(F && "Expected valid function");
47     if (!BasicBlockFwdRefs.count(F))
48       // Already materialized.
49       continue;
50
51     // Check for a function that isn't materializable to prevent an infinite
52     // loop.  When parsing a blockaddress stored in a global variable, there
53     // isn't a trivial way to check if a function will have a body without a
54     // linear search through FunctionsWithBodies, so just check it here.
55     if (!F->isMaterializable())
56       return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
57
58     // Try to materialize F.
59     if (std::error_code EC = materialize(F))
60       return EC;
61   }
62   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
63
64   // Reset state.
65   WillMaterializeAllForwardRefs = false;
66   return std::error_code();
67 }
68
69 void BitcodeReader::FreeState() {
70   Buffer = nullptr;
71   std::vector<Type*>().swap(TypeList);
72   ValueList.clear();
73   MDValueList.clear();
74   std::vector<Comdat *>().swap(ComdatList);
75
76   std::vector<AttributeSet>().swap(MAttributes);
77   std::vector<BasicBlock*>().swap(FunctionBBs);
78   std::vector<Function*>().swap(FunctionsWithBodies);
79   DeferredFunctionInfo.clear();
80   MDKindMap.clear();
81
82   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
83   BasicBlockFwdRefQueue.clear();
84 }
85
86 //===----------------------------------------------------------------------===//
87 //  Helper functions to implement forward reference resolution, etc.
88 //===----------------------------------------------------------------------===//
89
90 /// ConvertToString - Convert a string from a record into an std::string, return
91 /// true on failure.
92 template<typename StrTy>
93 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
94                             StrTy &Result) {
95   if (Idx > Record.size())
96     return true;
97
98   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
99     Result += (char)Record[i];
100   return false;
101 }
102
103 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
104   switch (Val) {
105   default: // Map unknown/new linkages to external
106   case 0:  return GlobalValue::ExternalLinkage;
107   case 1:  return GlobalValue::WeakAnyLinkage;
108   case 2:  return GlobalValue::AppendingLinkage;
109   case 3:  return GlobalValue::InternalLinkage;
110   case 4:  return GlobalValue::LinkOnceAnyLinkage;
111   case 5:  return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
112   case 6:  return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
113   case 7:  return GlobalValue::ExternalWeakLinkage;
114   case 8:  return GlobalValue::CommonLinkage;
115   case 9:  return GlobalValue::PrivateLinkage;
116   case 10: return GlobalValue::WeakODRLinkage;
117   case 11: return GlobalValue::LinkOnceODRLinkage;
118   case 12: return GlobalValue::AvailableExternallyLinkage;
119   case 13:
120     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
121   case 14:
122     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
123   }
124 }
125
126 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
127   switch (Val) {
128   default: // Map unknown visibilities to default.
129   case 0: return GlobalValue::DefaultVisibility;
130   case 1: return GlobalValue::HiddenVisibility;
131   case 2: return GlobalValue::ProtectedVisibility;
132   }
133 }
134
135 static GlobalValue::DLLStorageClassTypes
136 GetDecodedDLLStorageClass(unsigned Val) {
137   switch (Val) {
138   default: // Map unknown values to default.
139   case 0: return GlobalValue::DefaultStorageClass;
140   case 1: return GlobalValue::DLLImportStorageClass;
141   case 2: return GlobalValue::DLLExportStorageClass;
142   }
143 }
144
145 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
146   switch (Val) {
147     case 0: return GlobalVariable::NotThreadLocal;
148     default: // Map unknown non-zero value to general dynamic.
149     case 1: return GlobalVariable::GeneralDynamicTLSModel;
150     case 2: return GlobalVariable::LocalDynamicTLSModel;
151     case 3: return GlobalVariable::InitialExecTLSModel;
152     case 4: return GlobalVariable::LocalExecTLSModel;
153   }
154 }
155
156 static int GetDecodedCastOpcode(unsigned Val) {
157   switch (Val) {
158   default: return -1;
159   case bitc::CAST_TRUNC   : return Instruction::Trunc;
160   case bitc::CAST_ZEXT    : return Instruction::ZExt;
161   case bitc::CAST_SEXT    : return Instruction::SExt;
162   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
163   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
164   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
165   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
166   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
167   case bitc::CAST_FPEXT   : return Instruction::FPExt;
168   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
169   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
170   case bitc::CAST_BITCAST : return Instruction::BitCast;
171   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
172   }
173 }
174 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
175   switch (Val) {
176   default: return -1;
177   case bitc::BINOP_ADD:
178     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
179   case bitc::BINOP_SUB:
180     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
181   case bitc::BINOP_MUL:
182     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
183   case bitc::BINOP_UDIV: return Instruction::UDiv;
184   case bitc::BINOP_SDIV:
185     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
186   case bitc::BINOP_UREM: return Instruction::URem;
187   case bitc::BINOP_SREM:
188     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
189   case bitc::BINOP_SHL:  return Instruction::Shl;
190   case bitc::BINOP_LSHR: return Instruction::LShr;
191   case bitc::BINOP_ASHR: return Instruction::AShr;
192   case bitc::BINOP_AND:  return Instruction::And;
193   case bitc::BINOP_OR:   return Instruction::Or;
194   case bitc::BINOP_XOR:  return Instruction::Xor;
195   }
196 }
197
198 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
199   switch (Val) {
200   default: return AtomicRMWInst::BAD_BINOP;
201   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
202   case bitc::RMW_ADD: return AtomicRMWInst::Add;
203   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
204   case bitc::RMW_AND: return AtomicRMWInst::And;
205   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
206   case bitc::RMW_OR: return AtomicRMWInst::Or;
207   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
208   case bitc::RMW_MAX: return AtomicRMWInst::Max;
209   case bitc::RMW_MIN: return AtomicRMWInst::Min;
210   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
211   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
212   }
213 }
214
215 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
216   switch (Val) {
217   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
218   case bitc::ORDERING_UNORDERED: return Unordered;
219   case bitc::ORDERING_MONOTONIC: return Monotonic;
220   case bitc::ORDERING_ACQUIRE: return Acquire;
221   case bitc::ORDERING_RELEASE: return Release;
222   case bitc::ORDERING_ACQREL: return AcquireRelease;
223   default: // Map unknown orderings to sequentially-consistent.
224   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
225   }
226 }
227
228 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
229   switch (Val) {
230   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
231   default: // Map unknown scopes to cross-thread.
232   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
233   }
234 }
235
236 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
237   switch (Val) {
238   default: // Map unknown selection kinds to any.
239   case bitc::COMDAT_SELECTION_KIND_ANY:
240     return Comdat::Any;
241   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
242     return Comdat::ExactMatch;
243   case bitc::COMDAT_SELECTION_KIND_LARGEST:
244     return Comdat::Largest;
245   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
246     return Comdat::NoDuplicates;
247   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
248     return Comdat::SameSize;
249   }
250 }
251
252 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
253   switch (Val) {
254   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
255   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
256   }
257 }
258
259 namespace llvm {
260 namespace {
261   /// @brief A class for maintaining the slot number definition
262   /// as a placeholder for the actual definition for forward constants defs.
263   class ConstantPlaceHolder : public ConstantExpr {
264     void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
265   public:
266     // allocate space for exactly one operand
267     void *operator new(size_t s) {
268       return User::operator new(s, 1);
269     }
270     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
271       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
272       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
273     }
274
275     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
276     static bool classof(const Value *V) {
277       return isa<ConstantExpr>(V) &&
278              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
279     }
280
281
282     /// Provide fast operand accessors
283     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
284   };
285 }
286
287 // FIXME: can we inherit this from ConstantExpr?
288 template <>
289 struct OperandTraits<ConstantPlaceHolder> :
290   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
291 };
292 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
293 }
294
295
296 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
297   if (Idx == size()) {
298     push_back(V);
299     return;
300   }
301
302   if (Idx >= size())
303     resize(Idx+1);
304
305   WeakVH &OldV = ValuePtrs[Idx];
306   if (!OldV) {
307     OldV = V;
308     return;
309   }
310
311   // Handle constants and non-constants (e.g. instrs) differently for
312   // efficiency.
313   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
314     ResolveConstants.push_back(std::make_pair(PHC, Idx));
315     OldV = V;
316   } else {
317     // If there was a forward reference to this value, replace it.
318     Value *PrevVal = OldV;
319     OldV->replaceAllUsesWith(V);
320     delete PrevVal;
321   }
322 }
323
324
325 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
326                                                     Type *Ty) {
327   if (Idx >= size())
328     resize(Idx + 1);
329
330   if (Value *V = ValuePtrs[Idx]) {
331     assert(Ty == V->getType() && "Type mismatch in constant table!");
332     return cast<Constant>(V);
333   }
334
335   // Create and return a placeholder, which will later be RAUW'd.
336   Constant *C = new ConstantPlaceHolder(Ty, Context);
337   ValuePtrs[Idx] = C;
338   return C;
339 }
340
341 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
342   if (Idx >= size())
343     resize(Idx + 1);
344
345   if (Value *V = ValuePtrs[Idx]) {
346     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
347     return V;
348   }
349
350   // No type specified, must be invalid reference.
351   if (!Ty) return nullptr;
352
353   // Create and return a placeholder, which will later be RAUW'd.
354   Value *V = new Argument(Ty);
355   ValuePtrs[Idx] = V;
356   return V;
357 }
358
359 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
360 /// resolves any forward references.  The idea behind this is that we sometimes
361 /// get constants (such as large arrays) which reference *many* forward ref
362 /// constants.  Replacing each of these causes a lot of thrashing when
363 /// building/reuniquing the constant.  Instead of doing this, we look at all the
364 /// uses and rewrite all the place holders at once for any constant that uses
365 /// a placeholder.
366 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
367   // Sort the values by-pointer so that they are efficient to look up with a
368   // binary search.
369   std::sort(ResolveConstants.begin(), ResolveConstants.end());
370
371   SmallVector<Constant*, 64> NewOps;
372
373   while (!ResolveConstants.empty()) {
374     Value *RealVal = operator[](ResolveConstants.back().second);
375     Constant *Placeholder = ResolveConstants.back().first;
376     ResolveConstants.pop_back();
377
378     // Loop over all users of the placeholder, updating them to reference the
379     // new value.  If they reference more than one placeholder, update them all
380     // at once.
381     while (!Placeholder->use_empty()) {
382       auto UI = Placeholder->user_begin();
383       User *U = *UI;
384
385       // If the using object isn't uniqued, just update the operands.  This
386       // handles instructions and initializers for global variables.
387       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
388         UI.getUse().set(RealVal);
389         continue;
390       }
391
392       // Otherwise, we have a constant that uses the placeholder.  Replace that
393       // constant with a new constant that has *all* placeholder uses updated.
394       Constant *UserC = cast<Constant>(U);
395       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
396            I != E; ++I) {
397         Value *NewOp;
398         if (!isa<ConstantPlaceHolder>(*I)) {
399           // Not a placeholder reference.
400           NewOp = *I;
401         } else if (*I == Placeholder) {
402           // Common case is that it just references this one placeholder.
403           NewOp = RealVal;
404         } else {
405           // Otherwise, look up the placeholder in ResolveConstants.
406           ResolveConstantsTy::iterator It =
407             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
408                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
409                                                             0));
410           assert(It != ResolveConstants.end() && It->first == *I);
411           NewOp = operator[](It->second);
412         }
413
414         NewOps.push_back(cast<Constant>(NewOp));
415       }
416
417       // Make the new constant.
418       Constant *NewC;
419       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
420         NewC = ConstantArray::get(UserCA->getType(), NewOps);
421       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
422         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
423       } else if (isa<ConstantVector>(UserC)) {
424         NewC = ConstantVector::get(NewOps);
425       } else {
426         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
427         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
428       }
429
430       UserC->replaceAllUsesWith(NewC);
431       UserC->destroyConstant();
432       NewOps.clear();
433     }
434
435     // Update all ValueHandles, they should be the only users at this point.
436     Placeholder->replaceAllUsesWith(RealVal);
437     delete Placeholder;
438   }
439 }
440
441 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
442   if (Idx == size()) {
443     push_back(V);
444     return;
445   }
446
447   if (Idx >= size())
448     resize(Idx+1);
449
450   WeakVH &OldV = MDValuePtrs[Idx];
451   if (!OldV) {
452     OldV = V;
453     return;
454   }
455
456   // If there was a forward reference to this value, replace it.
457   MDNode *PrevVal = cast<MDNode>(OldV);
458   OldV->replaceAllUsesWith(V);
459   MDNode::deleteTemporary(PrevVal);
460   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
461   // value for Idx.
462   MDValuePtrs[Idx] = V;
463 }
464
465 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
466   if (Idx >= size())
467     resize(Idx + 1);
468
469   if (Value *V = MDValuePtrs[Idx]) {
470     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
471     return V;
472   }
473
474   // Create and return a placeholder, which will later be RAUW'd.
475   Value *V = MDNode::getTemporary(Context, None);
476   MDValuePtrs[Idx] = V;
477   return V;
478 }
479
480 Type *BitcodeReader::getTypeByID(unsigned ID) {
481   // The type table size is always specified correctly.
482   if (ID >= TypeList.size())
483     return nullptr;
484
485   if (Type *Ty = TypeList[ID])
486     return Ty;
487
488   // If we have a forward reference, the only possible case is when it is to a
489   // named struct.  Just create a placeholder for now.
490   return TypeList[ID] = StructType::create(Context);
491 }
492
493
494 //===----------------------------------------------------------------------===//
495 //  Functions for parsing blocks from the bitcode file
496 //===----------------------------------------------------------------------===//
497
498
499 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
500 /// been decoded from the given integer. This function must stay in sync with
501 /// 'encodeLLVMAttributesForBitcode'.
502 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
503                                            uint64_t EncodedAttrs) {
504   // FIXME: Remove in 4.0.
505
506   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
507   // the bits above 31 down by 11 bits.
508   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
509   assert((!Alignment || isPowerOf2_32(Alignment)) &&
510          "Alignment must be a power of two.");
511
512   if (Alignment)
513     B.addAlignmentAttr(Alignment);
514   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
515                 (EncodedAttrs & 0xffff));
516 }
517
518 std::error_code BitcodeReader::ParseAttributeBlock() {
519   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
520     return Error(BitcodeError::InvalidRecord);
521
522   if (!MAttributes.empty())
523     return Error(BitcodeError::InvalidMultipleBlocks);
524
525   SmallVector<uint64_t, 64> Record;
526
527   SmallVector<AttributeSet, 8> Attrs;
528
529   // Read all the records.
530   while (1) {
531     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
532
533     switch (Entry.Kind) {
534     case BitstreamEntry::SubBlock: // Handled for us already.
535     case BitstreamEntry::Error:
536       return Error(BitcodeError::MalformedBlock);
537     case BitstreamEntry::EndBlock:
538       return std::error_code();
539     case BitstreamEntry::Record:
540       // The interesting case.
541       break;
542     }
543
544     // Read a record.
545     Record.clear();
546     switch (Stream.readRecord(Entry.ID, Record)) {
547     default:  // Default behavior: ignore.
548       break;
549     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
550       // FIXME: Remove in 4.0.
551       if (Record.size() & 1)
552         return Error(BitcodeError::InvalidRecord);
553
554       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
555         AttrBuilder B;
556         decodeLLVMAttributesForBitcode(B, Record[i+1]);
557         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
558       }
559
560       MAttributes.push_back(AttributeSet::get(Context, Attrs));
561       Attrs.clear();
562       break;
563     }
564     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
565       for (unsigned i = 0, e = Record.size(); i != e; ++i)
566         Attrs.push_back(MAttributeGroups[Record[i]]);
567
568       MAttributes.push_back(AttributeSet::get(Context, Attrs));
569       Attrs.clear();
570       break;
571     }
572     }
573   }
574 }
575
576 // Returns Attribute::None on unrecognized codes.
577 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
578   switch (Code) {
579   default:
580     return Attribute::None;
581   case bitc::ATTR_KIND_ALIGNMENT:
582     return Attribute::Alignment;
583   case bitc::ATTR_KIND_ALWAYS_INLINE:
584     return Attribute::AlwaysInline;
585   case bitc::ATTR_KIND_BUILTIN:
586     return Attribute::Builtin;
587   case bitc::ATTR_KIND_BY_VAL:
588     return Attribute::ByVal;
589   case bitc::ATTR_KIND_IN_ALLOCA:
590     return Attribute::InAlloca;
591   case bitc::ATTR_KIND_COLD:
592     return Attribute::Cold;
593   case bitc::ATTR_KIND_INLINE_HINT:
594     return Attribute::InlineHint;
595   case bitc::ATTR_KIND_IN_REG:
596     return Attribute::InReg;
597   case bitc::ATTR_KIND_JUMP_TABLE:
598     return Attribute::JumpTable;
599   case bitc::ATTR_KIND_MIN_SIZE:
600     return Attribute::MinSize;
601   case bitc::ATTR_KIND_NAKED:
602     return Attribute::Naked;
603   case bitc::ATTR_KIND_NEST:
604     return Attribute::Nest;
605   case bitc::ATTR_KIND_NO_ALIAS:
606     return Attribute::NoAlias;
607   case bitc::ATTR_KIND_NO_BUILTIN:
608     return Attribute::NoBuiltin;
609   case bitc::ATTR_KIND_NO_CAPTURE:
610     return Attribute::NoCapture;
611   case bitc::ATTR_KIND_NO_DUPLICATE:
612     return Attribute::NoDuplicate;
613   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
614     return Attribute::NoImplicitFloat;
615   case bitc::ATTR_KIND_NO_INLINE:
616     return Attribute::NoInline;
617   case bitc::ATTR_KIND_NON_LAZY_BIND:
618     return Attribute::NonLazyBind;
619   case bitc::ATTR_KIND_NON_NULL:
620     return Attribute::NonNull;
621   case bitc::ATTR_KIND_DEREFERENCEABLE:
622     return Attribute::Dereferenceable;
623   case bitc::ATTR_KIND_NO_RED_ZONE:
624     return Attribute::NoRedZone;
625   case bitc::ATTR_KIND_NO_RETURN:
626     return Attribute::NoReturn;
627   case bitc::ATTR_KIND_NO_UNWIND:
628     return Attribute::NoUnwind;
629   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
630     return Attribute::OptimizeForSize;
631   case bitc::ATTR_KIND_OPTIMIZE_NONE:
632     return Attribute::OptimizeNone;
633   case bitc::ATTR_KIND_READ_NONE:
634     return Attribute::ReadNone;
635   case bitc::ATTR_KIND_READ_ONLY:
636     return Attribute::ReadOnly;
637   case bitc::ATTR_KIND_RETURNED:
638     return Attribute::Returned;
639   case bitc::ATTR_KIND_RETURNS_TWICE:
640     return Attribute::ReturnsTwice;
641   case bitc::ATTR_KIND_S_EXT:
642     return Attribute::SExt;
643   case bitc::ATTR_KIND_STACK_ALIGNMENT:
644     return Attribute::StackAlignment;
645   case bitc::ATTR_KIND_STACK_PROTECT:
646     return Attribute::StackProtect;
647   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
648     return Attribute::StackProtectReq;
649   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
650     return Attribute::StackProtectStrong;
651   case bitc::ATTR_KIND_STRUCT_RET:
652     return Attribute::StructRet;
653   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
654     return Attribute::SanitizeAddress;
655   case bitc::ATTR_KIND_SANITIZE_THREAD:
656     return Attribute::SanitizeThread;
657   case bitc::ATTR_KIND_SANITIZE_MEMORY:
658     return Attribute::SanitizeMemory;
659   case bitc::ATTR_KIND_UW_TABLE:
660     return Attribute::UWTable;
661   case bitc::ATTR_KIND_Z_EXT:
662     return Attribute::ZExt;
663   }
664 }
665
666 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
667                                              Attribute::AttrKind *Kind) {
668   *Kind = GetAttrFromCode(Code);
669   if (*Kind == Attribute::None)
670     return Error(BitcodeError::InvalidValue);
671   return std::error_code();
672 }
673
674 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
675   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
676     return Error(BitcodeError::InvalidRecord);
677
678   if (!MAttributeGroups.empty())
679     return Error(BitcodeError::InvalidMultipleBlocks);
680
681   SmallVector<uint64_t, 64> Record;
682
683   // Read all the records.
684   while (1) {
685     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
686
687     switch (Entry.Kind) {
688     case BitstreamEntry::SubBlock: // Handled for us already.
689     case BitstreamEntry::Error:
690       return Error(BitcodeError::MalformedBlock);
691     case BitstreamEntry::EndBlock:
692       return std::error_code();
693     case BitstreamEntry::Record:
694       // The interesting case.
695       break;
696     }
697
698     // Read a record.
699     Record.clear();
700     switch (Stream.readRecord(Entry.ID, Record)) {
701     default:  // Default behavior: ignore.
702       break;
703     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
704       if (Record.size() < 3)
705         return Error(BitcodeError::InvalidRecord);
706
707       uint64_t GrpID = Record[0];
708       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
709
710       AttrBuilder B;
711       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
712         if (Record[i] == 0) {        // Enum attribute
713           Attribute::AttrKind Kind;
714           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
715             return EC;
716
717           B.addAttribute(Kind);
718         } else if (Record[i] == 1) { // Integer attribute
719           Attribute::AttrKind Kind;
720           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
721             return EC;
722           if (Kind == Attribute::Alignment)
723             B.addAlignmentAttr(Record[++i]);
724           else if (Kind == Attribute::StackAlignment)
725             B.addStackAlignmentAttr(Record[++i]);
726           else if (Kind == Attribute::Dereferenceable)
727             B.addDereferenceableAttr(Record[++i]);
728         } else {                     // String attribute
729           assert((Record[i] == 3 || Record[i] == 4) &&
730                  "Invalid attribute group entry");
731           bool HasValue = (Record[i++] == 4);
732           SmallString<64> KindStr;
733           SmallString<64> ValStr;
734
735           while (Record[i] != 0 && i != e)
736             KindStr += Record[i++];
737           assert(Record[i] == 0 && "Kind string not null terminated");
738
739           if (HasValue) {
740             // Has a value associated with it.
741             ++i; // Skip the '0' that terminates the "kind" string.
742             while (Record[i] != 0 && i != e)
743               ValStr += Record[i++];
744             assert(Record[i] == 0 && "Value string not null terminated");
745           }
746
747           B.addAttribute(KindStr.str(), ValStr.str());
748         }
749       }
750
751       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
752       break;
753     }
754     }
755   }
756 }
757
758 std::error_code BitcodeReader::ParseTypeTable() {
759   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
760     return Error(BitcodeError::InvalidRecord);
761
762   return ParseTypeTableBody();
763 }
764
765 std::error_code BitcodeReader::ParseTypeTableBody() {
766   if (!TypeList.empty())
767     return Error(BitcodeError::InvalidMultipleBlocks);
768
769   SmallVector<uint64_t, 64> Record;
770   unsigned NumRecords = 0;
771
772   SmallString<64> TypeName;
773
774   // Read all the records for this type table.
775   while (1) {
776     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
777
778     switch (Entry.Kind) {
779     case BitstreamEntry::SubBlock: // Handled for us already.
780     case BitstreamEntry::Error:
781       return Error(BitcodeError::MalformedBlock);
782     case BitstreamEntry::EndBlock:
783       if (NumRecords != TypeList.size())
784         return Error(BitcodeError::MalformedBlock);
785       return std::error_code();
786     case BitstreamEntry::Record:
787       // The interesting case.
788       break;
789     }
790
791     // Read a record.
792     Record.clear();
793     Type *ResultTy = nullptr;
794     switch (Stream.readRecord(Entry.ID, Record)) {
795     default:
796       return Error(BitcodeError::InvalidValue);
797     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
798       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
799       // type list.  This allows us to reserve space.
800       if (Record.size() < 1)
801         return Error(BitcodeError::InvalidRecord);
802       TypeList.resize(Record[0]);
803       continue;
804     case bitc::TYPE_CODE_VOID:      // VOID
805       ResultTy = Type::getVoidTy(Context);
806       break;
807     case bitc::TYPE_CODE_HALF:     // HALF
808       ResultTy = Type::getHalfTy(Context);
809       break;
810     case bitc::TYPE_CODE_FLOAT:     // FLOAT
811       ResultTy = Type::getFloatTy(Context);
812       break;
813     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
814       ResultTy = Type::getDoubleTy(Context);
815       break;
816     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
817       ResultTy = Type::getX86_FP80Ty(Context);
818       break;
819     case bitc::TYPE_CODE_FP128:     // FP128
820       ResultTy = Type::getFP128Ty(Context);
821       break;
822     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
823       ResultTy = Type::getPPC_FP128Ty(Context);
824       break;
825     case bitc::TYPE_CODE_LABEL:     // LABEL
826       ResultTy = Type::getLabelTy(Context);
827       break;
828     case bitc::TYPE_CODE_METADATA:  // METADATA
829       ResultTy = Type::getMetadataTy(Context);
830       break;
831     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
832       ResultTy = Type::getX86_MMXTy(Context);
833       break;
834     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
835       if (Record.size() < 1)
836         return Error(BitcodeError::InvalidRecord);
837
838       ResultTy = IntegerType::get(Context, Record[0]);
839       break;
840     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
841                                     //          [pointee type, address space]
842       if (Record.size() < 1)
843         return Error(BitcodeError::InvalidRecord);
844       unsigned AddressSpace = 0;
845       if (Record.size() == 2)
846         AddressSpace = Record[1];
847       ResultTy = getTypeByID(Record[0]);
848       if (!ResultTy)
849         return Error(BitcodeError::InvalidType);
850       ResultTy = PointerType::get(ResultTy, AddressSpace);
851       break;
852     }
853     case bitc::TYPE_CODE_FUNCTION_OLD: {
854       // FIXME: attrid is dead, remove it in LLVM 4.0
855       // FUNCTION: [vararg, attrid, retty, paramty x N]
856       if (Record.size() < 3)
857         return Error(BitcodeError::InvalidRecord);
858       SmallVector<Type*, 8> ArgTys;
859       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
860         if (Type *T = getTypeByID(Record[i]))
861           ArgTys.push_back(T);
862         else
863           break;
864       }
865
866       ResultTy = getTypeByID(Record[2]);
867       if (!ResultTy || ArgTys.size() < Record.size()-3)
868         return Error(BitcodeError::InvalidType);
869
870       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
871       break;
872     }
873     case bitc::TYPE_CODE_FUNCTION: {
874       // FUNCTION: [vararg, retty, paramty x N]
875       if (Record.size() < 2)
876         return Error(BitcodeError::InvalidRecord);
877       SmallVector<Type*, 8> ArgTys;
878       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
879         if (Type *T = getTypeByID(Record[i]))
880           ArgTys.push_back(T);
881         else
882           break;
883       }
884
885       ResultTy = getTypeByID(Record[1]);
886       if (!ResultTy || ArgTys.size() < Record.size()-2)
887         return Error(BitcodeError::InvalidType);
888
889       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
890       break;
891     }
892     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
893       if (Record.size() < 1)
894         return Error(BitcodeError::InvalidRecord);
895       SmallVector<Type*, 8> EltTys;
896       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
897         if (Type *T = getTypeByID(Record[i]))
898           EltTys.push_back(T);
899         else
900           break;
901       }
902       if (EltTys.size() != Record.size()-1)
903         return Error(BitcodeError::InvalidType);
904       ResultTy = StructType::get(Context, EltTys, Record[0]);
905       break;
906     }
907     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
908       if (ConvertToString(Record, 0, TypeName))
909         return Error(BitcodeError::InvalidRecord);
910       continue;
911
912     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
913       if (Record.size() < 1)
914         return Error(BitcodeError::InvalidRecord);
915
916       if (NumRecords >= TypeList.size())
917         return Error(BitcodeError::InvalidTYPETable);
918
919       // Check to see if this was forward referenced, if so fill in the temp.
920       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
921       if (Res) {
922         Res->setName(TypeName);
923         TypeList[NumRecords] = nullptr;
924       } else  // Otherwise, create a new struct.
925         Res = StructType::create(Context, TypeName);
926       TypeName.clear();
927
928       SmallVector<Type*, 8> EltTys;
929       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
930         if (Type *T = getTypeByID(Record[i]))
931           EltTys.push_back(T);
932         else
933           break;
934       }
935       if (EltTys.size() != Record.size()-1)
936         return Error(BitcodeError::InvalidRecord);
937       Res->setBody(EltTys, Record[0]);
938       ResultTy = Res;
939       break;
940     }
941     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
942       if (Record.size() != 1)
943         return Error(BitcodeError::InvalidRecord);
944
945       if (NumRecords >= TypeList.size())
946         return Error(BitcodeError::InvalidTYPETable);
947
948       // Check to see if this was forward referenced, if so fill in the temp.
949       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
950       if (Res) {
951         Res->setName(TypeName);
952         TypeList[NumRecords] = nullptr;
953       } else  // Otherwise, create a new struct with no body.
954         Res = StructType::create(Context, TypeName);
955       TypeName.clear();
956       ResultTy = Res;
957       break;
958     }
959     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
960       if (Record.size() < 2)
961         return Error(BitcodeError::InvalidRecord);
962       if ((ResultTy = getTypeByID(Record[1])))
963         ResultTy = ArrayType::get(ResultTy, Record[0]);
964       else
965         return Error(BitcodeError::InvalidType);
966       break;
967     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
968       if (Record.size() < 2)
969         return Error(BitcodeError::InvalidRecord);
970       if ((ResultTy = getTypeByID(Record[1])))
971         ResultTy = VectorType::get(ResultTy, Record[0]);
972       else
973         return Error(BitcodeError::InvalidType);
974       break;
975     }
976
977     if (NumRecords >= TypeList.size())
978       return Error(BitcodeError::InvalidTYPETable);
979     assert(ResultTy && "Didn't read a type?");
980     assert(!TypeList[NumRecords] && "Already read type?");
981     TypeList[NumRecords++] = ResultTy;
982   }
983 }
984
985 std::error_code BitcodeReader::ParseValueSymbolTable() {
986   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
987     return Error(BitcodeError::InvalidRecord);
988
989   SmallVector<uint64_t, 64> Record;
990
991   // Read all the records for this value table.
992   SmallString<128> ValueName;
993   while (1) {
994     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
995
996     switch (Entry.Kind) {
997     case BitstreamEntry::SubBlock: // Handled for us already.
998     case BitstreamEntry::Error:
999       return Error(BitcodeError::MalformedBlock);
1000     case BitstreamEntry::EndBlock:
1001       return std::error_code();
1002     case BitstreamEntry::Record:
1003       // The interesting case.
1004       break;
1005     }
1006
1007     // Read a record.
1008     Record.clear();
1009     switch (Stream.readRecord(Entry.ID, Record)) {
1010     default:  // Default behavior: unknown type.
1011       break;
1012     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1013       if (ConvertToString(Record, 1, ValueName))
1014         return Error(BitcodeError::InvalidRecord);
1015       unsigned ValueID = Record[0];
1016       if (ValueID >= ValueList.size() || !ValueList[ValueID])
1017         return Error(BitcodeError::InvalidRecord);
1018       Value *V = ValueList[ValueID];
1019
1020       V->setName(StringRef(ValueName.data(), ValueName.size()));
1021       ValueName.clear();
1022       break;
1023     }
1024     case bitc::VST_CODE_BBENTRY: {
1025       if (ConvertToString(Record, 1, ValueName))
1026         return Error(BitcodeError::InvalidRecord);
1027       BasicBlock *BB = getBasicBlock(Record[0]);
1028       if (!BB)
1029         return Error(BitcodeError::InvalidRecord);
1030
1031       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1032       ValueName.clear();
1033       break;
1034     }
1035     }
1036   }
1037 }
1038
1039 std::error_code BitcodeReader::ParseMetadata() {
1040   unsigned NextMDValueNo = MDValueList.size();
1041
1042   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1043     return Error(BitcodeError::InvalidRecord);
1044
1045   SmallVector<uint64_t, 64> Record;
1046
1047   // Read all the records.
1048   while (1) {
1049     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1050
1051     switch (Entry.Kind) {
1052     case BitstreamEntry::SubBlock: // Handled for us already.
1053     case BitstreamEntry::Error:
1054       return Error(BitcodeError::MalformedBlock);
1055     case BitstreamEntry::EndBlock:
1056       return std::error_code();
1057     case BitstreamEntry::Record:
1058       // The interesting case.
1059       break;
1060     }
1061
1062     bool IsFunctionLocal = false;
1063     // Read a record.
1064     Record.clear();
1065     unsigned Code = Stream.readRecord(Entry.ID, Record);
1066     switch (Code) {
1067     default:  // Default behavior: ignore.
1068       break;
1069     case bitc::METADATA_NAME: {
1070       // Read name of the named metadata.
1071       SmallString<8> Name(Record.begin(), Record.end());
1072       Record.clear();
1073       Code = Stream.ReadCode();
1074
1075       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1076       unsigned NextBitCode = Stream.readRecord(Code, Record);
1077       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1078
1079       // Read named metadata elements.
1080       unsigned Size = Record.size();
1081       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1082       for (unsigned i = 0; i != Size; ++i) {
1083         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1084         if (!MD)
1085           return Error(BitcodeError::InvalidRecord);
1086         NMD->addOperand(MD);
1087       }
1088       break;
1089     }
1090     case bitc::METADATA_FN_NODE:
1091       IsFunctionLocal = true;
1092       // fall-through
1093     case bitc::METADATA_NODE: {
1094       if (Record.size() % 2 == 1)
1095         return Error(BitcodeError::InvalidRecord);
1096
1097       unsigned Size = Record.size();
1098       SmallVector<Value*, 8> Elts;
1099       for (unsigned i = 0; i != Size; i += 2) {
1100         Type *Ty = getTypeByID(Record[i]);
1101         if (!Ty)
1102           return Error(BitcodeError::InvalidRecord);
1103         if (Ty->isMetadataTy())
1104           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1105         else if (!Ty->isVoidTy())
1106           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1107         else
1108           Elts.push_back(nullptr);
1109       }
1110       Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1111       IsFunctionLocal = false;
1112       MDValueList.AssignValue(V, NextMDValueNo++);
1113       break;
1114     }
1115     case bitc::METADATA_STRING: {
1116       std::string String(Record.begin(), Record.end());
1117       llvm::UpgradeMDStringConstant(String);
1118       Value *V = MDString::get(Context, String);
1119       MDValueList.AssignValue(V, NextMDValueNo++);
1120       break;
1121     }
1122     case bitc::METADATA_KIND: {
1123       if (Record.size() < 2)
1124         return Error(BitcodeError::InvalidRecord);
1125
1126       unsigned Kind = Record[0];
1127       SmallString<8> Name(Record.begin()+1, Record.end());
1128
1129       unsigned NewKind = TheModule->getMDKindID(Name.str());
1130       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1131         return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1132       break;
1133     }
1134     }
1135   }
1136 }
1137
1138 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1139 /// the LSB for dense VBR encoding.
1140 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1141   if ((V & 1) == 0)
1142     return V >> 1;
1143   if (V != 1)
1144     return -(V >> 1);
1145   // There is no such thing as -0 with integers.  "-0" really means MININT.
1146   return 1ULL << 63;
1147 }
1148
1149 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1150 /// values and aliases that we can.
1151 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1152   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1153   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1154   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1155
1156   GlobalInitWorklist.swap(GlobalInits);
1157   AliasInitWorklist.swap(AliasInits);
1158   FunctionPrefixWorklist.swap(FunctionPrefixes);
1159
1160   while (!GlobalInitWorklist.empty()) {
1161     unsigned ValID = GlobalInitWorklist.back().second;
1162     if (ValID >= ValueList.size()) {
1163       // Not ready to resolve this yet, it requires something later in the file.
1164       GlobalInits.push_back(GlobalInitWorklist.back());
1165     } else {
1166       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1167         GlobalInitWorklist.back().first->setInitializer(C);
1168       else
1169         return Error(BitcodeError::ExpectedConstant);
1170     }
1171     GlobalInitWorklist.pop_back();
1172   }
1173
1174   while (!AliasInitWorklist.empty()) {
1175     unsigned ValID = AliasInitWorklist.back().second;
1176     if (ValID >= ValueList.size()) {
1177       AliasInits.push_back(AliasInitWorklist.back());
1178     } else {
1179       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1180         AliasInitWorklist.back().first->setAliasee(C);
1181       else
1182         return Error(BitcodeError::ExpectedConstant);
1183     }
1184     AliasInitWorklist.pop_back();
1185   }
1186
1187   while (!FunctionPrefixWorklist.empty()) {
1188     unsigned ValID = FunctionPrefixWorklist.back().second;
1189     if (ValID >= ValueList.size()) {
1190       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1191     } else {
1192       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1193         FunctionPrefixWorklist.back().first->setPrefixData(C);
1194       else
1195         return Error(BitcodeError::ExpectedConstant);
1196     }
1197     FunctionPrefixWorklist.pop_back();
1198   }
1199
1200   return std::error_code();
1201 }
1202
1203 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1204   SmallVector<uint64_t, 8> Words(Vals.size());
1205   std::transform(Vals.begin(), Vals.end(), Words.begin(),
1206                  BitcodeReader::decodeSignRotatedValue);
1207
1208   return APInt(TypeBits, Words);
1209 }
1210
1211 std::error_code BitcodeReader::ParseConstants() {
1212   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1213     return Error(BitcodeError::InvalidRecord);
1214
1215   SmallVector<uint64_t, 64> Record;
1216
1217   // Read all the records for this value table.
1218   Type *CurTy = Type::getInt32Ty(Context);
1219   unsigned NextCstNo = ValueList.size();
1220   while (1) {
1221     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1222
1223     switch (Entry.Kind) {
1224     case BitstreamEntry::SubBlock: // Handled for us already.
1225     case BitstreamEntry::Error:
1226       return Error(BitcodeError::MalformedBlock);
1227     case BitstreamEntry::EndBlock:
1228       if (NextCstNo != ValueList.size())
1229         return Error(BitcodeError::InvalidConstantReference);
1230
1231       // Once all the constants have been read, go through and resolve forward
1232       // references.
1233       ValueList.ResolveConstantForwardRefs();
1234       return std::error_code();
1235     case BitstreamEntry::Record:
1236       // The interesting case.
1237       break;
1238     }
1239
1240     // Read a record.
1241     Record.clear();
1242     Value *V = nullptr;
1243     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1244     switch (BitCode) {
1245     default:  // Default behavior: unknown constant
1246     case bitc::CST_CODE_UNDEF:     // UNDEF
1247       V = UndefValue::get(CurTy);
1248       break;
1249     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1250       if (Record.empty())
1251         return Error(BitcodeError::InvalidRecord);
1252       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1253         return Error(BitcodeError::InvalidRecord);
1254       CurTy = TypeList[Record[0]];
1255       continue;  // Skip the ValueList manipulation.
1256     case bitc::CST_CODE_NULL:      // NULL
1257       V = Constant::getNullValue(CurTy);
1258       break;
1259     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1260       if (!CurTy->isIntegerTy() || Record.empty())
1261         return Error(BitcodeError::InvalidRecord);
1262       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1263       break;
1264     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1265       if (!CurTy->isIntegerTy() || Record.empty())
1266         return Error(BitcodeError::InvalidRecord);
1267
1268       APInt VInt = ReadWideAPInt(Record,
1269                                  cast<IntegerType>(CurTy)->getBitWidth());
1270       V = ConstantInt::get(Context, VInt);
1271
1272       break;
1273     }
1274     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1275       if (Record.empty())
1276         return Error(BitcodeError::InvalidRecord);
1277       if (CurTy->isHalfTy())
1278         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1279                                              APInt(16, (uint16_t)Record[0])));
1280       else if (CurTy->isFloatTy())
1281         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1282                                              APInt(32, (uint32_t)Record[0])));
1283       else if (CurTy->isDoubleTy())
1284         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1285                                              APInt(64, Record[0])));
1286       else if (CurTy->isX86_FP80Ty()) {
1287         // Bits are not stored the same way as a normal i80 APInt, compensate.
1288         uint64_t Rearrange[2];
1289         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1290         Rearrange[1] = Record[0] >> 48;
1291         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1292                                              APInt(80, Rearrange)));
1293       } else if (CurTy->isFP128Ty())
1294         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1295                                              APInt(128, Record)));
1296       else if (CurTy->isPPC_FP128Ty())
1297         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1298                                              APInt(128, Record)));
1299       else
1300         V = UndefValue::get(CurTy);
1301       break;
1302     }
1303
1304     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1305       if (Record.empty())
1306         return Error(BitcodeError::InvalidRecord);
1307
1308       unsigned Size = Record.size();
1309       SmallVector<Constant*, 16> Elts;
1310
1311       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1312         for (unsigned i = 0; i != Size; ++i)
1313           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1314                                                      STy->getElementType(i)));
1315         V = ConstantStruct::get(STy, Elts);
1316       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1317         Type *EltTy = ATy->getElementType();
1318         for (unsigned i = 0; i != Size; ++i)
1319           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1320         V = ConstantArray::get(ATy, Elts);
1321       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1322         Type *EltTy = VTy->getElementType();
1323         for (unsigned i = 0; i != Size; ++i)
1324           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1325         V = ConstantVector::get(Elts);
1326       } else {
1327         V = UndefValue::get(CurTy);
1328       }
1329       break;
1330     }
1331     case bitc::CST_CODE_STRING:    // STRING: [values]
1332     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1333       if (Record.empty())
1334         return Error(BitcodeError::InvalidRecord);
1335
1336       SmallString<16> Elts(Record.begin(), Record.end());
1337       V = ConstantDataArray::getString(Context, Elts,
1338                                        BitCode == bitc::CST_CODE_CSTRING);
1339       break;
1340     }
1341     case bitc::CST_CODE_DATA: {// DATA: [n x value]
1342       if (Record.empty())
1343         return Error(BitcodeError::InvalidRecord);
1344
1345       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1346       unsigned Size = Record.size();
1347
1348       if (EltTy->isIntegerTy(8)) {
1349         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1350         if (isa<VectorType>(CurTy))
1351           V = ConstantDataVector::get(Context, Elts);
1352         else
1353           V = ConstantDataArray::get(Context, Elts);
1354       } else if (EltTy->isIntegerTy(16)) {
1355         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1356         if (isa<VectorType>(CurTy))
1357           V = ConstantDataVector::get(Context, Elts);
1358         else
1359           V = ConstantDataArray::get(Context, Elts);
1360       } else if (EltTy->isIntegerTy(32)) {
1361         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1362         if (isa<VectorType>(CurTy))
1363           V = ConstantDataVector::get(Context, Elts);
1364         else
1365           V = ConstantDataArray::get(Context, Elts);
1366       } else if (EltTy->isIntegerTy(64)) {
1367         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1368         if (isa<VectorType>(CurTy))
1369           V = ConstantDataVector::get(Context, Elts);
1370         else
1371           V = ConstantDataArray::get(Context, Elts);
1372       } else if (EltTy->isFloatTy()) {
1373         SmallVector<float, 16> Elts(Size);
1374         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1375         if (isa<VectorType>(CurTy))
1376           V = ConstantDataVector::get(Context, Elts);
1377         else
1378           V = ConstantDataArray::get(Context, Elts);
1379       } else if (EltTy->isDoubleTy()) {
1380         SmallVector<double, 16> Elts(Size);
1381         std::transform(Record.begin(), Record.end(), Elts.begin(),
1382                        BitsToDouble);
1383         if (isa<VectorType>(CurTy))
1384           V = ConstantDataVector::get(Context, Elts);
1385         else
1386           V = ConstantDataArray::get(Context, Elts);
1387       } else {
1388         return Error(BitcodeError::InvalidTypeForValue);
1389       }
1390       break;
1391     }
1392
1393     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1394       if (Record.size() < 3)
1395         return Error(BitcodeError::InvalidRecord);
1396       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1397       if (Opc < 0) {
1398         V = UndefValue::get(CurTy);  // Unknown binop.
1399       } else {
1400         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1401         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1402         unsigned Flags = 0;
1403         if (Record.size() >= 4) {
1404           if (Opc == Instruction::Add ||
1405               Opc == Instruction::Sub ||
1406               Opc == Instruction::Mul ||
1407               Opc == Instruction::Shl) {
1408             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1409               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1410             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1411               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1412           } else if (Opc == Instruction::SDiv ||
1413                      Opc == Instruction::UDiv ||
1414                      Opc == Instruction::LShr ||
1415                      Opc == Instruction::AShr) {
1416             if (Record[3] & (1 << bitc::PEO_EXACT))
1417               Flags |= SDivOperator::IsExact;
1418           }
1419         }
1420         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1421       }
1422       break;
1423     }
1424     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1425       if (Record.size() < 3)
1426         return Error(BitcodeError::InvalidRecord);
1427       int Opc = GetDecodedCastOpcode(Record[0]);
1428       if (Opc < 0) {
1429         V = UndefValue::get(CurTy);  // Unknown cast.
1430       } else {
1431         Type *OpTy = getTypeByID(Record[1]);
1432         if (!OpTy)
1433           return Error(BitcodeError::InvalidRecord);
1434         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1435         V = UpgradeBitCastExpr(Opc, Op, CurTy);
1436         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1437       }
1438       break;
1439     }
1440     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1441     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1442       if (Record.size() & 1)
1443         return Error(BitcodeError::InvalidRecord);
1444       SmallVector<Constant*, 16> Elts;
1445       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1446         Type *ElTy = getTypeByID(Record[i]);
1447         if (!ElTy)
1448           return Error(BitcodeError::InvalidRecord);
1449         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1450       }
1451       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1452       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1453                                          BitCode ==
1454                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
1455       break;
1456     }
1457     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
1458       if (Record.size() < 3)
1459         return Error(BitcodeError::InvalidRecord);
1460
1461       Type *SelectorTy = Type::getInt1Ty(Context);
1462
1463       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1464       // vector. Otherwise, it must be a single bit.
1465       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1466         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1467                                      VTy->getNumElements());
1468
1469       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1470                                                               SelectorTy),
1471                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1472                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1473       break;
1474     }
1475     case bitc::CST_CODE_CE_EXTRACTELT
1476         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
1477       if (Record.size() < 3)
1478         return Error(BitcodeError::InvalidRecord);
1479       VectorType *OpTy =
1480         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1481       if (!OpTy)
1482         return Error(BitcodeError::InvalidRecord);
1483       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1484       Constant *Op1 = nullptr;
1485       if (Record.size() == 4) {
1486         Type *IdxTy = getTypeByID(Record[2]);
1487         if (!IdxTy)
1488           return Error(BitcodeError::InvalidRecord);
1489         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1490       } else // TODO: Remove with llvm 4.0
1491         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1492       if (!Op1)
1493         return Error(BitcodeError::InvalidRecord);
1494       V = ConstantExpr::getExtractElement(Op0, Op1);
1495       break;
1496     }
1497     case bitc::CST_CODE_CE_INSERTELT
1498         : { // CE_INSERTELT: [opval, opval, opty, opval]
1499       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1500       if (Record.size() < 3 || !OpTy)
1501         return Error(BitcodeError::InvalidRecord);
1502       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1503       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1504                                                   OpTy->getElementType());
1505       Constant *Op2 = nullptr;
1506       if (Record.size() == 4) {
1507         Type *IdxTy = getTypeByID(Record[2]);
1508         if (!IdxTy)
1509           return Error(BitcodeError::InvalidRecord);
1510         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
1511       } else // TODO: Remove with llvm 4.0
1512         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1513       if (!Op2)
1514         return Error(BitcodeError::InvalidRecord);
1515       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1516       break;
1517     }
1518     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1519       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1520       if (Record.size() < 3 || !OpTy)
1521         return Error(BitcodeError::InvalidRecord);
1522       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1523       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1524       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1525                                                  OpTy->getNumElements());
1526       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1527       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1528       break;
1529     }
1530     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1531       VectorType *RTy = dyn_cast<VectorType>(CurTy);
1532       VectorType *OpTy =
1533         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1534       if (Record.size() < 4 || !RTy || !OpTy)
1535         return Error(BitcodeError::InvalidRecord);
1536       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1537       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1538       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1539                                                  RTy->getNumElements());
1540       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1541       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1542       break;
1543     }
1544     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1545       if (Record.size() < 4)
1546         return Error(BitcodeError::InvalidRecord);
1547       Type *OpTy = getTypeByID(Record[0]);
1548       if (!OpTy)
1549         return Error(BitcodeError::InvalidRecord);
1550       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1551       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1552
1553       if (OpTy->isFPOrFPVectorTy())
1554         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1555       else
1556         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1557       break;
1558     }
1559     // This maintains backward compatibility, pre-asm dialect keywords.
1560     // FIXME: Remove with the 4.0 release.
1561     case bitc::CST_CODE_INLINEASM_OLD: {
1562       if (Record.size() < 2)
1563         return Error(BitcodeError::InvalidRecord);
1564       std::string AsmStr, ConstrStr;
1565       bool HasSideEffects = Record[0] & 1;
1566       bool IsAlignStack = Record[0] >> 1;
1567       unsigned AsmStrSize = Record[1];
1568       if (2+AsmStrSize >= Record.size())
1569         return Error(BitcodeError::InvalidRecord);
1570       unsigned ConstStrSize = Record[2+AsmStrSize];
1571       if (3+AsmStrSize+ConstStrSize > Record.size())
1572         return Error(BitcodeError::InvalidRecord);
1573
1574       for (unsigned i = 0; i != AsmStrSize; ++i)
1575         AsmStr += (char)Record[2+i];
1576       for (unsigned i = 0; i != ConstStrSize; ++i)
1577         ConstrStr += (char)Record[3+AsmStrSize+i];
1578       PointerType *PTy = cast<PointerType>(CurTy);
1579       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1580                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1581       break;
1582     }
1583     // This version adds support for the asm dialect keywords (e.g.,
1584     // inteldialect).
1585     case bitc::CST_CODE_INLINEASM: {
1586       if (Record.size() < 2)
1587         return Error(BitcodeError::InvalidRecord);
1588       std::string AsmStr, ConstrStr;
1589       bool HasSideEffects = Record[0] & 1;
1590       bool IsAlignStack = (Record[0] >> 1) & 1;
1591       unsigned AsmDialect = Record[0] >> 2;
1592       unsigned AsmStrSize = Record[1];
1593       if (2+AsmStrSize >= Record.size())
1594         return Error(BitcodeError::InvalidRecord);
1595       unsigned ConstStrSize = Record[2+AsmStrSize];
1596       if (3+AsmStrSize+ConstStrSize > Record.size())
1597         return Error(BitcodeError::InvalidRecord);
1598
1599       for (unsigned i = 0; i != AsmStrSize; ++i)
1600         AsmStr += (char)Record[2+i];
1601       for (unsigned i = 0; i != ConstStrSize; ++i)
1602         ConstrStr += (char)Record[3+AsmStrSize+i];
1603       PointerType *PTy = cast<PointerType>(CurTy);
1604       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1605                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1606                          InlineAsm::AsmDialect(AsmDialect));
1607       break;
1608     }
1609     case bitc::CST_CODE_BLOCKADDRESS:{
1610       if (Record.size() < 3)
1611         return Error(BitcodeError::InvalidRecord);
1612       Type *FnTy = getTypeByID(Record[0]);
1613       if (!FnTy)
1614         return Error(BitcodeError::InvalidRecord);
1615       Function *Fn =
1616         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1617       if (!Fn)
1618         return Error(BitcodeError::InvalidRecord);
1619
1620       // Don't let Fn get dematerialized.
1621       BlockAddressesTaken.insert(Fn);
1622
1623       // If the function is already parsed we can insert the block address right
1624       // away.
1625       BasicBlock *BB;
1626       unsigned BBID = Record[2];
1627       if (!BBID)
1628         // Invalid reference to entry block.
1629         return Error(BitcodeError::InvalidID);
1630       if (!Fn->empty()) {
1631         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1632         for (size_t I = 0, E = BBID; I != E; ++I) {
1633           if (BBI == BBE)
1634             return Error(BitcodeError::InvalidID);
1635           ++BBI;
1636         }
1637         BB = BBI;
1638       } else {
1639         // Otherwise insert a placeholder and remember it so it can be inserted
1640         // when the function is parsed.
1641         auto &FwdBBs = BasicBlockFwdRefs[Fn];
1642         if (FwdBBs.empty())
1643           BasicBlockFwdRefQueue.push_back(Fn);
1644         if (FwdBBs.size() < BBID + 1)
1645           FwdBBs.resize(BBID + 1);
1646         if (!FwdBBs[BBID])
1647           FwdBBs[BBID] = BasicBlock::Create(Context);
1648         BB = FwdBBs[BBID];
1649       }
1650       V = BlockAddress::get(Fn, BB);
1651       break;
1652     }
1653     }
1654
1655     ValueList.AssignValue(V, NextCstNo);
1656     ++NextCstNo;
1657   }
1658 }
1659
1660 std::error_code BitcodeReader::ParseUseLists() {
1661   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1662     return Error(BitcodeError::InvalidRecord);
1663
1664   // Read all the records.
1665   SmallVector<uint64_t, 64> Record;
1666   while (1) {
1667     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1668
1669     switch (Entry.Kind) {
1670     case BitstreamEntry::SubBlock: // Handled for us already.
1671     case BitstreamEntry::Error:
1672       return Error(BitcodeError::MalformedBlock);
1673     case BitstreamEntry::EndBlock:
1674       return std::error_code();
1675     case BitstreamEntry::Record:
1676       // The interesting case.
1677       break;
1678     }
1679
1680     // Read a use list record.
1681     Record.clear();
1682     bool IsBB = false;
1683     switch (Stream.readRecord(Entry.ID, Record)) {
1684     default:  // Default behavior: unknown type.
1685       break;
1686     case bitc::USELIST_CODE_BB:
1687       IsBB = true;
1688       // fallthrough
1689     case bitc::USELIST_CODE_DEFAULT: {
1690       unsigned RecordLength = Record.size();
1691       if (RecordLength < 3)
1692         // Records should have at least an ID and two indexes.
1693         return Error(BitcodeError::InvalidRecord);
1694       unsigned ID = Record.back();
1695       Record.pop_back();
1696
1697       Value *V;
1698       if (IsBB) {
1699         assert(ID < FunctionBBs.size() && "Basic block not found");
1700         V = FunctionBBs[ID];
1701       } else
1702         V = ValueList[ID];
1703       unsigned NumUses = 0;
1704       SmallDenseMap<const Use *, unsigned, 16> Order;
1705       for (const Use &U : V->uses()) {
1706         if (++NumUses > Record.size())
1707           break;
1708         Order[&U] = Record[NumUses - 1];
1709       }
1710       if (Order.size() != Record.size() || NumUses > Record.size())
1711         // Mismatches can happen if the functions are being materialized lazily
1712         // (out-of-order), or a value has been upgraded.
1713         break;
1714
1715       V->sortUseList([&](const Use &L, const Use &R) {
1716         return Order.lookup(&L) < Order.lookup(&R);
1717       });
1718       break;
1719     }
1720     }
1721   }
1722 }
1723
1724 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1725 /// remember where it is and then skip it.  This lets us lazily deserialize the
1726 /// functions.
1727 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1728   // Get the function we are talking about.
1729   if (FunctionsWithBodies.empty())
1730     return Error(BitcodeError::InsufficientFunctionProtos);
1731
1732   Function *Fn = FunctionsWithBodies.back();
1733   FunctionsWithBodies.pop_back();
1734
1735   // Save the current stream state.
1736   uint64_t CurBit = Stream.GetCurrentBitNo();
1737   DeferredFunctionInfo[Fn] = CurBit;
1738
1739   // Skip over the function block for now.
1740   if (Stream.SkipBlock())
1741     return Error(BitcodeError::InvalidRecord);
1742   return std::error_code();
1743 }
1744
1745 std::error_code BitcodeReader::GlobalCleanup() {
1746   // Patch the initializers for globals and aliases up.
1747   ResolveGlobalAndAliasInits();
1748   if (!GlobalInits.empty() || !AliasInits.empty())
1749     return Error(BitcodeError::MalformedGlobalInitializerSet);
1750
1751   // Look for intrinsic functions which need to be upgraded at some point
1752   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1753        FI != FE; ++FI) {
1754     Function *NewFn;
1755     if (UpgradeIntrinsicFunction(FI, NewFn))
1756       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1757   }
1758
1759   // Look for global variables which need to be renamed.
1760   for (Module::global_iterator
1761          GI = TheModule->global_begin(), GE = TheModule->global_end();
1762        GI != GE;) {
1763     GlobalVariable *GV = GI++;
1764     UpgradeGlobalVariable(GV);
1765   }
1766
1767   // Force deallocation of memory for these vectors to favor the client that
1768   // want lazy deserialization.
1769   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1770   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1771   return std::error_code();
1772 }
1773
1774 std::error_code BitcodeReader::ParseModule(bool Resume) {
1775   if (Resume)
1776     Stream.JumpToBit(NextUnreadBit);
1777   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1778     return Error(BitcodeError::InvalidRecord);
1779
1780   SmallVector<uint64_t, 64> Record;
1781   std::vector<std::string> SectionTable;
1782   std::vector<std::string> GCTable;
1783
1784   // Read all the records for this module.
1785   while (1) {
1786     BitstreamEntry Entry = Stream.advance();
1787
1788     switch (Entry.Kind) {
1789     case BitstreamEntry::Error:
1790       return Error(BitcodeError::MalformedBlock);
1791     case BitstreamEntry::EndBlock:
1792       return GlobalCleanup();
1793
1794     case BitstreamEntry::SubBlock:
1795       switch (Entry.ID) {
1796       default:  // Skip unknown content.
1797         if (Stream.SkipBlock())
1798           return Error(BitcodeError::InvalidRecord);
1799         break;
1800       case bitc::BLOCKINFO_BLOCK_ID:
1801         if (Stream.ReadBlockInfoBlock())
1802           return Error(BitcodeError::MalformedBlock);
1803         break;
1804       case bitc::PARAMATTR_BLOCK_ID:
1805         if (std::error_code EC = ParseAttributeBlock())
1806           return EC;
1807         break;
1808       case bitc::PARAMATTR_GROUP_BLOCK_ID:
1809         if (std::error_code EC = ParseAttributeGroupBlock())
1810           return EC;
1811         break;
1812       case bitc::TYPE_BLOCK_ID_NEW:
1813         if (std::error_code EC = ParseTypeTable())
1814           return EC;
1815         break;
1816       case bitc::VALUE_SYMTAB_BLOCK_ID:
1817         if (std::error_code EC = ParseValueSymbolTable())
1818           return EC;
1819         SeenValueSymbolTable = true;
1820         break;
1821       case bitc::CONSTANTS_BLOCK_ID:
1822         if (std::error_code EC = ParseConstants())
1823           return EC;
1824         if (std::error_code EC = ResolveGlobalAndAliasInits())
1825           return EC;
1826         break;
1827       case bitc::METADATA_BLOCK_ID:
1828         if (std::error_code EC = ParseMetadata())
1829           return EC;
1830         break;
1831       case bitc::FUNCTION_BLOCK_ID:
1832         // If this is the first function body we've seen, reverse the
1833         // FunctionsWithBodies list.
1834         if (!SeenFirstFunctionBody) {
1835           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1836           if (std::error_code EC = GlobalCleanup())
1837             return EC;
1838           SeenFirstFunctionBody = true;
1839         }
1840
1841         if (std::error_code EC = RememberAndSkipFunctionBody())
1842           return EC;
1843         // For streaming bitcode, suspend parsing when we reach the function
1844         // bodies. Subsequent materialization calls will resume it when
1845         // necessary. For streaming, the function bodies must be at the end of
1846         // the bitcode. If the bitcode file is old, the symbol table will be
1847         // at the end instead and will not have been seen yet. In this case,
1848         // just finish the parse now.
1849         if (LazyStreamer && SeenValueSymbolTable) {
1850           NextUnreadBit = Stream.GetCurrentBitNo();
1851           return std::error_code();
1852         }
1853         break;
1854       case bitc::USELIST_BLOCK_ID:
1855         if (std::error_code EC = ParseUseLists())
1856           return EC;
1857         break;
1858       }
1859       continue;
1860
1861     case BitstreamEntry::Record:
1862       // The interesting case.
1863       break;
1864     }
1865
1866
1867     // Read a record.
1868     switch (Stream.readRecord(Entry.ID, Record)) {
1869     default: break;  // Default behavior, ignore unknown content.
1870     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
1871       if (Record.size() < 1)
1872         return Error(BitcodeError::InvalidRecord);
1873       // Only version #0 and #1 are supported so far.
1874       unsigned module_version = Record[0];
1875       switch (module_version) {
1876         default:
1877           return Error(BitcodeError::InvalidValue);
1878         case 0:
1879           UseRelativeIDs = false;
1880           break;
1881         case 1:
1882           UseRelativeIDs = true;
1883           break;
1884       }
1885       break;
1886     }
1887     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1888       std::string S;
1889       if (ConvertToString(Record, 0, S))
1890         return Error(BitcodeError::InvalidRecord);
1891       TheModule->setTargetTriple(S);
1892       break;
1893     }
1894     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1895       std::string S;
1896       if (ConvertToString(Record, 0, S))
1897         return Error(BitcodeError::InvalidRecord);
1898       TheModule->setDataLayout(S);
1899       break;
1900     }
1901     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1902       std::string S;
1903       if (ConvertToString(Record, 0, S))
1904         return Error(BitcodeError::InvalidRecord);
1905       TheModule->setModuleInlineAsm(S);
1906       break;
1907     }
1908     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1909       // FIXME: Remove in 4.0.
1910       std::string S;
1911       if (ConvertToString(Record, 0, S))
1912         return Error(BitcodeError::InvalidRecord);
1913       // Ignore value.
1914       break;
1915     }
1916     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1917       std::string S;
1918       if (ConvertToString(Record, 0, S))
1919         return Error(BitcodeError::InvalidRecord);
1920       SectionTable.push_back(S);
1921       break;
1922     }
1923     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1924       std::string S;
1925       if (ConvertToString(Record, 0, S))
1926         return Error(BitcodeError::InvalidRecord);
1927       GCTable.push_back(S);
1928       break;
1929     }
1930     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
1931       if (Record.size() < 2)
1932         return Error(BitcodeError::InvalidRecord);
1933       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
1934       unsigned ComdatNameSize = Record[1];
1935       std::string ComdatName;
1936       ComdatName.reserve(ComdatNameSize);
1937       for (unsigned i = 0; i != ComdatNameSize; ++i)
1938         ComdatName += (char)Record[2 + i];
1939       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
1940       C->setSelectionKind(SK);
1941       ComdatList.push_back(C);
1942       break;
1943     }
1944     // GLOBALVAR: [pointer type, isconst, initid,
1945     //             linkage, alignment, section, visibility, threadlocal,
1946     //             unnamed_addr, dllstorageclass]
1947     case bitc::MODULE_CODE_GLOBALVAR: {
1948       if (Record.size() < 6)
1949         return Error(BitcodeError::InvalidRecord);
1950       Type *Ty = getTypeByID(Record[0]);
1951       if (!Ty)
1952         return Error(BitcodeError::InvalidRecord);
1953       if (!Ty->isPointerTy())
1954         return Error(BitcodeError::InvalidTypeForValue);
1955       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1956       Ty = cast<PointerType>(Ty)->getElementType();
1957
1958       bool isConstant = Record[1];
1959       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1960       unsigned Alignment = (1 << Record[4]) >> 1;
1961       std::string Section;
1962       if (Record[5]) {
1963         if (Record[5]-1 >= SectionTable.size())
1964           return Error(BitcodeError::InvalidID);
1965         Section = SectionTable[Record[5]-1];
1966       }
1967       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1968       // Local linkage must have default visibility.
1969       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
1970         // FIXME: Change to an error if non-default in 4.0.
1971         Visibility = GetDecodedVisibility(Record[6]);
1972
1973       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1974       if (Record.size() > 7)
1975         TLM = GetDecodedThreadLocalMode(Record[7]);
1976
1977       bool UnnamedAddr = false;
1978       if (Record.size() > 8)
1979         UnnamedAddr = Record[8];
1980
1981       bool ExternallyInitialized = false;
1982       if (Record.size() > 9)
1983         ExternallyInitialized = Record[9];
1984
1985       GlobalVariable *NewGV =
1986         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
1987                            TLM, AddressSpace, ExternallyInitialized);
1988       NewGV->setAlignment(Alignment);
1989       if (!Section.empty())
1990         NewGV->setSection(Section);
1991       NewGV->setVisibility(Visibility);
1992       NewGV->setUnnamedAddr(UnnamedAddr);
1993
1994       if (Record.size() > 10)
1995         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
1996       else
1997         UpgradeDLLImportExportLinkage(NewGV, Record[3]);
1998
1999       ValueList.push_back(NewGV);
2000
2001       // Remember which value to use for the global initializer.
2002       if (unsigned InitID = Record[2])
2003         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2004
2005       if (Record.size() > 11)
2006         if (unsigned ComdatID = Record[11]) {
2007           assert(ComdatID <= ComdatList.size());
2008           NewGV->setComdat(ComdatList[ComdatID - 1]);
2009         }
2010       break;
2011     }
2012     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
2013     //             alignment, section, visibility, gc, unnamed_addr,
2014     //             dllstorageclass]
2015     case bitc::MODULE_CODE_FUNCTION: {
2016       if (Record.size() < 8)
2017         return Error(BitcodeError::InvalidRecord);
2018       Type *Ty = getTypeByID(Record[0]);
2019       if (!Ty)
2020         return Error(BitcodeError::InvalidRecord);
2021       if (!Ty->isPointerTy())
2022         return Error(BitcodeError::InvalidTypeForValue);
2023       FunctionType *FTy =
2024         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2025       if (!FTy)
2026         return Error(BitcodeError::InvalidTypeForValue);
2027
2028       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2029                                         "", TheModule);
2030
2031       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2032       bool isProto = Record[2];
2033       Func->setLinkage(GetDecodedLinkage(Record[3]));
2034       Func->setAttributes(getAttributes(Record[4]));
2035
2036       Func->setAlignment((1 << Record[5]) >> 1);
2037       if (Record[6]) {
2038         if (Record[6]-1 >= SectionTable.size())
2039           return Error(BitcodeError::InvalidID);
2040         Func->setSection(SectionTable[Record[6]-1]);
2041       }
2042       // Local linkage must have default visibility.
2043       if (!Func->hasLocalLinkage())
2044         // FIXME: Change to an error if non-default in 4.0.
2045         Func->setVisibility(GetDecodedVisibility(Record[7]));
2046       if (Record.size() > 8 && Record[8]) {
2047         if (Record[8]-1 > GCTable.size())
2048           return Error(BitcodeError::InvalidID);
2049         Func->setGC(GCTable[Record[8]-1].c_str());
2050       }
2051       bool UnnamedAddr = false;
2052       if (Record.size() > 9)
2053         UnnamedAddr = Record[9];
2054       Func->setUnnamedAddr(UnnamedAddr);
2055       if (Record.size() > 10 && Record[10] != 0)
2056         FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
2057
2058       if (Record.size() > 11)
2059         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2060       else
2061         UpgradeDLLImportExportLinkage(Func, Record[3]);
2062
2063       if (Record.size() > 12)
2064         if (unsigned ComdatID = Record[12]) {
2065           assert(ComdatID <= ComdatList.size());
2066           Func->setComdat(ComdatList[ComdatID - 1]);
2067         }
2068
2069       ValueList.push_back(Func);
2070
2071       // If this is a function with a body, remember the prototype we are
2072       // creating now, so that we can match up the body with them later.
2073       if (!isProto) {
2074         Func->setIsMaterializable(true);
2075         FunctionsWithBodies.push_back(Func);
2076         if (LazyStreamer)
2077           DeferredFunctionInfo[Func] = 0;
2078       }
2079       break;
2080     }
2081     // ALIAS: [alias type, aliasee val#, linkage]
2082     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2083     case bitc::MODULE_CODE_ALIAS: {
2084       if (Record.size() < 3)
2085         return Error(BitcodeError::InvalidRecord);
2086       Type *Ty = getTypeByID(Record[0]);
2087       if (!Ty)
2088         return Error(BitcodeError::InvalidRecord);
2089       auto *PTy = dyn_cast<PointerType>(Ty);
2090       if (!PTy)
2091         return Error(BitcodeError::InvalidTypeForValue);
2092
2093       auto *NewGA =
2094           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
2095                               GetDecodedLinkage(Record[2]), "", TheModule);
2096       // Old bitcode files didn't have visibility field.
2097       // Local linkage must have default visibility.
2098       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
2099         // FIXME: Change to an error if non-default in 4.0.
2100         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2101       if (Record.size() > 4)
2102         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
2103       else
2104         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
2105       if (Record.size() > 5)
2106         NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
2107       if (Record.size() > 6)
2108         NewGA->setUnnamedAddr(Record[6]);
2109       ValueList.push_back(NewGA);
2110       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2111       break;
2112     }
2113     /// MODULE_CODE_PURGEVALS: [numvals]
2114     case bitc::MODULE_CODE_PURGEVALS:
2115       // Trim down the value list to the specified size.
2116       if (Record.size() < 1 || Record[0] > ValueList.size())
2117         return Error(BitcodeError::InvalidRecord);
2118       ValueList.shrinkTo(Record[0]);
2119       break;
2120     }
2121     Record.clear();
2122   }
2123 }
2124
2125 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2126   TheModule = nullptr;
2127
2128   if (std::error_code EC = InitStream())
2129     return EC;
2130
2131   // Sniff for the signature.
2132   if (Stream.Read(8) != 'B' ||
2133       Stream.Read(8) != 'C' ||
2134       Stream.Read(4) != 0x0 ||
2135       Stream.Read(4) != 0xC ||
2136       Stream.Read(4) != 0xE ||
2137       Stream.Read(4) != 0xD)
2138     return Error(BitcodeError::InvalidBitcodeSignature);
2139
2140   // We expect a number of well-defined blocks, though we don't necessarily
2141   // need to understand them all.
2142   while (1) {
2143     if (Stream.AtEndOfStream())
2144       return std::error_code();
2145
2146     BitstreamEntry Entry =
2147       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2148
2149     switch (Entry.Kind) {
2150     case BitstreamEntry::Error:
2151       return Error(BitcodeError::MalformedBlock);
2152     case BitstreamEntry::EndBlock:
2153       return std::error_code();
2154
2155     case BitstreamEntry::SubBlock:
2156       switch (Entry.ID) {
2157       case bitc::BLOCKINFO_BLOCK_ID:
2158         if (Stream.ReadBlockInfoBlock())
2159           return Error(BitcodeError::MalformedBlock);
2160         break;
2161       case bitc::MODULE_BLOCK_ID:
2162         // Reject multiple MODULE_BLOCK's in a single bitstream.
2163         if (TheModule)
2164           return Error(BitcodeError::InvalidMultipleBlocks);
2165         TheModule = M;
2166         if (std::error_code EC = ParseModule(false))
2167           return EC;
2168         if (LazyStreamer)
2169           return std::error_code();
2170         break;
2171       default:
2172         if (Stream.SkipBlock())
2173           return Error(BitcodeError::InvalidRecord);
2174         break;
2175       }
2176       continue;
2177     case BitstreamEntry::Record:
2178       // There should be no records in the top-level of blocks.
2179
2180       // The ranlib in Xcode 4 will align archive members by appending newlines
2181       // to the end of them. If this file size is a multiple of 4 but not 8, we
2182       // have to read and ignore these final 4 bytes :-(
2183       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2184           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2185           Stream.AtEndOfStream())
2186         return std::error_code();
2187
2188       return Error(BitcodeError::InvalidRecord);
2189     }
2190   }
2191 }
2192
2193 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2194   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2195     return Error(BitcodeError::InvalidRecord);
2196
2197   SmallVector<uint64_t, 64> Record;
2198
2199   std::string Triple;
2200   // Read all the records for this module.
2201   while (1) {
2202     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2203
2204     switch (Entry.Kind) {
2205     case BitstreamEntry::SubBlock: // Handled for us already.
2206     case BitstreamEntry::Error:
2207       return Error(BitcodeError::MalformedBlock);
2208     case BitstreamEntry::EndBlock:
2209       return Triple;
2210     case BitstreamEntry::Record:
2211       // The interesting case.
2212       break;
2213     }
2214
2215     // Read a record.
2216     switch (Stream.readRecord(Entry.ID, Record)) {
2217     default: break;  // Default behavior, ignore unknown content.
2218     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2219       std::string S;
2220       if (ConvertToString(Record, 0, S))
2221         return Error(BitcodeError::InvalidRecord);
2222       Triple = S;
2223       break;
2224     }
2225     }
2226     Record.clear();
2227   }
2228   llvm_unreachable("Exit infinite loop");
2229 }
2230
2231 ErrorOr<std::string> BitcodeReader::parseTriple() {
2232   if (std::error_code EC = InitStream())
2233     return EC;
2234
2235   // Sniff for the signature.
2236   if (Stream.Read(8) != 'B' ||
2237       Stream.Read(8) != 'C' ||
2238       Stream.Read(4) != 0x0 ||
2239       Stream.Read(4) != 0xC ||
2240       Stream.Read(4) != 0xE ||
2241       Stream.Read(4) != 0xD)
2242     return Error(BitcodeError::InvalidBitcodeSignature);
2243
2244   // We expect a number of well-defined blocks, though we don't necessarily
2245   // need to understand them all.
2246   while (1) {
2247     BitstreamEntry Entry = Stream.advance();
2248
2249     switch (Entry.Kind) {
2250     case BitstreamEntry::Error:
2251       return Error(BitcodeError::MalformedBlock);
2252     case BitstreamEntry::EndBlock:
2253       return std::error_code();
2254
2255     case BitstreamEntry::SubBlock:
2256       if (Entry.ID == bitc::MODULE_BLOCK_ID)
2257         return parseModuleTriple();
2258
2259       // Ignore other sub-blocks.
2260       if (Stream.SkipBlock())
2261         return Error(BitcodeError::MalformedBlock);
2262       continue;
2263
2264     case BitstreamEntry::Record:
2265       Stream.skipRecord(Entry.ID);
2266       continue;
2267     }
2268   }
2269 }
2270
2271 /// ParseMetadataAttachment - Parse metadata attachments.
2272 std::error_code BitcodeReader::ParseMetadataAttachment() {
2273   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2274     return Error(BitcodeError::InvalidRecord);
2275
2276   SmallVector<uint64_t, 64> Record;
2277   while (1) {
2278     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2279
2280     switch (Entry.Kind) {
2281     case BitstreamEntry::SubBlock: // Handled for us already.
2282     case BitstreamEntry::Error:
2283       return Error(BitcodeError::MalformedBlock);
2284     case BitstreamEntry::EndBlock:
2285       return std::error_code();
2286     case BitstreamEntry::Record:
2287       // The interesting case.
2288       break;
2289     }
2290
2291     // Read a metadata attachment record.
2292     Record.clear();
2293     switch (Stream.readRecord(Entry.ID, Record)) {
2294     default:  // Default behavior: ignore.
2295       break;
2296     case bitc::METADATA_ATTACHMENT: {
2297       unsigned RecordLength = Record.size();
2298       if (Record.empty() || (RecordLength - 1) % 2 == 1)
2299         return Error(BitcodeError::InvalidRecord);
2300       Instruction *Inst = InstructionList[Record[0]];
2301       for (unsigned i = 1; i != RecordLength; i = i+2) {
2302         unsigned Kind = Record[i];
2303         DenseMap<unsigned, unsigned>::iterator I =
2304           MDKindMap.find(Kind);
2305         if (I == MDKindMap.end())
2306           return Error(BitcodeError::InvalidID);
2307         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2308         Inst->setMetadata(I->second, cast<MDNode>(Node));
2309         if (I->second == LLVMContext::MD_tbaa)
2310           InstsWithTBAATag.push_back(Inst);
2311       }
2312       break;
2313     }
2314     }
2315   }
2316 }
2317
2318 /// ParseFunctionBody - Lazily parse the specified function body block.
2319 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2320   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2321     return Error(BitcodeError::InvalidRecord);
2322
2323   InstructionList.clear();
2324   unsigned ModuleValueListSize = ValueList.size();
2325   unsigned ModuleMDValueListSize = MDValueList.size();
2326
2327   // Add all the function arguments to the value table.
2328   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2329     ValueList.push_back(I);
2330
2331   unsigned NextValueNo = ValueList.size();
2332   BasicBlock *CurBB = nullptr;
2333   unsigned CurBBNo = 0;
2334
2335   DebugLoc LastLoc;
2336
2337   // Read all the records.
2338   SmallVector<uint64_t, 64> Record;
2339   while (1) {
2340     BitstreamEntry Entry = Stream.advance();
2341
2342     switch (Entry.Kind) {
2343     case BitstreamEntry::Error:
2344       return Error(BitcodeError::MalformedBlock);
2345     case BitstreamEntry::EndBlock:
2346       goto OutOfRecordLoop;
2347
2348     case BitstreamEntry::SubBlock:
2349       switch (Entry.ID) {
2350       default:  // Skip unknown content.
2351         if (Stream.SkipBlock())
2352           return Error(BitcodeError::InvalidRecord);
2353         break;
2354       case bitc::CONSTANTS_BLOCK_ID:
2355         if (std::error_code EC = ParseConstants())
2356           return EC;
2357         NextValueNo = ValueList.size();
2358         break;
2359       case bitc::VALUE_SYMTAB_BLOCK_ID:
2360         if (std::error_code EC = ParseValueSymbolTable())
2361           return EC;
2362         break;
2363       case bitc::METADATA_ATTACHMENT_ID:
2364         if (std::error_code EC = ParseMetadataAttachment())
2365           return EC;
2366         break;
2367       case bitc::METADATA_BLOCK_ID:
2368         if (std::error_code EC = ParseMetadata())
2369           return EC;
2370         break;
2371       case bitc::USELIST_BLOCK_ID:
2372         if (std::error_code EC = ParseUseLists())
2373           return EC;
2374         break;
2375       }
2376       continue;
2377
2378     case BitstreamEntry::Record:
2379       // The interesting case.
2380       break;
2381     }
2382
2383     // Read a record.
2384     Record.clear();
2385     Instruction *I = nullptr;
2386     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2387     switch (BitCode) {
2388     default: // Default behavior: reject
2389       return Error(BitcodeError::InvalidValue);
2390     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
2391       if (Record.size() < 1 || Record[0] == 0)
2392         return Error(BitcodeError::InvalidRecord);
2393       // Create all the basic blocks for the function.
2394       FunctionBBs.resize(Record[0]);
2395
2396       // See if anything took the address of blocks in this function.
2397       auto BBFRI = BasicBlockFwdRefs.find(F);
2398       if (BBFRI == BasicBlockFwdRefs.end()) {
2399         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2400           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2401       } else {
2402         auto &BBRefs = BBFRI->second;
2403         // Check for invalid basic block references.
2404         if (BBRefs.size() > FunctionBBs.size())
2405           return Error(BitcodeError::InvalidID);
2406         assert(!BBRefs.empty() && "Unexpected empty array");
2407         assert(!BBRefs.front() && "Invalid reference to entry block");
2408         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
2409              ++I)
2410           if (I < RE && BBRefs[I]) {
2411             BBRefs[I]->insertInto(F);
2412             FunctionBBs[I] = BBRefs[I];
2413           } else {
2414             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
2415           }
2416
2417         // Erase from the table.
2418         BasicBlockFwdRefs.erase(BBFRI);
2419       }
2420
2421       CurBB = FunctionBBs[0];
2422       continue;
2423     }
2424
2425     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
2426       // This record indicates that the last instruction is at the same
2427       // location as the previous instruction with a location.
2428       I = nullptr;
2429
2430       // Get the last instruction emitted.
2431       if (CurBB && !CurBB->empty())
2432         I = &CurBB->back();
2433       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2434                !FunctionBBs[CurBBNo-1]->empty())
2435         I = &FunctionBBs[CurBBNo-1]->back();
2436
2437       if (!I)
2438         return Error(BitcodeError::InvalidRecord);
2439       I->setDebugLoc(LastLoc);
2440       I = nullptr;
2441       continue;
2442
2443     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2444       I = nullptr;     // Get the last instruction emitted.
2445       if (CurBB && !CurBB->empty())
2446         I = &CurBB->back();
2447       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2448                !FunctionBBs[CurBBNo-1]->empty())
2449         I = &FunctionBBs[CurBBNo-1]->back();
2450       if (!I || Record.size() < 4)
2451         return Error(BitcodeError::InvalidRecord);
2452
2453       unsigned Line = Record[0], Col = Record[1];
2454       unsigned ScopeID = Record[2], IAID = Record[3];
2455
2456       MDNode *Scope = nullptr, *IA = nullptr;
2457       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2458       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2459       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2460       I->setDebugLoc(LastLoc);
2461       I = nullptr;
2462       continue;
2463     }
2464
2465     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2466       unsigned OpNum = 0;
2467       Value *LHS, *RHS;
2468       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2469           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2470           OpNum+1 > Record.size())
2471         return Error(BitcodeError::InvalidRecord);
2472
2473       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2474       if (Opc == -1)
2475         return Error(BitcodeError::InvalidRecord);
2476       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2477       InstructionList.push_back(I);
2478       if (OpNum < Record.size()) {
2479         if (Opc == Instruction::Add ||
2480             Opc == Instruction::Sub ||
2481             Opc == Instruction::Mul ||
2482             Opc == Instruction::Shl) {
2483           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2484             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2485           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2486             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2487         } else if (Opc == Instruction::SDiv ||
2488                    Opc == Instruction::UDiv ||
2489                    Opc == Instruction::LShr ||
2490                    Opc == Instruction::AShr) {
2491           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2492             cast<BinaryOperator>(I)->setIsExact(true);
2493         } else if (isa<FPMathOperator>(I)) {
2494           FastMathFlags FMF;
2495           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2496             FMF.setUnsafeAlgebra();
2497           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2498             FMF.setNoNaNs();
2499           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2500             FMF.setNoInfs();
2501           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2502             FMF.setNoSignedZeros();
2503           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2504             FMF.setAllowReciprocal();
2505           if (FMF.any())
2506             I->setFastMathFlags(FMF);
2507         }
2508
2509       }
2510       break;
2511     }
2512     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2513       unsigned OpNum = 0;
2514       Value *Op;
2515       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2516           OpNum+2 != Record.size())
2517         return Error(BitcodeError::InvalidRecord);
2518
2519       Type *ResTy = getTypeByID(Record[OpNum]);
2520       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2521       if (Opc == -1 || !ResTy)
2522         return Error(BitcodeError::InvalidRecord);
2523       Instruction *Temp = nullptr;
2524       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
2525         if (Temp) {
2526           InstructionList.push_back(Temp);
2527           CurBB->getInstList().push_back(Temp);
2528         }
2529       } else {
2530         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2531       }
2532       InstructionList.push_back(I);
2533       break;
2534     }
2535     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2536     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2537       unsigned OpNum = 0;
2538       Value *BasePtr;
2539       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2540         return Error(BitcodeError::InvalidRecord);
2541
2542       SmallVector<Value*, 16> GEPIdx;
2543       while (OpNum != Record.size()) {
2544         Value *Op;
2545         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2546           return Error(BitcodeError::InvalidRecord);
2547         GEPIdx.push_back(Op);
2548       }
2549
2550       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2551       InstructionList.push_back(I);
2552       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2553         cast<GetElementPtrInst>(I)->setIsInBounds(true);
2554       break;
2555     }
2556
2557     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2558                                        // EXTRACTVAL: [opty, opval, n x indices]
2559       unsigned OpNum = 0;
2560       Value *Agg;
2561       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2562         return Error(BitcodeError::InvalidRecord);
2563
2564       SmallVector<unsigned, 4> EXTRACTVALIdx;
2565       for (unsigned RecSize = Record.size();
2566            OpNum != RecSize; ++OpNum) {
2567         uint64_t Index = Record[OpNum];
2568         if ((unsigned)Index != Index)
2569           return Error(BitcodeError::InvalidValue);
2570         EXTRACTVALIdx.push_back((unsigned)Index);
2571       }
2572
2573       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2574       InstructionList.push_back(I);
2575       break;
2576     }
2577
2578     case bitc::FUNC_CODE_INST_INSERTVAL: {
2579                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
2580       unsigned OpNum = 0;
2581       Value *Agg;
2582       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2583         return Error(BitcodeError::InvalidRecord);
2584       Value *Val;
2585       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2586         return Error(BitcodeError::InvalidRecord);
2587
2588       SmallVector<unsigned, 4> INSERTVALIdx;
2589       for (unsigned RecSize = Record.size();
2590            OpNum != RecSize; ++OpNum) {
2591         uint64_t Index = Record[OpNum];
2592         if ((unsigned)Index != Index)
2593           return Error(BitcodeError::InvalidValue);
2594         INSERTVALIdx.push_back((unsigned)Index);
2595       }
2596
2597       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2598       InstructionList.push_back(I);
2599       break;
2600     }
2601
2602     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2603       // obsolete form of select
2604       // handles select i1 ... in old bitcode
2605       unsigned OpNum = 0;
2606       Value *TrueVal, *FalseVal, *Cond;
2607       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2608           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2609           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2610         return Error(BitcodeError::InvalidRecord);
2611
2612       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2613       InstructionList.push_back(I);
2614       break;
2615     }
2616
2617     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2618       // new form of select
2619       // handles select i1 or select [N x i1]
2620       unsigned OpNum = 0;
2621       Value *TrueVal, *FalseVal, *Cond;
2622       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2623           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2624           getValueTypePair(Record, OpNum, NextValueNo, Cond))
2625         return Error(BitcodeError::InvalidRecord);
2626
2627       // select condition can be either i1 or [N x i1]
2628       if (VectorType* vector_type =
2629           dyn_cast<VectorType>(Cond->getType())) {
2630         // expect <n x i1>
2631         if (vector_type->getElementType() != Type::getInt1Ty(Context))
2632           return Error(BitcodeError::InvalidTypeForValue);
2633       } else {
2634         // expect i1
2635         if (Cond->getType() != Type::getInt1Ty(Context))
2636           return Error(BitcodeError::InvalidTypeForValue);
2637       }
2638
2639       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2640       InstructionList.push_back(I);
2641       break;
2642     }
2643
2644     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2645       unsigned OpNum = 0;
2646       Value *Vec, *Idx;
2647       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2648           getValueTypePair(Record, OpNum, NextValueNo, Idx))
2649         return Error(BitcodeError::InvalidRecord);
2650       I = ExtractElementInst::Create(Vec, Idx);
2651       InstructionList.push_back(I);
2652       break;
2653     }
2654
2655     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2656       unsigned OpNum = 0;
2657       Value *Vec, *Elt, *Idx;
2658       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2659           popValue(Record, OpNum, NextValueNo,
2660                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2661           getValueTypePair(Record, OpNum, NextValueNo, Idx))
2662         return Error(BitcodeError::InvalidRecord);
2663       I = InsertElementInst::Create(Vec, Elt, Idx);
2664       InstructionList.push_back(I);
2665       break;
2666     }
2667
2668     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2669       unsigned OpNum = 0;
2670       Value *Vec1, *Vec2, *Mask;
2671       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2672           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2673         return Error(BitcodeError::InvalidRecord);
2674
2675       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2676         return Error(BitcodeError::InvalidRecord);
2677       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2678       InstructionList.push_back(I);
2679       break;
2680     }
2681
2682     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2683       // Old form of ICmp/FCmp returning bool
2684       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2685       // both legal on vectors but had different behaviour.
2686     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2687       // FCmp/ICmp returning bool or vector of bool
2688
2689       unsigned OpNum = 0;
2690       Value *LHS, *RHS;
2691       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2692           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2693           OpNum+1 != Record.size())
2694         return Error(BitcodeError::InvalidRecord);
2695
2696       if (LHS->getType()->isFPOrFPVectorTy())
2697         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2698       else
2699         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2700       InstructionList.push_back(I);
2701       break;
2702     }
2703
2704     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2705       {
2706         unsigned Size = Record.size();
2707         if (Size == 0) {
2708           I = ReturnInst::Create(Context);
2709           InstructionList.push_back(I);
2710           break;
2711         }
2712
2713         unsigned OpNum = 0;
2714         Value *Op = nullptr;
2715         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2716           return Error(BitcodeError::InvalidRecord);
2717         if (OpNum != Record.size())
2718           return Error(BitcodeError::InvalidRecord);
2719
2720         I = ReturnInst::Create(Context, Op);
2721         InstructionList.push_back(I);
2722         break;
2723       }
2724     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2725       if (Record.size() != 1 && Record.size() != 3)
2726         return Error(BitcodeError::InvalidRecord);
2727       BasicBlock *TrueDest = getBasicBlock(Record[0]);
2728       if (!TrueDest)
2729         return Error(BitcodeError::InvalidRecord);
2730
2731       if (Record.size() == 1) {
2732         I = BranchInst::Create(TrueDest);
2733         InstructionList.push_back(I);
2734       }
2735       else {
2736         BasicBlock *FalseDest = getBasicBlock(Record[1]);
2737         Value *Cond = getValue(Record, 2, NextValueNo,
2738                                Type::getInt1Ty(Context));
2739         if (!FalseDest || !Cond)
2740           return Error(BitcodeError::InvalidRecord);
2741         I = BranchInst::Create(TrueDest, FalseDest, Cond);
2742         InstructionList.push_back(I);
2743       }
2744       break;
2745     }
2746     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2747       // Check magic
2748       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2749         // "New" SwitchInst format with case ranges. The changes to write this
2750         // format were reverted but we still recognize bitcode that uses it.
2751         // Hopefully someday we will have support for case ranges and can use
2752         // this format again.
2753
2754         Type *OpTy = getTypeByID(Record[1]);
2755         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2756
2757         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2758         BasicBlock *Default = getBasicBlock(Record[3]);
2759         if (!OpTy || !Cond || !Default)
2760           return Error(BitcodeError::InvalidRecord);
2761
2762         unsigned NumCases = Record[4];
2763
2764         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2765         InstructionList.push_back(SI);
2766
2767         unsigned CurIdx = 5;
2768         for (unsigned i = 0; i != NumCases; ++i) {
2769           SmallVector<ConstantInt*, 1> CaseVals;
2770           unsigned NumItems = Record[CurIdx++];
2771           for (unsigned ci = 0; ci != NumItems; ++ci) {
2772             bool isSingleNumber = Record[CurIdx++];
2773
2774             APInt Low;
2775             unsigned ActiveWords = 1;
2776             if (ValueBitWidth > 64)
2777               ActiveWords = Record[CurIdx++];
2778             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2779                                 ValueBitWidth);
2780             CurIdx += ActiveWords;
2781
2782             if (!isSingleNumber) {
2783               ActiveWords = 1;
2784               if (ValueBitWidth > 64)
2785                 ActiveWords = Record[CurIdx++];
2786               APInt High =
2787                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2788                                 ValueBitWidth);
2789               CurIdx += ActiveWords;
2790
2791               // FIXME: It is not clear whether values in the range should be
2792               // compared as signed or unsigned values. The partially
2793               // implemented changes that used this format in the past used
2794               // unsigned comparisons.
2795               for ( ; Low.ule(High); ++Low)
2796                 CaseVals.push_back(ConstantInt::get(Context, Low));
2797             } else
2798               CaseVals.push_back(ConstantInt::get(Context, Low));
2799           }
2800           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2801           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2802                  cve = CaseVals.end(); cvi != cve; ++cvi)
2803             SI->addCase(*cvi, DestBB);
2804         }
2805         I = SI;
2806         break;
2807       }
2808
2809       // Old SwitchInst format without case ranges.
2810
2811       if (Record.size() < 3 || (Record.size() & 1) == 0)
2812         return Error(BitcodeError::InvalidRecord);
2813       Type *OpTy = getTypeByID(Record[0]);
2814       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2815       BasicBlock *Default = getBasicBlock(Record[2]);
2816       if (!OpTy || !Cond || !Default)
2817         return Error(BitcodeError::InvalidRecord);
2818       unsigned NumCases = (Record.size()-3)/2;
2819       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2820       InstructionList.push_back(SI);
2821       for (unsigned i = 0, e = NumCases; i != e; ++i) {
2822         ConstantInt *CaseVal =
2823           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2824         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2825         if (!CaseVal || !DestBB) {
2826           delete SI;
2827           return Error(BitcodeError::InvalidRecord);
2828         }
2829         SI->addCase(CaseVal, DestBB);
2830       }
2831       I = SI;
2832       break;
2833     }
2834     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2835       if (Record.size() < 2)
2836         return Error(BitcodeError::InvalidRecord);
2837       Type *OpTy = getTypeByID(Record[0]);
2838       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2839       if (!OpTy || !Address)
2840         return Error(BitcodeError::InvalidRecord);
2841       unsigned NumDests = Record.size()-2;
2842       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2843       InstructionList.push_back(IBI);
2844       for (unsigned i = 0, e = NumDests; i != e; ++i) {
2845         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2846           IBI->addDestination(DestBB);
2847         } else {
2848           delete IBI;
2849           return Error(BitcodeError::InvalidRecord);
2850         }
2851       }
2852       I = IBI;
2853       break;
2854     }
2855
2856     case bitc::FUNC_CODE_INST_INVOKE: {
2857       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2858       if (Record.size() < 4)
2859         return Error(BitcodeError::InvalidRecord);
2860       AttributeSet PAL = getAttributes(Record[0]);
2861       unsigned CCInfo = Record[1];
2862       BasicBlock *NormalBB = getBasicBlock(Record[2]);
2863       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2864
2865       unsigned OpNum = 4;
2866       Value *Callee;
2867       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2868         return Error(BitcodeError::InvalidRecord);
2869
2870       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2871       FunctionType *FTy = !CalleeTy ? nullptr :
2872         dyn_cast<FunctionType>(CalleeTy->getElementType());
2873
2874       // Check that the right number of fixed parameters are here.
2875       if (!FTy || !NormalBB || !UnwindBB ||
2876           Record.size() < OpNum+FTy->getNumParams())
2877         return Error(BitcodeError::InvalidRecord);
2878
2879       SmallVector<Value*, 16> Ops;
2880       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2881         Ops.push_back(getValue(Record, OpNum, NextValueNo,
2882                                FTy->getParamType(i)));
2883         if (!Ops.back())
2884           return Error(BitcodeError::InvalidRecord);
2885       }
2886
2887       if (!FTy->isVarArg()) {
2888         if (Record.size() != OpNum)
2889           return Error(BitcodeError::InvalidRecord);
2890       } else {
2891         // Read type/value pairs for varargs params.
2892         while (OpNum != Record.size()) {
2893           Value *Op;
2894           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2895             return Error(BitcodeError::InvalidRecord);
2896           Ops.push_back(Op);
2897         }
2898       }
2899
2900       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2901       InstructionList.push_back(I);
2902       cast<InvokeInst>(I)->setCallingConv(
2903         static_cast<CallingConv::ID>(CCInfo));
2904       cast<InvokeInst>(I)->setAttributes(PAL);
2905       break;
2906     }
2907     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2908       unsigned Idx = 0;
2909       Value *Val = nullptr;
2910       if (getValueTypePair(Record, Idx, NextValueNo, Val))
2911         return Error(BitcodeError::InvalidRecord);
2912       I = ResumeInst::Create(Val);
2913       InstructionList.push_back(I);
2914       break;
2915     }
2916     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2917       I = new UnreachableInst(Context);
2918       InstructionList.push_back(I);
2919       break;
2920     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2921       if (Record.size() < 1 || ((Record.size()-1)&1))
2922         return Error(BitcodeError::InvalidRecord);
2923       Type *Ty = getTypeByID(Record[0]);
2924       if (!Ty)
2925         return Error(BitcodeError::InvalidRecord);
2926
2927       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2928       InstructionList.push_back(PN);
2929
2930       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2931         Value *V;
2932         // With the new function encoding, it is possible that operands have
2933         // negative IDs (for forward references).  Use a signed VBR
2934         // representation to keep the encoding small.
2935         if (UseRelativeIDs)
2936           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2937         else
2938           V = getValue(Record, 1+i, NextValueNo, Ty);
2939         BasicBlock *BB = getBasicBlock(Record[2+i]);
2940         if (!V || !BB)
2941           return Error(BitcodeError::InvalidRecord);
2942         PN->addIncoming(V, BB);
2943       }
2944       I = PN;
2945       break;
2946     }
2947
2948     case bitc::FUNC_CODE_INST_LANDINGPAD: {
2949       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2950       unsigned Idx = 0;
2951       if (Record.size() < 4)
2952         return Error(BitcodeError::InvalidRecord);
2953       Type *Ty = getTypeByID(Record[Idx++]);
2954       if (!Ty)
2955         return Error(BitcodeError::InvalidRecord);
2956       Value *PersFn = nullptr;
2957       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2958         return Error(BitcodeError::InvalidRecord);
2959
2960       bool IsCleanup = !!Record[Idx++];
2961       unsigned NumClauses = Record[Idx++];
2962       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2963       LP->setCleanup(IsCleanup);
2964       for (unsigned J = 0; J != NumClauses; ++J) {
2965         LandingPadInst::ClauseType CT =
2966           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2967         Value *Val;
2968
2969         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2970           delete LP;
2971           return Error(BitcodeError::InvalidRecord);
2972         }
2973
2974         assert((CT != LandingPadInst::Catch ||
2975                 !isa<ArrayType>(Val->getType())) &&
2976                "Catch clause has a invalid type!");
2977         assert((CT != LandingPadInst::Filter ||
2978                 isa<ArrayType>(Val->getType())) &&
2979                "Filter clause has invalid type!");
2980         LP->addClause(cast<Constant>(Val));
2981       }
2982
2983       I = LP;
2984       InstructionList.push_back(I);
2985       break;
2986     }
2987
2988     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2989       if (Record.size() != 4)
2990         return Error(BitcodeError::InvalidRecord);
2991       PointerType *Ty =
2992         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2993       Type *OpTy = getTypeByID(Record[1]);
2994       Value *Size = getFnValueByID(Record[2], OpTy);
2995       unsigned AlignRecord = Record[3];
2996       bool InAlloca = AlignRecord & (1 << 5);
2997       unsigned Align = AlignRecord & ((1 << 5) - 1);
2998       if (!Ty || !Size)
2999         return Error(BitcodeError::InvalidRecord);
3000       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3001       AI->setUsedWithInAlloca(InAlloca);
3002       I = AI;
3003       InstructionList.push_back(I);
3004       break;
3005     }
3006     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3007       unsigned OpNum = 0;
3008       Value *Op;
3009       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3010           OpNum+2 != Record.size())
3011         return Error(BitcodeError::InvalidRecord);
3012
3013       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3014       InstructionList.push_back(I);
3015       break;
3016     }
3017     case bitc::FUNC_CODE_INST_LOADATOMIC: {
3018        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
3019       unsigned OpNum = 0;
3020       Value *Op;
3021       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3022           OpNum+4 != Record.size())
3023         return Error(BitcodeError::InvalidRecord);
3024
3025       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3026       if (Ordering == NotAtomic || Ordering == Release ||
3027           Ordering == AcquireRelease)
3028         return Error(BitcodeError::InvalidRecord);
3029       if (Ordering != NotAtomic && Record[OpNum] == 0)
3030         return Error(BitcodeError::InvalidRecord);
3031       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3032
3033       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3034                        Ordering, SynchScope);
3035       InstructionList.push_back(I);
3036       break;
3037     }
3038     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
3039       unsigned OpNum = 0;
3040       Value *Val, *Ptr;
3041       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3042           popValue(Record, OpNum, NextValueNo,
3043                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3044           OpNum+2 != Record.size())
3045         return Error(BitcodeError::InvalidRecord);
3046
3047       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3048       InstructionList.push_back(I);
3049       break;
3050     }
3051     case bitc::FUNC_CODE_INST_STOREATOMIC: {
3052       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
3053       unsigned OpNum = 0;
3054       Value *Val, *Ptr;
3055       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3056           popValue(Record, OpNum, NextValueNo,
3057                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3058           OpNum+4 != Record.size())
3059         return Error(BitcodeError::InvalidRecord);
3060
3061       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3062       if (Ordering == NotAtomic || Ordering == Acquire ||
3063           Ordering == AcquireRelease)
3064         return Error(BitcodeError::InvalidRecord);
3065       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3066       if (Ordering != NotAtomic && Record[OpNum] == 0)
3067         return Error(BitcodeError::InvalidRecord);
3068
3069       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
3070                         Ordering, SynchScope);
3071       InstructionList.push_back(I);
3072       break;
3073     }
3074     case bitc::FUNC_CODE_INST_CMPXCHG: {
3075       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
3076       //          failureordering?, isweak?]
3077       unsigned OpNum = 0;
3078       Value *Ptr, *Cmp, *New;
3079       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3080           popValue(Record, OpNum, NextValueNo,
3081                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
3082           popValue(Record, OpNum, NextValueNo,
3083                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
3084           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3085         return Error(BitcodeError::InvalidRecord);
3086       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
3087       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3088         return Error(BitcodeError::InvalidRecord);
3089       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
3090
3091       AtomicOrdering FailureOrdering;
3092       if (Record.size() < 7)
3093         FailureOrdering =
3094             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
3095       else
3096         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
3097
3098       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
3099                                 SynchScope);
3100       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
3101
3102       if (Record.size() < 8) {
3103         // Before weak cmpxchgs existed, the instruction simply returned the
3104         // value loaded from memory, so bitcode files from that era will be
3105         // expecting the first component of a modern cmpxchg.
3106         CurBB->getInstList().push_back(I);
3107         I = ExtractValueInst::Create(I, 0);
3108       } else {
3109         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
3110       }
3111
3112       InstructionList.push_back(I);
3113       break;
3114     }
3115     case bitc::FUNC_CODE_INST_ATOMICRMW: {
3116       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
3117       unsigned OpNum = 0;
3118       Value *Ptr, *Val;
3119       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3120           popValue(Record, OpNum, NextValueNo,
3121                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3122           OpNum+4 != Record.size())
3123         return Error(BitcodeError::InvalidRecord);
3124       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
3125       if (Operation < AtomicRMWInst::FIRST_BINOP ||
3126           Operation > AtomicRMWInst::LAST_BINOP)
3127         return Error(BitcodeError::InvalidRecord);
3128       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
3129       if (Ordering == NotAtomic || Ordering == Unordered)
3130         return Error(BitcodeError::InvalidRecord);
3131       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
3132       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
3133       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
3134       InstructionList.push_back(I);
3135       break;
3136     }
3137     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
3138       if (2 != Record.size())
3139         return Error(BitcodeError::InvalidRecord);
3140       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
3141       if (Ordering == NotAtomic || Ordering == Unordered ||
3142           Ordering == Monotonic)
3143         return Error(BitcodeError::InvalidRecord);
3144       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
3145       I = new FenceInst(Context, Ordering, SynchScope);
3146       InstructionList.push_back(I);
3147       break;
3148     }
3149     case bitc::FUNC_CODE_INST_CALL: {
3150       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3151       if (Record.size() < 3)
3152         return Error(BitcodeError::InvalidRecord);
3153
3154       AttributeSet PAL = getAttributes(Record[0]);
3155       unsigned CCInfo = Record[1];
3156
3157       unsigned OpNum = 2;
3158       Value *Callee;
3159       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3160         return Error(BitcodeError::InvalidRecord);
3161
3162       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3163       FunctionType *FTy = nullptr;
3164       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3165       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3166         return Error(BitcodeError::InvalidRecord);
3167
3168       SmallVector<Value*, 16> Args;
3169       // Read the fixed params.
3170       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3171         if (FTy->getParamType(i)->isLabelTy())
3172           Args.push_back(getBasicBlock(Record[OpNum]));
3173         else
3174           Args.push_back(getValue(Record, OpNum, NextValueNo,
3175                                   FTy->getParamType(i)));
3176         if (!Args.back())
3177           return Error(BitcodeError::InvalidRecord);
3178       }
3179
3180       // Read type/value pairs for varargs params.
3181       if (!FTy->isVarArg()) {
3182         if (OpNum != Record.size())
3183           return Error(BitcodeError::InvalidRecord);
3184       } else {
3185         while (OpNum != Record.size()) {
3186           Value *Op;
3187           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3188             return Error(BitcodeError::InvalidRecord);
3189           Args.push_back(Op);
3190         }
3191       }
3192
3193       I = CallInst::Create(Callee, Args);
3194       InstructionList.push_back(I);
3195       cast<CallInst>(I)->setCallingConv(
3196           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
3197       CallInst::TailCallKind TCK = CallInst::TCK_None;
3198       if (CCInfo & 1)
3199         TCK = CallInst::TCK_Tail;
3200       if (CCInfo & (1 << 14))
3201         TCK = CallInst::TCK_MustTail;
3202       cast<CallInst>(I)->setTailCallKind(TCK);
3203       cast<CallInst>(I)->setAttributes(PAL);
3204       break;
3205     }
3206     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3207       if (Record.size() < 3)
3208         return Error(BitcodeError::InvalidRecord);
3209       Type *OpTy = getTypeByID(Record[0]);
3210       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
3211       Type *ResTy = getTypeByID(Record[2]);
3212       if (!OpTy || !Op || !ResTy)
3213         return Error(BitcodeError::InvalidRecord);
3214       I = new VAArgInst(Op, ResTy);
3215       InstructionList.push_back(I);
3216       break;
3217     }
3218     }
3219
3220     // Add instruction to end of current BB.  If there is no current BB, reject
3221     // this file.
3222     if (!CurBB) {
3223       delete I;
3224       return Error(BitcodeError::InvalidInstructionWithNoBB);
3225     }
3226     CurBB->getInstList().push_back(I);
3227
3228     // If this was a terminator instruction, move to the next block.
3229     if (isa<TerminatorInst>(I)) {
3230       ++CurBBNo;
3231       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3232     }
3233
3234     // Non-void values get registered in the value table for future use.
3235     if (I && !I->getType()->isVoidTy())
3236       ValueList.AssignValue(I, NextValueNo++);
3237   }
3238
3239 OutOfRecordLoop:
3240
3241   // Check the function list for unresolved values.
3242   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3243     if (!A->getParent()) {
3244       // We found at least one unresolved value.  Nuke them all to avoid leaks.
3245       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3246         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3247           A->replaceAllUsesWith(UndefValue::get(A->getType()));
3248           delete A;
3249         }
3250       }
3251       return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3252     }
3253   }
3254
3255   // FIXME: Check for unresolved forward-declared metadata references
3256   // and clean up leaks.
3257
3258   // Trim the value list down to the size it was before we parsed this function.
3259   ValueList.shrinkTo(ModuleValueListSize);
3260   MDValueList.shrinkTo(ModuleMDValueListSize);
3261   std::vector<BasicBlock*>().swap(FunctionBBs);
3262   return std::error_code();
3263 }
3264
3265 /// Find the function body in the bitcode stream
3266 std::error_code BitcodeReader::FindFunctionInStream(
3267     Function *F,
3268     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
3269   while (DeferredFunctionInfoIterator->second == 0) {
3270     if (Stream.AtEndOfStream())
3271       return Error(BitcodeError::CouldNotFindFunctionInStream);
3272     // ParseModule will parse the next body in the stream and set its
3273     // position in the DeferredFunctionInfo map.
3274     if (std::error_code EC = ParseModule(true))
3275       return EC;
3276   }
3277   return std::error_code();
3278 }
3279
3280 //===----------------------------------------------------------------------===//
3281 // GVMaterializer implementation
3282 //===----------------------------------------------------------------------===//
3283
3284 void BitcodeReader::releaseBuffer() { Buffer.release(); }
3285
3286 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3287   Function *F = dyn_cast<Function>(GV);
3288   // If it's not a function or is already material, ignore the request.
3289   if (!F || !F->isMaterializable())
3290     return std::error_code();
3291
3292   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3293   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3294   // If its position is recorded as 0, its body is somewhere in the stream
3295   // but we haven't seen it yet.
3296   if (DFII->second == 0 && LazyStreamer)
3297     if (std::error_code EC = FindFunctionInStream(F, DFII))
3298       return EC;
3299
3300   // Move the bit stream to the saved position of the deferred function body.
3301   Stream.JumpToBit(DFII->second);
3302
3303   if (std::error_code EC = ParseFunctionBody(F))
3304     return EC;
3305   F->setIsMaterializable(false);
3306
3307   // Upgrade any old intrinsic calls in the function.
3308   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3309        E = UpgradedIntrinsics.end(); I != E; ++I) {
3310     if (I->first != I->second) {
3311       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3312            UI != UE;) {
3313         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3314           UpgradeIntrinsicCall(CI, I->second);
3315       }
3316     }
3317   }
3318
3319   // Bring in any functions that this function forward-referenced via
3320   // blockaddresses.
3321   return materializeForwardReferencedFunctions();
3322 }
3323
3324 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3325   const Function *F = dyn_cast<Function>(GV);
3326   if (!F || F->isDeclaration())
3327     return false;
3328
3329   // Dematerializing F would leave dangling references that wouldn't be
3330   // reconnected on re-materialization.
3331   if (BlockAddressesTaken.count(F))
3332     return false;
3333
3334   return DeferredFunctionInfo.count(const_cast<Function*>(F));
3335 }
3336
3337 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3338   Function *F = dyn_cast<Function>(GV);
3339   // If this function isn't dematerializable, this is a noop.
3340   if (!F || !isDematerializable(F))
3341     return;
3342
3343   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3344
3345   // Just forget the function body, we can remat it later.
3346   F->dropAllReferences();
3347   F->setIsMaterializable(true);
3348 }
3349
3350 std::error_code BitcodeReader::MaterializeModule(Module *M) {
3351   assert(M == TheModule &&
3352          "Can only Materialize the Module this BitcodeReader is attached to.");
3353
3354   // Promise to materialize all forward references.
3355   WillMaterializeAllForwardRefs = true;
3356
3357   // Iterate over the module, deserializing any functions that are still on
3358   // disk.
3359   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3360        F != E; ++F) {
3361     if (std::error_code EC = materialize(F))
3362       return EC;
3363   }
3364   // At this point, if there are any function bodies, the current bit is
3365   // pointing to the END_BLOCK record after them. Now make sure the rest
3366   // of the bits in the module have been read.
3367   if (NextUnreadBit)
3368     ParseModule(true);
3369
3370   // Check that all block address forward references got resolved (as we
3371   // promised above).
3372   if (!BasicBlockFwdRefs.empty())
3373     return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3374
3375   // Upgrade any intrinsic calls that slipped through (should not happen!) and
3376   // delete the old functions to clean up. We can't do this unless the entire
3377   // module is materialized because there could always be another function body
3378   // with calls to the old function.
3379   for (std::vector<std::pair<Function*, Function*> >::iterator I =
3380        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3381     if (I->first != I->second) {
3382       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3383            UI != UE;) {
3384         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3385           UpgradeIntrinsicCall(CI, I->second);
3386       }
3387       if (!I->first->use_empty())
3388         I->first->replaceAllUsesWith(I->second);
3389       I->first->eraseFromParent();
3390     }
3391   }
3392   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3393
3394   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3395     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3396
3397   UpgradeDebugInfo(*M);
3398   return std::error_code();
3399 }
3400
3401 std::error_code BitcodeReader::InitStream() {
3402   if (LazyStreamer)
3403     return InitLazyStream();
3404   return InitStreamFromBuffer();
3405 }
3406
3407 std::error_code BitcodeReader::InitStreamFromBuffer() {
3408   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3409   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3410
3411   if (Buffer->getBufferSize() & 3)
3412     return Error(BitcodeError::InvalidBitcodeSignature);
3413
3414   // If we have a wrapper header, parse it and ignore the non-bc file contents.
3415   // The magic number is 0x0B17C0DE stored in little endian.
3416   if (isBitcodeWrapper(BufPtr, BufEnd))
3417     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3418       return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3419
3420   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3421   Stream.init(&*StreamFile);
3422
3423   return std::error_code();
3424 }
3425
3426 std::error_code BitcodeReader::InitLazyStream() {
3427   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3428   // see it.
3429   StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3430   StreamFile.reset(new BitstreamReader(Bytes));
3431   Stream.init(&*StreamFile);
3432
3433   unsigned char buf[16];
3434   if (Bytes->readBytes(buf, 16, 0) != 16)
3435     return Error(BitcodeError::InvalidBitcodeSignature);
3436
3437   if (!isBitcode(buf, buf + 16))
3438     return Error(BitcodeError::InvalidBitcodeSignature);
3439
3440   if (isBitcodeWrapper(buf, buf + 4)) {
3441     const unsigned char *bitcodeStart = buf;
3442     const unsigned char *bitcodeEnd = buf + 16;
3443     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3444     Bytes->dropLeadingBytes(bitcodeStart - buf);
3445     Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3446   }
3447   return std::error_code();
3448 }
3449
3450 namespace {
3451 class BitcodeErrorCategoryType : public std::error_category {
3452   const char *name() const LLVM_NOEXCEPT override {
3453     return "llvm.bitcode";
3454   }
3455   std::string message(int IE) const override {
3456     BitcodeError E = static_cast<BitcodeError>(IE);
3457     switch (E) {
3458     case BitcodeError::ConflictingMETADATA_KINDRecords:
3459       return "Conflicting METADATA_KIND records";
3460     case BitcodeError::CouldNotFindFunctionInStream:
3461       return "Could not find function in stream";
3462     case BitcodeError::ExpectedConstant:
3463       return "Expected a constant";
3464     case BitcodeError::InsufficientFunctionProtos:
3465       return "Insufficient function protos";
3466     case BitcodeError::InvalidBitcodeSignature:
3467       return "Invalid bitcode signature";
3468     case BitcodeError::InvalidBitcodeWrapperHeader:
3469       return "Invalid bitcode wrapper header";
3470     case BitcodeError::InvalidConstantReference:
3471       return "Invalid ronstant reference";
3472     case BitcodeError::InvalidID:
3473       return "Invalid ID";
3474     case BitcodeError::InvalidInstructionWithNoBB:
3475       return "Invalid instruction with no BB";
3476     case BitcodeError::InvalidRecord:
3477       return "Invalid record";
3478     case BitcodeError::InvalidTypeForValue:
3479       return "Invalid type for value";
3480     case BitcodeError::InvalidTYPETable:
3481       return "Invalid TYPE table";
3482     case BitcodeError::InvalidType:
3483       return "Invalid type";
3484     case BitcodeError::MalformedBlock:
3485       return "Malformed block";
3486     case BitcodeError::MalformedGlobalInitializerSet:
3487       return "Malformed global initializer set";
3488     case BitcodeError::InvalidMultipleBlocks:
3489       return "Invalid multiple blocks";
3490     case BitcodeError::NeverResolvedValueFoundInFunction:
3491       return "Never resolved value found in function";
3492     case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3493       return "Never resolved function from blockaddress";
3494     case BitcodeError::InvalidValue:
3495       return "Invalid value";
3496     }
3497     llvm_unreachable("Unknown error type!");
3498   }
3499 };
3500 }
3501
3502 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3503
3504 const std::error_category &llvm::BitcodeErrorCategory() {
3505   return *ErrorCategory;
3506 }
3507
3508 //===----------------------------------------------------------------------===//
3509 // External interface
3510 //===----------------------------------------------------------------------===//
3511
3512 /// \brief Get a lazy one-at-time loading module from bitcode.
3513 ///
3514 /// This isn't always used in a lazy context.  In particular, it's also used by
3515 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
3516 /// in forward-referenced functions from block address references.
3517 ///
3518 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
3519 /// materialize everything -- in particular, if this isn't truly lazy.
3520 static ErrorOr<Module *>
3521 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3522                          LLVMContext &Context, bool WillMaterializeAll) {
3523   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3524   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3525   M->setMaterializer(R);
3526
3527   auto cleanupOnError = [&](std::error_code EC) {
3528     R->releaseBuffer(); // Never take ownership on error.
3529     delete M;  // Also deletes R.
3530     return EC;
3531   };
3532
3533   if (std::error_code EC = R->ParseBitcodeInto(M))
3534     return cleanupOnError(EC);
3535
3536   if (!WillMaterializeAll)
3537     // Resolve forward references from blockaddresses.
3538     if (std::error_code EC = R->materializeForwardReferencedFunctions())
3539       return cleanupOnError(EC);
3540
3541   Buffer.release(); // The BitcodeReader owns it now.
3542   return M;
3543 }
3544
3545 ErrorOr<Module *>
3546 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3547                            LLVMContext &Context) {
3548   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3549 }
3550
3551 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3552                                        DataStreamer *streamer,
3553                                        LLVMContext &Context,
3554                                        std::string *ErrMsg) {
3555   Module *M = new Module(name, Context);
3556   BitcodeReader *R = new BitcodeReader(streamer, Context);
3557   M->setMaterializer(R);
3558   if (std::error_code EC = R->ParseBitcodeInto(M)) {
3559     if (ErrMsg)
3560       *ErrMsg = EC.message();
3561     delete M;  // Also deletes R.
3562     return nullptr;
3563   }
3564   return M;
3565 }
3566
3567 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3568                                          LLVMContext &Context) {
3569   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3570   ErrorOr<Module *> ModuleOrErr =
3571       getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3572   if (!ModuleOrErr)
3573     return ModuleOrErr;
3574   Module *M = ModuleOrErr.get();
3575   // Read in the entire module, and destroy the BitcodeReader.
3576   if (std::error_code EC = M->materializeAllPermanently()) {
3577     delete M;
3578     return EC;
3579   }
3580
3581   // TODO: Restore the use-lists to the in-memory state when the bitcode was
3582   // written.  We must defer until the Module has been fully materialized.
3583
3584   return M;
3585 }
3586
3587 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3588                                          LLVMContext &Context) {
3589   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3590   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
3591   ErrorOr<std::string> Triple = R->parseTriple();
3592   if (Triple.getError())
3593     return "";
3594   return Triple.get();
3595 }