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