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