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