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