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