DI: Require subprogram definitions to be distinct
[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 "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/DataStream.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <deque>
37 using namespace llvm;
38
39 namespace {
40 enum {
41   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
42 };
43
44 /// Indicates which operator an operand allows (for the few operands that may
45 /// only reference a certain operator).
46 enum OperatorConstraint {
47   OC_None = 0,  // No constraint
48   OC_CatchPad,  // Must be CatchPadInst
49   OC_CleanupPad // Must be CleanupPadInst
50 };
51
52 class BitcodeReaderValueList {
53   std::vector<WeakVH> ValuePtrs;
54
55   /// As we resolve forward-referenced constants, we add information about them
56   /// to this vector.  This allows us to resolve them in bulk instead of
57   /// resolving each reference at a time.  See the code in
58   /// ResolveConstantForwardRefs for more information about this.
59   ///
60   /// The key of this vector is the placeholder constant, the value is the slot
61   /// number that holds the resolved value.
62   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
63   ResolveConstantsTy ResolveConstants;
64   LLVMContext &Context;
65 public:
66   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
67   ~BitcodeReaderValueList() {
68     assert(ResolveConstants.empty() && "Constants not resolved?");
69   }
70
71   // vector compatibility methods
72   unsigned size() const { return ValuePtrs.size(); }
73   void resize(unsigned N) { ValuePtrs.resize(N); }
74   void push_back(Value *V) { ValuePtrs.emplace_back(V); }
75
76   void clear() {
77     assert(ResolveConstants.empty() && "Constants not resolved?");
78     ValuePtrs.clear();
79   }
80
81   Value *operator[](unsigned i) const {
82     assert(i < ValuePtrs.size());
83     return ValuePtrs[i];
84   }
85
86   Value *back() const { return ValuePtrs.back(); }
87     void pop_back() { ValuePtrs.pop_back(); }
88   bool empty() const { return ValuePtrs.empty(); }
89   void shrinkTo(unsigned N) {
90     assert(N <= size() && "Invalid shrinkTo request!");
91     ValuePtrs.resize(N);
92   }
93
94   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
95   Value *getValueFwdRef(unsigned Idx, Type *Ty,
96                         OperatorConstraint OC = OC_None);
97
98   bool assignValue(Value *V, unsigned Idx);
99
100   /// Once all constants are read, this method bulk resolves any forward
101   /// references.
102   void resolveConstantForwardRefs();
103 };
104
105 class BitcodeReaderMDValueList {
106   unsigned NumFwdRefs;
107   bool AnyFwdRefs;
108   unsigned MinFwdRef;
109   unsigned MaxFwdRef;
110   std::vector<TrackingMDRef> MDValuePtrs;
111
112   LLVMContext &Context;
113 public:
114   BitcodeReaderMDValueList(LLVMContext &C)
115       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
116
117   // vector compatibility methods
118   unsigned size() const       { return MDValuePtrs.size(); }
119   void resize(unsigned N)     { MDValuePtrs.resize(N); }
120   void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
121   void clear()                { MDValuePtrs.clear();  }
122   Metadata *back() const      { return MDValuePtrs.back(); }
123   void pop_back()             { MDValuePtrs.pop_back(); }
124   bool empty() const          { return MDValuePtrs.empty(); }
125
126   Metadata *operator[](unsigned i) const {
127     assert(i < MDValuePtrs.size());
128     return MDValuePtrs[i];
129   }
130
131   void shrinkTo(unsigned N) {
132     assert(N <= size() && "Invalid shrinkTo request!");
133     MDValuePtrs.resize(N);
134   }
135
136   Metadata *getValueFwdRef(unsigned Idx);
137   void assignValue(Metadata *MD, unsigned Idx);
138   void tryToResolveCycles();
139 };
140
141 class BitcodeReader : public GVMaterializer {
142   LLVMContext &Context;
143   DiagnosticHandlerFunction DiagnosticHandler;
144   Module *TheModule = nullptr;
145   std::unique_ptr<MemoryBuffer> Buffer;
146   std::unique_ptr<BitstreamReader> StreamFile;
147   BitstreamCursor Stream;
148   uint64_t NextUnreadBit = 0;
149   bool SeenValueSymbolTable = false;
150
151   std::vector<Type*> TypeList;
152   BitcodeReaderValueList ValueList;
153   BitcodeReaderMDValueList MDValueList;
154   std::vector<Comdat *> ComdatList;
155   SmallVector<Instruction *, 64> InstructionList;
156
157   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
158   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
159   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
160   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
161   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
162
163   SmallVector<Instruction*, 64> InstsWithTBAATag;
164
165   /// The set of attributes by index.  Index zero in the file is for null, and
166   /// is thus not represented here.  As such all indices are off by one.
167   std::vector<AttributeSet> MAttributes;
168
169   /// \brief The set of attribute groups.
170   std::map<unsigned, AttributeSet> MAttributeGroups;
171
172   /// While parsing a function body, this is a list of the basic blocks for the
173   /// function.
174   std::vector<BasicBlock*> FunctionBBs;
175
176   // When reading the module header, this list is populated with functions that
177   // have bodies later in the file.
178   std::vector<Function*> FunctionsWithBodies;
179
180   // When intrinsic functions are encountered which require upgrading they are
181   // stored here with their replacement function.
182   typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
183   UpgradedIntrinsicMap UpgradedIntrinsics;
184
185   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
186   DenseMap<unsigned, unsigned> MDKindMap;
187
188   // Several operations happen after the module header has been read, but
189   // before function bodies are processed. This keeps track of whether
190   // we've done this yet.
191   bool SeenFirstFunctionBody = false;
192
193   /// When function bodies are initially scanned, this map contains info about
194   /// where to find deferred function body in the stream.
195   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
196
197   /// When Metadata block is initially scanned when parsing the module, we may
198   /// choose to defer parsing of the metadata. This vector contains info about
199   /// which Metadata blocks are deferred.
200   std::vector<uint64_t> DeferredMetadataInfo;
201
202   /// These are basic blocks forward-referenced by block addresses.  They are
203   /// inserted lazily into functions when they're loaded.  The basic block ID is
204   /// its index into the vector.
205   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
206   std::deque<Function *> BasicBlockFwdRefQueue;
207
208   /// Indicates that we are using a new encoding for instruction operands where
209   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
210   /// instruction number, for a more compact encoding.  Some instruction
211   /// operands are not relative to the instruction ID: basic block numbers, and
212   /// types. Once the old style function blocks have been phased out, we would
213   /// not need this flag.
214   bool UseRelativeIDs = false;
215
216   /// True if all functions will be materialized, negating the need to process
217   /// (e.g.) blockaddress forward references.
218   bool WillMaterializeAllForwardRefs = false;
219
220   /// Functions that have block addresses taken.  This is usually empty.
221   SmallPtrSet<const Function *, 4> BlockAddressesTaken;
222
223   /// True if any Metadata block has been materialized.
224   bool IsMetadataMaterialized = false;
225
226   bool StripDebugInfo = false;
227
228 public:
229   std::error_code error(BitcodeError E, const Twine &Message);
230   std::error_code error(BitcodeError E);
231   std::error_code error(const Twine &Message);
232
233   BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
234                 DiagnosticHandlerFunction DiagnosticHandler);
235   BitcodeReader(LLVMContext &Context,
236                 DiagnosticHandlerFunction DiagnosticHandler);
237   ~BitcodeReader() override { freeState(); }
238
239   std::error_code materializeForwardReferencedFunctions();
240
241   void freeState();
242
243   void releaseBuffer();
244
245   bool isDematerializable(const GlobalValue *GV) const override;
246   std::error_code materialize(GlobalValue *GV) override;
247   std::error_code materializeModule(Module *M) override;
248   std::vector<StructType *> getIdentifiedStructTypes() const override;
249   void dematerialize(GlobalValue *GV) override;
250
251   /// \brief Main interface to parsing a bitcode buffer.
252   /// \returns true if an error occurred.
253   std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
254                                    Module *M,
255                                    bool ShouldLazyLoadMetadata = false);
256
257   /// \brief Cheap mechanism to just extract module triple
258   /// \returns true if an error occurred.
259   ErrorOr<std::string> parseTriple();
260
261   static uint64_t decodeSignRotatedValue(uint64_t V);
262
263   /// Materialize any deferred Metadata block.
264   std::error_code materializeMetadata() override;
265
266   void setStripDebugInfo() override;
267
268 private:
269   std::vector<StructType *> IdentifiedStructTypes;
270   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
271   StructType *createIdentifiedStructType(LLVMContext &Context);
272
273   Type *getTypeByID(unsigned ID);
274   Value *getFnValueByID(unsigned ID, Type *Ty,
275                         OperatorConstraint OC = OC_None) {
276     if (Ty && Ty->isMetadataTy())
277       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
278     return ValueList.getValueFwdRef(ID, Ty, OC);
279   }
280   Metadata *getFnMetadataByID(unsigned ID) {
281     return MDValueList.getValueFwdRef(ID);
282   }
283   BasicBlock *getBasicBlock(unsigned ID) const {
284     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
285     return FunctionBBs[ID];
286   }
287   AttributeSet getAttributes(unsigned i) const {
288     if (i-1 < MAttributes.size())
289       return MAttributes[i-1];
290     return AttributeSet();
291   }
292
293   /// Read a value/type pair out of the specified record from slot 'Slot'.
294   /// Increment Slot past the number of slots used in the record. Return true on
295   /// failure.
296   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
297                         unsigned InstNum, Value *&ResVal) {
298     if (Slot == Record.size()) return true;
299     unsigned ValNo = (unsigned)Record[Slot++];
300     // Adjust the ValNo, if it was encoded relative to the InstNum.
301     if (UseRelativeIDs)
302       ValNo = InstNum - ValNo;
303     if (ValNo < InstNum) {
304       // If this is not a forward reference, just return the value we already
305       // have.
306       ResVal = getFnValueByID(ValNo, nullptr);
307       return ResVal == nullptr;
308     }
309     if (Slot == Record.size())
310       return true;
311
312     unsigned TypeNo = (unsigned)Record[Slot++];
313     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
314     return ResVal == nullptr;
315   }
316
317   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
318   /// past the number of slots used by the value in the record. Return true if
319   /// there is an error.
320   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
321                 unsigned InstNum, Type *Ty, Value *&ResVal,
322                 OperatorConstraint OC = OC_None) {
323     if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
324       return true;
325     // All values currently take a single record slot.
326     ++Slot;
327     return false;
328   }
329
330   /// Like popValue, but does not increment the Slot number.
331   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
332                 unsigned InstNum, Type *Ty, Value *&ResVal,
333                 OperatorConstraint OC = OC_None) {
334     ResVal = getValue(Record, Slot, InstNum, Ty, OC);
335     return ResVal == nullptr;
336   }
337
338   /// Version of getValue that returns ResVal directly, or 0 if there is an
339   /// error.
340   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
341                   unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
342     if (Slot == Record.size()) return nullptr;
343     unsigned ValNo = (unsigned)Record[Slot];
344     // Adjust the ValNo, if it was encoded relative to the InstNum.
345     if (UseRelativeIDs)
346       ValNo = InstNum - ValNo;
347     return getFnValueByID(ValNo, Ty, OC);
348   }
349
350   /// Like getValue, but decodes signed VBRs.
351   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
352                         unsigned InstNum, Type *Ty,
353                         OperatorConstraint OC = OC_None) {
354     if (Slot == Record.size()) return nullptr;
355     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
356     // Adjust the ValNo, if it was encoded relative to the InstNum.
357     if (UseRelativeIDs)
358       ValNo = InstNum - ValNo;
359     return getFnValueByID(ValNo, Ty, OC);
360   }
361
362   /// Converts alignment exponent (i.e. power of two (or zero)) to the
363   /// corresponding alignment to use. If alignment is too large, returns
364   /// a corresponding error code.
365   std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
366   std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
367   std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
368   std::error_code parseAttributeBlock();
369   std::error_code parseAttributeGroupBlock();
370   std::error_code parseTypeTable();
371   std::error_code parseTypeTableBody();
372
373   std::error_code parseValueSymbolTable();
374   std::error_code parseConstants();
375   std::error_code rememberAndSkipFunctionBody();
376   /// Save the positions of the Metadata blocks and skip parsing the blocks.
377   std::error_code rememberAndSkipMetadata();
378   std::error_code parseFunctionBody(Function *F);
379   std::error_code globalCleanup();
380   std::error_code resolveGlobalAndAliasInits();
381   std::error_code parseMetadata();
382   std::error_code parseMetadataAttachment(Function &F);
383   ErrorOr<std::string> parseModuleTriple();
384   std::error_code parseUseLists();
385   std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
386   std::error_code initStreamFromBuffer();
387   std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
388   std::error_code findFunctionInStream(
389       Function *F,
390       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
391 };
392 } // namespace
393
394 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
395                                              DiagnosticSeverity Severity,
396                                              const Twine &Msg)
397     : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
398
399 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
400
401 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
402                              std::error_code EC, const Twine &Message) {
403   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
404   DiagnosticHandler(DI);
405   return EC;
406 }
407
408 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
409                              std::error_code EC) {
410   return error(DiagnosticHandler, EC, EC.message());
411 }
412
413 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
414                              const Twine &Message) {
415   return error(DiagnosticHandler,
416                make_error_code(BitcodeError::CorruptedBitcode), Message);
417 }
418
419 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
420   return ::error(DiagnosticHandler, make_error_code(E), Message);
421 }
422
423 std::error_code BitcodeReader::error(const Twine &Message) {
424   return ::error(DiagnosticHandler,
425                  make_error_code(BitcodeError::CorruptedBitcode), Message);
426 }
427
428 std::error_code BitcodeReader::error(BitcodeError E) {
429   return ::error(DiagnosticHandler, make_error_code(E));
430 }
431
432 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
433                                                 LLVMContext &C) {
434   if (F)
435     return F;
436   return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
437 }
438
439 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
440                              DiagnosticHandlerFunction DiagnosticHandler)
441     : Context(Context),
442       DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
443       Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
444
445 BitcodeReader::BitcodeReader(LLVMContext &Context,
446                              DiagnosticHandlerFunction DiagnosticHandler)
447     : Context(Context),
448       DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
449       Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
450
451 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
452   if (WillMaterializeAllForwardRefs)
453     return std::error_code();
454
455   // Prevent recursion.
456   WillMaterializeAllForwardRefs = true;
457
458   while (!BasicBlockFwdRefQueue.empty()) {
459     Function *F = BasicBlockFwdRefQueue.front();
460     BasicBlockFwdRefQueue.pop_front();
461     assert(F && "Expected valid function");
462     if (!BasicBlockFwdRefs.count(F))
463       // Already materialized.
464       continue;
465
466     // Check for a function that isn't materializable to prevent an infinite
467     // loop.  When parsing a blockaddress stored in a global variable, there
468     // isn't a trivial way to check if a function will have a body without a
469     // linear search through FunctionsWithBodies, so just check it here.
470     if (!F->isMaterializable())
471       return error("Never resolved function from blockaddress");
472
473     // Try to materialize F.
474     if (std::error_code EC = materialize(F))
475       return EC;
476   }
477   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
478
479   // Reset state.
480   WillMaterializeAllForwardRefs = false;
481   return std::error_code();
482 }
483
484 void BitcodeReader::freeState() {
485   Buffer = nullptr;
486   std::vector<Type*>().swap(TypeList);
487   ValueList.clear();
488   MDValueList.clear();
489   std::vector<Comdat *>().swap(ComdatList);
490
491   std::vector<AttributeSet>().swap(MAttributes);
492   std::vector<BasicBlock*>().swap(FunctionBBs);
493   std::vector<Function*>().swap(FunctionsWithBodies);
494   DeferredFunctionInfo.clear();
495   DeferredMetadataInfo.clear();
496   MDKindMap.clear();
497
498   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
499   BasicBlockFwdRefQueue.clear();
500 }
501
502 //===----------------------------------------------------------------------===//
503 //  Helper functions to implement forward reference resolution, etc.
504 //===----------------------------------------------------------------------===//
505
506 /// Convert a string from a record into an std::string, return true on failure.
507 template <typename StrTy>
508 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
509                             StrTy &Result) {
510   if (Idx > Record.size())
511     return true;
512
513   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
514     Result += (char)Record[i];
515   return false;
516 }
517
518 static bool hasImplicitComdat(size_t Val) {
519   switch (Val) {
520   default:
521     return false;
522   case 1:  // Old WeakAnyLinkage
523   case 4:  // Old LinkOnceAnyLinkage
524   case 10: // Old WeakODRLinkage
525   case 11: // Old LinkOnceODRLinkage
526     return true;
527   }
528 }
529
530 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
531   switch (Val) {
532   default: // Map unknown/new linkages to external
533   case 0:
534     return GlobalValue::ExternalLinkage;
535   case 2:
536     return GlobalValue::AppendingLinkage;
537   case 3:
538     return GlobalValue::InternalLinkage;
539   case 5:
540     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
541   case 6:
542     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
543   case 7:
544     return GlobalValue::ExternalWeakLinkage;
545   case 8:
546     return GlobalValue::CommonLinkage;
547   case 9:
548     return GlobalValue::PrivateLinkage;
549   case 12:
550     return GlobalValue::AvailableExternallyLinkage;
551   case 13:
552     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
553   case 14:
554     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
555   case 15:
556     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
557   case 1: // Old value with implicit comdat.
558   case 16:
559     return GlobalValue::WeakAnyLinkage;
560   case 10: // Old value with implicit comdat.
561   case 17:
562     return GlobalValue::WeakODRLinkage;
563   case 4: // Old value with implicit comdat.
564   case 18:
565     return GlobalValue::LinkOnceAnyLinkage;
566   case 11: // Old value with implicit comdat.
567   case 19:
568     return GlobalValue::LinkOnceODRLinkage;
569   }
570 }
571
572 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
573   switch (Val) {
574   default: // Map unknown visibilities to default.
575   case 0: return GlobalValue::DefaultVisibility;
576   case 1: return GlobalValue::HiddenVisibility;
577   case 2: return GlobalValue::ProtectedVisibility;
578   }
579 }
580
581 static GlobalValue::DLLStorageClassTypes
582 getDecodedDLLStorageClass(unsigned Val) {
583   switch (Val) {
584   default: // Map unknown values to default.
585   case 0: return GlobalValue::DefaultStorageClass;
586   case 1: return GlobalValue::DLLImportStorageClass;
587   case 2: return GlobalValue::DLLExportStorageClass;
588   }
589 }
590
591 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
592   switch (Val) {
593     case 0: return GlobalVariable::NotThreadLocal;
594     default: // Map unknown non-zero value to general dynamic.
595     case 1: return GlobalVariable::GeneralDynamicTLSModel;
596     case 2: return GlobalVariable::LocalDynamicTLSModel;
597     case 3: return GlobalVariable::InitialExecTLSModel;
598     case 4: return GlobalVariable::LocalExecTLSModel;
599   }
600 }
601
602 static int getDecodedCastOpcode(unsigned Val) {
603   switch (Val) {
604   default: return -1;
605   case bitc::CAST_TRUNC   : return Instruction::Trunc;
606   case bitc::CAST_ZEXT    : return Instruction::ZExt;
607   case bitc::CAST_SEXT    : return Instruction::SExt;
608   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
609   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
610   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
611   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
612   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
613   case bitc::CAST_FPEXT   : return Instruction::FPExt;
614   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
615   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
616   case bitc::CAST_BITCAST : return Instruction::BitCast;
617   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
618   }
619 }
620
621 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
622   bool IsFP = Ty->isFPOrFPVectorTy();
623   // BinOps are only valid for int/fp or vector of int/fp types
624   if (!IsFP && !Ty->isIntOrIntVectorTy())
625     return -1;
626
627   switch (Val) {
628   default:
629     return -1;
630   case bitc::BINOP_ADD:
631     return IsFP ? Instruction::FAdd : Instruction::Add;
632   case bitc::BINOP_SUB:
633     return IsFP ? Instruction::FSub : Instruction::Sub;
634   case bitc::BINOP_MUL:
635     return IsFP ? Instruction::FMul : Instruction::Mul;
636   case bitc::BINOP_UDIV:
637     return IsFP ? -1 : Instruction::UDiv;
638   case bitc::BINOP_SDIV:
639     return IsFP ? Instruction::FDiv : Instruction::SDiv;
640   case bitc::BINOP_UREM:
641     return IsFP ? -1 : Instruction::URem;
642   case bitc::BINOP_SREM:
643     return IsFP ? Instruction::FRem : Instruction::SRem;
644   case bitc::BINOP_SHL:
645     return IsFP ? -1 : Instruction::Shl;
646   case bitc::BINOP_LSHR:
647     return IsFP ? -1 : Instruction::LShr;
648   case bitc::BINOP_ASHR:
649     return IsFP ? -1 : Instruction::AShr;
650   case bitc::BINOP_AND:
651     return IsFP ? -1 : Instruction::And;
652   case bitc::BINOP_OR:
653     return IsFP ? -1 : Instruction::Or;
654   case bitc::BINOP_XOR:
655     return IsFP ? -1 : Instruction::Xor;
656   }
657 }
658
659 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
660   switch (Val) {
661   default: return AtomicRMWInst::BAD_BINOP;
662   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
663   case bitc::RMW_ADD: return AtomicRMWInst::Add;
664   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
665   case bitc::RMW_AND: return AtomicRMWInst::And;
666   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
667   case bitc::RMW_OR: return AtomicRMWInst::Or;
668   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
669   case bitc::RMW_MAX: return AtomicRMWInst::Max;
670   case bitc::RMW_MIN: return AtomicRMWInst::Min;
671   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
672   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
673   }
674 }
675
676 static AtomicOrdering getDecodedOrdering(unsigned Val) {
677   switch (Val) {
678   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
679   case bitc::ORDERING_UNORDERED: return Unordered;
680   case bitc::ORDERING_MONOTONIC: return Monotonic;
681   case bitc::ORDERING_ACQUIRE: return Acquire;
682   case bitc::ORDERING_RELEASE: return Release;
683   case bitc::ORDERING_ACQREL: return AcquireRelease;
684   default: // Map unknown orderings to sequentially-consistent.
685   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
686   }
687 }
688
689 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
690   switch (Val) {
691   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
692   default: // Map unknown scopes to cross-thread.
693   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
694   }
695 }
696
697 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
698   switch (Val) {
699   default: // Map unknown selection kinds to any.
700   case bitc::COMDAT_SELECTION_KIND_ANY:
701     return Comdat::Any;
702   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
703     return Comdat::ExactMatch;
704   case bitc::COMDAT_SELECTION_KIND_LARGEST:
705     return Comdat::Largest;
706   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
707     return Comdat::NoDuplicates;
708   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
709     return Comdat::SameSize;
710   }
711 }
712
713 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
714   FastMathFlags FMF;
715   if (0 != (Val & FastMathFlags::UnsafeAlgebra))
716     FMF.setUnsafeAlgebra();
717   if (0 != (Val & FastMathFlags::NoNaNs))
718     FMF.setNoNaNs();
719   if (0 != (Val & FastMathFlags::NoInfs))
720     FMF.setNoInfs();
721   if (0 != (Val & FastMathFlags::NoSignedZeros))
722     FMF.setNoSignedZeros();
723   if (0 != (Val & FastMathFlags::AllowReciprocal))
724     FMF.setAllowReciprocal();
725   return FMF;
726 }
727
728 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
729   switch (Val) {
730   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
731   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
732   }
733 }
734
735 namespace llvm {
736 namespace {
737 /// \brief A class for maintaining the slot number definition
738 /// as a placeholder for the actual definition for forward constants defs.
739 class ConstantPlaceHolder : public ConstantExpr {
740   void operator=(const ConstantPlaceHolder &) = delete;
741
742 public:
743   // allocate space for exactly one operand
744   void *operator new(size_t s) { return User::operator new(s, 1); }
745   explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
746       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
747     Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
748   }
749
750   /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
751   static bool classof(const Value *V) {
752     return isa<ConstantExpr>(V) &&
753            cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
754   }
755
756   /// Provide fast operand accessors
757   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
758 };
759 }
760
761 // FIXME: can we inherit this from ConstantExpr?
762 template <>
763 struct OperandTraits<ConstantPlaceHolder> :
764   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
765 };
766 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
767 }
768
769 bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
770   if (Idx == size()) {
771     push_back(V);
772     return false;
773   }
774
775   if (Idx >= size())
776     resize(Idx+1);
777
778   WeakVH &OldV = ValuePtrs[Idx];
779   if (!OldV) {
780     OldV = V;
781     return false;
782   }
783
784   // Handle constants and non-constants (e.g. instrs) differently for
785   // efficiency.
786   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
787     ResolveConstants.push_back(std::make_pair(PHC, Idx));
788     OldV = V;
789   } else {
790     // If there was a forward reference to this value, replace it.
791     Value *PrevVal = OldV;
792     // Check operator constraints.  We only put cleanuppads or catchpads in
793     // the forward value map if the value is constrained to match.
794     if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
795       if (!isa<CatchPadInst>(V))
796         return true;
797       // Delete the dummy basic block that was created with the sentinel
798       // catchpad.
799       BasicBlock *DummyBlock = CatchPad->getUnwindDest();
800       assert(DummyBlock == CatchPad->getNormalDest());
801       CatchPad->dropAllReferences();
802       delete DummyBlock;
803     } else if (isa<CleanupPadInst>(PrevVal)) {
804       if (!isa<CleanupPadInst>(V))
805         return true;
806     }
807     OldV->replaceAllUsesWith(V);
808     delete PrevVal;
809   }
810
811   return false;
812 }
813
814
815 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
816                                                     Type *Ty) {
817   if (Idx >= size())
818     resize(Idx + 1);
819
820   if (Value *V = ValuePtrs[Idx]) {
821     if (Ty != V->getType())
822       report_fatal_error("Type mismatch in constant table!");
823     return cast<Constant>(V);
824   }
825
826   // Create and return a placeholder, which will later be RAUW'd.
827   Constant *C = new ConstantPlaceHolder(Ty, Context);
828   ValuePtrs[Idx] = C;
829   return C;
830 }
831
832 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
833                                               OperatorConstraint OC) {
834   // Bail out for a clearly invalid value. This would make us call resize(0)
835   if (Idx == UINT_MAX)
836     return nullptr;
837
838   if (Idx >= size())
839     resize(Idx + 1);
840
841   if (Value *V = ValuePtrs[Idx]) {
842     // If the types don't match, it's invalid.
843     if (Ty && Ty != V->getType())
844       return nullptr;
845     if (!OC)
846       return V;
847     // Use dyn_cast to enforce operator constraints
848     switch (OC) {
849     case OC_CatchPad:
850       return dyn_cast<CatchPadInst>(V);
851     case OC_CleanupPad:
852       return dyn_cast<CleanupPadInst>(V);
853     default:
854       llvm_unreachable("Unexpected operator constraint");
855     }
856   }
857
858   // No type specified, must be invalid reference.
859   if (!Ty) return nullptr;
860
861   // Create and return a placeholder, which will later be RAUW'd.
862   Value *V;
863   switch (OC) {
864   case OC_None:
865     V = new Argument(Ty);
866     break;
867   case OC_CatchPad: {
868     BasicBlock *BB = BasicBlock::Create(Context);
869     V = CatchPadInst::Create(BB, BB, {});
870     break;
871   }
872   default:
873     assert(OC == OC_CleanupPad && "unexpected operator constraint");
874     V = CleanupPadInst::Create(Context, {});
875     break;
876   }
877
878   ValuePtrs[Idx] = V;
879   return V;
880 }
881
882 /// Once all constants are read, this method bulk resolves any forward
883 /// references.  The idea behind this is that we sometimes get constants (such
884 /// as large arrays) which reference *many* forward ref constants.  Replacing
885 /// each of these causes a lot of thrashing when building/reuniquing the
886 /// constant.  Instead of doing this, we look at all the uses and rewrite all
887 /// the place holders at once for any constant that uses a placeholder.
888 void BitcodeReaderValueList::resolveConstantForwardRefs() {
889   // Sort the values by-pointer so that they are efficient to look up with a
890   // binary search.
891   std::sort(ResolveConstants.begin(), ResolveConstants.end());
892
893   SmallVector<Constant*, 64> NewOps;
894
895   while (!ResolveConstants.empty()) {
896     Value *RealVal = operator[](ResolveConstants.back().second);
897     Constant *Placeholder = ResolveConstants.back().first;
898     ResolveConstants.pop_back();
899
900     // Loop over all users of the placeholder, updating them to reference the
901     // new value.  If they reference more than one placeholder, update them all
902     // at once.
903     while (!Placeholder->use_empty()) {
904       auto UI = Placeholder->user_begin();
905       User *U = *UI;
906
907       // If the using object isn't uniqued, just update the operands.  This
908       // handles instructions and initializers for global variables.
909       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
910         UI.getUse().set(RealVal);
911         continue;
912       }
913
914       // Otherwise, we have a constant that uses the placeholder.  Replace that
915       // constant with a new constant that has *all* placeholder uses updated.
916       Constant *UserC = cast<Constant>(U);
917       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
918            I != E; ++I) {
919         Value *NewOp;
920         if (!isa<ConstantPlaceHolder>(*I)) {
921           // Not a placeholder reference.
922           NewOp = *I;
923         } else if (*I == Placeholder) {
924           // Common case is that it just references this one placeholder.
925           NewOp = RealVal;
926         } else {
927           // Otherwise, look up the placeholder in ResolveConstants.
928           ResolveConstantsTy::iterator It =
929             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
930                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
931                                                             0));
932           assert(It != ResolveConstants.end() && It->first == *I);
933           NewOp = operator[](It->second);
934         }
935
936         NewOps.push_back(cast<Constant>(NewOp));
937       }
938
939       // Make the new constant.
940       Constant *NewC;
941       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
942         NewC = ConstantArray::get(UserCA->getType(), NewOps);
943       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
944         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
945       } else if (isa<ConstantVector>(UserC)) {
946         NewC = ConstantVector::get(NewOps);
947       } else {
948         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
949         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
950       }
951
952       UserC->replaceAllUsesWith(NewC);
953       UserC->destroyConstant();
954       NewOps.clear();
955     }
956
957     // Update all ValueHandles, they should be the only users at this point.
958     Placeholder->replaceAllUsesWith(RealVal);
959     delete Placeholder;
960   }
961 }
962
963 void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
964   if (Idx == size()) {
965     push_back(MD);
966     return;
967   }
968
969   if (Idx >= size())
970     resize(Idx+1);
971
972   TrackingMDRef &OldMD = MDValuePtrs[Idx];
973   if (!OldMD) {
974     OldMD.reset(MD);
975     return;
976   }
977
978   // If there was a forward reference to this value, replace it.
979   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
980   PrevMD->replaceAllUsesWith(MD);
981   --NumFwdRefs;
982 }
983
984 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
985   if (Idx >= size())
986     resize(Idx + 1);
987
988   if (Metadata *MD = MDValuePtrs[Idx])
989     return MD;
990
991   // Track forward refs to be resolved later.
992   if (AnyFwdRefs) {
993     MinFwdRef = std::min(MinFwdRef, Idx);
994     MaxFwdRef = std::max(MaxFwdRef, Idx);
995   } else {
996     AnyFwdRefs = true;
997     MinFwdRef = MaxFwdRef = Idx;
998   }
999   ++NumFwdRefs;
1000
1001   // Create and return a placeholder, which will later be RAUW'd.
1002   Metadata *MD = MDNode::getTemporary(Context, None).release();
1003   MDValuePtrs[Idx].reset(MD);
1004   return MD;
1005 }
1006
1007 void BitcodeReaderMDValueList::tryToResolveCycles() {
1008   if (!AnyFwdRefs)
1009     // Nothing to do.
1010     return;
1011
1012   if (NumFwdRefs)
1013     // Still forward references... can't resolve cycles.
1014     return;
1015
1016   // Resolve any cycles.
1017   for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1018     auto &MD = MDValuePtrs[I];
1019     auto *N = dyn_cast_or_null<MDNode>(MD);
1020     if (!N)
1021       continue;
1022
1023     assert(!N->isTemporary() && "Unexpected forward reference");
1024     N->resolveCycles();
1025   }
1026
1027   // Make sure we return early again until there's another forward ref.
1028   AnyFwdRefs = false;
1029 }
1030
1031 Type *BitcodeReader::getTypeByID(unsigned ID) {
1032   // The type table size is always specified correctly.
1033   if (ID >= TypeList.size())
1034     return nullptr;
1035
1036   if (Type *Ty = TypeList[ID])
1037     return Ty;
1038
1039   // If we have a forward reference, the only possible case is when it is to a
1040   // named struct.  Just create a placeholder for now.
1041   return TypeList[ID] = createIdentifiedStructType(Context);
1042 }
1043
1044 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1045                                                       StringRef Name) {
1046   auto *Ret = StructType::create(Context, Name);
1047   IdentifiedStructTypes.push_back(Ret);
1048   return Ret;
1049 }
1050
1051 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1052   auto *Ret = StructType::create(Context);
1053   IdentifiedStructTypes.push_back(Ret);
1054   return Ret;
1055 }
1056
1057
1058 //===----------------------------------------------------------------------===//
1059 //  Functions for parsing blocks from the bitcode file
1060 //===----------------------------------------------------------------------===//
1061
1062
1063 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1064 /// been decoded from the given integer. This function must stay in sync with
1065 /// 'encodeLLVMAttributesForBitcode'.
1066 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1067                                            uint64_t EncodedAttrs) {
1068   // FIXME: Remove in 4.0.
1069
1070   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1071   // the bits above 31 down by 11 bits.
1072   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1073   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1074          "Alignment must be a power of two.");
1075
1076   if (Alignment)
1077     B.addAlignmentAttr(Alignment);
1078   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1079                 (EncodedAttrs & 0xffff));
1080 }
1081
1082 std::error_code BitcodeReader::parseAttributeBlock() {
1083   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1084     return error("Invalid record");
1085
1086   if (!MAttributes.empty())
1087     return error("Invalid multiple blocks");
1088
1089   SmallVector<uint64_t, 64> Record;
1090
1091   SmallVector<AttributeSet, 8> Attrs;
1092
1093   // Read all the records.
1094   while (1) {
1095     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1096
1097     switch (Entry.Kind) {
1098     case BitstreamEntry::SubBlock: // Handled for us already.
1099     case BitstreamEntry::Error:
1100       return error("Malformed block");
1101     case BitstreamEntry::EndBlock:
1102       return std::error_code();
1103     case BitstreamEntry::Record:
1104       // The interesting case.
1105       break;
1106     }
1107
1108     // Read a record.
1109     Record.clear();
1110     switch (Stream.readRecord(Entry.ID, Record)) {
1111     default:  // Default behavior: ignore.
1112       break;
1113     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1114       // FIXME: Remove in 4.0.
1115       if (Record.size() & 1)
1116         return error("Invalid record");
1117
1118       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1119         AttrBuilder B;
1120         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1121         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1122       }
1123
1124       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1125       Attrs.clear();
1126       break;
1127     }
1128     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1129       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1130         Attrs.push_back(MAttributeGroups[Record[i]]);
1131
1132       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1133       Attrs.clear();
1134       break;
1135     }
1136     }
1137   }
1138 }
1139
1140 // Returns Attribute::None on unrecognized codes.
1141 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1142   switch (Code) {
1143   default:
1144     return Attribute::None;
1145   case bitc::ATTR_KIND_ALIGNMENT:
1146     return Attribute::Alignment;
1147   case bitc::ATTR_KIND_ALWAYS_INLINE:
1148     return Attribute::AlwaysInline;
1149   case bitc::ATTR_KIND_ARGMEMONLY:
1150     return Attribute::ArgMemOnly;
1151   case bitc::ATTR_KIND_BUILTIN:
1152     return Attribute::Builtin;
1153   case bitc::ATTR_KIND_BY_VAL:
1154     return Attribute::ByVal;
1155   case bitc::ATTR_KIND_IN_ALLOCA:
1156     return Attribute::InAlloca;
1157   case bitc::ATTR_KIND_COLD:
1158     return Attribute::Cold;
1159   case bitc::ATTR_KIND_CONVERGENT:
1160     return Attribute::Convergent;
1161   case bitc::ATTR_KIND_INLINE_HINT:
1162     return Attribute::InlineHint;
1163   case bitc::ATTR_KIND_IN_REG:
1164     return Attribute::InReg;
1165   case bitc::ATTR_KIND_JUMP_TABLE:
1166     return Attribute::JumpTable;
1167   case bitc::ATTR_KIND_MIN_SIZE:
1168     return Attribute::MinSize;
1169   case bitc::ATTR_KIND_NAKED:
1170     return Attribute::Naked;
1171   case bitc::ATTR_KIND_NEST:
1172     return Attribute::Nest;
1173   case bitc::ATTR_KIND_NO_ALIAS:
1174     return Attribute::NoAlias;
1175   case bitc::ATTR_KIND_NO_BUILTIN:
1176     return Attribute::NoBuiltin;
1177   case bitc::ATTR_KIND_NO_CAPTURE:
1178     return Attribute::NoCapture;
1179   case bitc::ATTR_KIND_NO_DUPLICATE:
1180     return Attribute::NoDuplicate;
1181   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1182     return Attribute::NoImplicitFloat;
1183   case bitc::ATTR_KIND_NO_INLINE:
1184     return Attribute::NoInline;
1185   case bitc::ATTR_KIND_NON_LAZY_BIND:
1186     return Attribute::NonLazyBind;
1187   case bitc::ATTR_KIND_NON_NULL:
1188     return Attribute::NonNull;
1189   case bitc::ATTR_KIND_DEREFERENCEABLE:
1190     return Attribute::Dereferenceable;
1191   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1192     return Attribute::DereferenceableOrNull;
1193   case bitc::ATTR_KIND_NO_RED_ZONE:
1194     return Attribute::NoRedZone;
1195   case bitc::ATTR_KIND_NO_RETURN:
1196     return Attribute::NoReturn;
1197   case bitc::ATTR_KIND_NO_UNWIND:
1198     return Attribute::NoUnwind;
1199   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1200     return Attribute::OptimizeForSize;
1201   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1202     return Attribute::OptimizeNone;
1203   case bitc::ATTR_KIND_READ_NONE:
1204     return Attribute::ReadNone;
1205   case bitc::ATTR_KIND_READ_ONLY:
1206     return Attribute::ReadOnly;
1207   case bitc::ATTR_KIND_RETURNED:
1208     return Attribute::Returned;
1209   case bitc::ATTR_KIND_RETURNS_TWICE:
1210     return Attribute::ReturnsTwice;
1211   case bitc::ATTR_KIND_S_EXT:
1212     return Attribute::SExt;
1213   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1214     return Attribute::StackAlignment;
1215   case bitc::ATTR_KIND_STACK_PROTECT:
1216     return Attribute::StackProtect;
1217   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1218     return Attribute::StackProtectReq;
1219   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1220     return Attribute::StackProtectStrong;
1221   case bitc::ATTR_KIND_SAFESTACK:
1222     return Attribute::SafeStack;
1223   case bitc::ATTR_KIND_STRUCT_RET:
1224     return Attribute::StructRet;
1225   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1226     return Attribute::SanitizeAddress;
1227   case bitc::ATTR_KIND_SANITIZE_THREAD:
1228     return Attribute::SanitizeThread;
1229   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1230     return Attribute::SanitizeMemory;
1231   case bitc::ATTR_KIND_UW_TABLE:
1232     return Attribute::UWTable;
1233   case bitc::ATTR_KIND_Z_EXT:
1234     return Attribute::ZExt;
1235   }
1236 }
1237
1238 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1239                                                    unsigned &Alignment) {
1240   // Note: Alignment in bitcode files is incremented by 1, so that zero
1241   // can be used for default alignment.
1242   if (Exponent > Value::MaxAlignmentExponent + 1)
1243     return error("Invalid alignment value");
1244   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1245   return std::error_code();
1246 }
1247
1248 std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1249                                              Attribute::AttrKind *Kind) {
1250   *Kind = getAttrFromCode(Code);
1251   if (*Kind == Attribute::None)
1252     return error(BitcodeError::CorruptedBitcode,
1253                  "Unknown attribute kind (" + Twine(Code) + ")");
1254   return std::error_code();
1255 }
1256
1257 std::error_code BitcodeReader::parseAttributeGroupBlock() {
1258   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1259     return error("Invalid record");
1260
1261   if (!MAttributeGroups.empty())
1262     return error("Invalid multiple blocks");
1263
1264   SmallVector<uint64_t, 64> Record;
1265
1266   // Read all the records.
1267   while (1) {
1268     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1269
1270     switch (Entry.Kind) {
1271     case BitstreamEntry::SubBlock: // Handled for us already.
1272     case BitstreamEntry::Error:
1273       return error("Malformed block");
1274     case BitstreamEntry::EndBlock:
1275       return std::error_code();
1276     case BitstreamEntry::Record:
1277       // The interesting case.
1278       break;
1279     }
1280
1281     // Read a record.
1282     Record.clear();
1283     switch (Stream.readRecord(Entry.ID, Record)) {
1284     default:  // Default behavior: ignore.
1285       break;
1286     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1287       if (Record.size() < 3)
1288         return error("Invalid record");
1289
1290       uint64_t GrpID = Record[0];
1291       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1292
1293       AttrBuilder B;
1294       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1295         if (Record[i] == 0) {        // Enum attribute
1296           Attribute::AttrKind Kind;
1297           if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1298             return EC;
1299
1300           B.addAttribute(Kind);
1301         } else if (Record[i] == 1) { // Integer attribute
1302           Attribute::AttrKind Kind;
1303           if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1304             return EC;
1305           if (Kind == Attribute::Alignment)
1306             B.addAlignmentAttr(Record[++i]);
1307           else if (Kind == Attribute::StackAlignment)
1308             B.addStackAlignmentAttr(Record[++i]);
1309           else if (Kind == Attribute::Dereferenceable)
1310             B.addDereferenceableAttr(Record[++i]);
1311           else if (Kind == Attribute::DereferenceableOrNull)
1312             B.addDereferenceableOrNullAttr(Record[++i]);
1313         } else {                     // String attribute
1314           assert((Record[i] == 3 || Record[i] == 4) &&
1315                  "Invalid attribute group entry");
1316           bool HasValue = (Record[i++] == 4);
1317           SmallString<64> KindStr;
1318           SmallString<64> ValStr;
1319
1320           while (Record[i] != 0 && i != e)
1321             KindStr += Record[i++];
1322           assert(Record[i] == 0 && "Kind string not null terminated");
1323
1324           if (HasValue) {
1325             // Has a value associated with it.
1326             ++i; // Skip the '0' that terminates the "kind" string.
1327             while (Record[i] != 0 && i != e)
1328               ValStr += Record[i++];
1329             assert(Record[i] == 0 && "Value string not null terminated");
1330           }
1331
1332           B.addAttribute(KindStr.str(), ValStr.str());
1333         }
1334       }
1335
1336       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1337       break;
1338     }
1339     }
1340   }
1341 }
1342
1343 std::error_code BitcodeReader::parseTypeTable() {
1344   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1345     return error("Invalid record");
1346
1347   return parseTypeTableBody();
1348 }
1349
1350 std::error_code BitcodeReader::parseTypeTableBody() {
1351   if (!TypeList.empty())
1352     return error("Invalid multiple blocks");
1353
1354   SmallVector<uint64_t, 64> Record;
1355   unsigned NumRecords = 0;
1356
1357   SmallString<64> TypeName;
1358
1359   // Read all the records for this type table.
1360   while (1) {
1361     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1362
1363     switch (Entry.Kind) {
1364     case BitstreamEntry::SubBlock: // Handled for us already.
1365     case BitstreamEntry::Error:
1366       return error("Malformed block");
1367     case BitstreamEntry::EndBlock:
1368       if (NumRecords != TypeList.size())
1369         return error("Malformed block");
1370       return std::error_code();
1371     case BitstreamEntry::Record:
1372       // The interesting case.
1373       break;
1374     }
1375
1376     // Read a record.
1377     Record.clear();
1378     Type *ResultTy = nullptr;
1379     switch (Stream.readRecord(Entry.ID, Record)) {
1380     default:
1381       return error("Invalid value");
1382     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1383       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1384       // type list.  This allows us to reserve space.
1385       if (Record.size() < 1)
1386         return error("Invalid record");
1387       TypeList.resize(Record[0]);
1388       continue;
1389     case bitc::TYPE_CODE_VOID:      // VOID
1390       ResultTy = Type::getVoidTy(Context);
1391       break;
1392     case bitc::TYPE_CODE_HALF:     // HALF
1393       ResultTy = Type::getHalfTy(Context);
1394       break;
1395     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1396       ResultTy = Type::getFloatTy(Context);
1397       break;
1398     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1399       ResultTy = Type::getDoubleTy(Context);
1400       break;
1401     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1402       ResultTy = Type::getX86_FP80Ty(Context);
1403       break;
1404     case bitc::TYPE_CODE_FP128:     // FP128
1405       ResultTy = Type::getFP128Ty(Context);
1406       break;
1407     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1408       ResultTy = Type::getPPC_FP128Ty(Context);
1409       break;
1410     case bitc::TYPE_CODE_LABEL:     // LABEL
1411       ResultTy = Type::getLabelTy(Context);
1412       break;
1413     case bitc::TYPE_CODE_METADATA:  // METADATA
1414       ResultTy = Type::getMetadataTy(Context);
1415       break;
1416     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1417       ResultTy = Type::getX86_MMXTy(Context);
1418       break;
1419     case bitc::TYPE_CODE_TOKEN:     // TOKEN
1420       ResultTy = Type::getTokenTy(Context);
1421       break;
1422     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1423       if (Record.size() < 1)
1424         return error("Invalid record");
1425
1426       uint64_t NumBits = Record[0];
1427       if (NumBits < IntegerType::MIN_INT_BITS ||
1428           NumBits > IntegerType::MAX_INT_BITS)
1429         return error("Bitwidth for integer type out of range");
1430       ResultTy = IntegerType::get(Context, NumBits);
1431       break;
1432     }
1433     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1434                                     //          [pointee type, address space]
1435       if (Record.size() < 1)
1436         return error("Invalid record");
1437       unsigned AddressSpace = 0;
1438       if (Record.size() == 2)
1439         AddressSpace = Record[1];
1440       ResultTy = getTypeByID(Record[0]);
1441       if (!ResultTy ||
1442           !PointerType::isValidElementType(ResultTy))
1443         return error("Invalid type");
1444       ResultTy = PointerType::get(ResultTy, AddressSpace);
1445       break;
1446     }
1447     case bitc::TYPE_CODE_FUNCTION_OLD: {
1448       // FIXME: attrid is dead, remove it in LLVM 4.0
1449       // FUNCTION: [vararg, attrid, retty, paramty x N]
1450       if (Record.size() < 3)
1451         return error("Invalid record");
1452       SmallVector<Type*, 8> ArgTys;
1453       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1454         if (Type *T = getTypeByID(Record[i]))
1455           ArgTys.push_back(T);
1456         else
1457           break;
1458       }
1459
1460       ResultTy = getTypeByID(Record[2]);
1461       if (!ResultTy || ArgTys.size() < Record.size()-3)
1462         return error("Invalid type");
1463
1464       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1465       break;
1466     }
1467     case bitc::TYPE_CODE_FUNCTION: {
1468       // FUNCTION: [vararg, retty, paramty x N]
1469       if (Record.size() < 2)
1470         return error("Invalid record");
1471       SmallVector<Type*, 8> ArgTys;
1472       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1473         if (Type *T = getTypeByID(Record[i])) {
1474           if (!FunctionType::isValidArgumentType(T))
1475             return error("Invalid function argument type");
1476           ArgTys.push_back(T);
1477         }
1478         else
1479           break;
1480       }
1481
1482       ResultTy = getTypeByID(Record[1]);
1483       if (!ResultTy || ArgTys.size() < Record.size()-2)
1484         return error("Invalid type");
1485
1486       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1487       break;
1488     }
1489     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1490       if (Record.size() < 1)
1491         return error("Invalid record");
1492       SmallVector<Type*, 8> EltTys;
1493       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1494         if (Type *T = getTypeByID(Record[i]))
1495           EltTys.push_back(T);
1496         else
1497           break;
1498       }
1499       if (EltTys.size() != Record.size()-1)
1500         return error("Invalid type");
1501       ResultTy = StructType::get(Context, EltTys, Record[0]);
1502       break;
1503     }
1504     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1505       if (convertToString(Record, 0, TypeName))
1506         return error("Invalid record");
1507       continue;
1508
1509     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1510       if (Record.size() < 1)
1511         return error("Invalid record");
1512
1513       if (NumRecords >= TypeList.size())
1514         return error("Invalid TYPE table");
1515
1516       // Check to see if this was forward referenced, if so fill in the temp.
1517       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1518       if (Res) {
1519         Res->setName(TypeName);
1520         TypeList[NumRecords] = nullptr;
1521       } else  // Otherwise, create a new struct.
1522         Res = createIdentifiedStructType(Context, TypeName);
1523       TypeName.clear();
1524
1525       SmallVector<Type*, 8> EltTys;
1526       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1527         if (Type *T = getTypeByID(Record[i]))
1528           EltTys.push_back(T);
1529         else
1530           break;
1531       }
1532       if (EltTys.size() != Record.size()-1)
1533         return error("Invalid record");
1534       Res->setBody(EltTys, Record[0]);
1535       ResultTy = Res;
1536       break;
1537     }
1538     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1539       if (Record.size() != 1)
1540         return error("Invalid record");
1541
1542       if (NumRecords >= TypeList.size())
1543         return error("Invalid TYPE table");
1544
1545       // Check to see if this was forward referenced, if so fill in the temp.
1546       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1547       if (Res) {
1548         Res->setName(TypeName);
1549         TypeList[NumRecords] = nullptr;
1550       } else  // Otherwise, create a new struct with no body.
1551         Res = createIdentifiedStructType(Context, TypeName);
1552       TypeName.clear();
1553       ResultTy = Res;
1554       break;
1555     }
1556     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1557       if (Record.size() < 2)
1558         return error("Invalid record");
1559       ResultTy = getTypeByID(Record[1]);
1560       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1561         return error("Invalid type");
1562       ResultTy = ArrayType::get(ResultTy, Record[0]);
1563       break;
1564     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1565       if (Record.size() < 2)
1566         return error("Invalid record");
1567       if (Record[0] == 0)
1568         return error("Invalid vector length");
1569       ResultTy = getTypeByID(Record[1]);
1570       if (!ResultTy || !StructType::isValidElementType(ResultTy))
1571         return error("Invalid type");
1572       ResultTy = VectorType::get(ResultTy, Record[0]);
1573       break;
1574     }
1575
1576     if (NumRecords >= TypeList.size())
1577       return error("Invalid TYPE table");
1578     if (TypeList[NumRecords])
1579       return error(
1580           "Invalid TYPE table: Only named structs can be forward referenced");
1581     assert(ResultTy && "Didn't read a type?");
1582     TypeList[NumRecords++] = ResultTy;
1583   }
1584 }
1585
1586 std::error_code BitcodeReader::parseValueSymbolTable() {
1587   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1588     return error("Invalid record");
1589
1590   SmallVector<uint64_t, 64> Record;
1591
1592   Triple TT(TheModule->getTargetTriple());
1593
1594   // Read all the records for this value table.
1595   SmallString<128> ValueName;
1596   while (1) {
1597     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1598
1599     switch (Entry.Kind) {
1600     case BitstreamEntry::SubBlock: // Handled for us already.
1601     case BitstreamEntry::Error:
1602       return error("Malformed block");
1603     case BitstreamEntry::EndBlock:
1604       return std::error_code();
1605     case BitstreamEntry::Record:
1606       // The interesting case.
1607       break;
1608     }
1609
1610     // Read a record.
1611     Record.clear();
1612     switch (Stream.readRecord(Entry.ID, Record)) {
1613     default:  // Default behavior: unknown type.
1614       break;
1615     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1616       if (convertToString(Record, 1, ValueName))
1617         return error("Invalid record");
1618       unsigned ValueID = Record[0];
1619       if (ValueID >= ValueList.size() || !ValueList[ValueID])
1620         return error("Invalid record");
1621       Value *V = ValueList[ValueID];
1622
1623       V->setName(StringRef(ValueName.data(), ValueName.size()));
1624       if (auto *GO = dyn_cast<GlobalObject>(V)) {
1625         if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1626           if (TT.isOSBinFormatMachO())
1627             GO->setComdat(nullptr);
1628           else
1629             GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1630         }
1631       }
1632       ValueName.clear();
1633       break;
1634     }
1635     case bitc::VST_CODE_BBENTRY: {
1636       if (convertToString(Record, 1, ValueName))
1637         return error("Invalid record");
1638       BasicBlock *BB = getBasicBlock(Record[0]);
1639       if (!BB)
1640         return error("Invalid record");
1641
1642       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1643       ValueName.clear();
1644       break;
1645     }
1646     }
1647   }
1648 }
1649
1650 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1651
1652 std::error_code BitcodeReader::parseMetadata() {
1653   IsMetadataMaterialized = true;
1654   unsigned NextMDValueNo = MDValueList.size();
1655
1656   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1657     return error("Invalid record");
1658
1659   SmallVector<uint64_t, 64> Record;
1660
1661   auto getMD =
1662       [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1663   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1664     if (ID)
1665       return getMD(ID - 1);
1666     return nullptr;
1667   };
1668   auto getMDString = [&](unsigned ID) -> MDString *{
1669     // This requires that the ID is not really a forward reference.  In
1670     // particular, the MDString must already have been resolved.
1671     return cast_or_null<MDString>(getMDOrNull(ID));
1672   };
1673
1674 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
1675   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1676
1677   // Read all the records.
1678   while (1) {
1679     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1680
1681     switch (Entry.Kind) {
1682     case BitstreamEntry::SubBlock: // Handled for us already.
1683     case BitstreamEntry::Error:
1684       return error("Malformed block");
1685     case BitstreamEntry::EndBlock:
1686       MDValueList.tryToResolveCycles();
1687       return std::error_code();
1688     case BitstreamEntry::Record:
1689       // The interesting case.
1690       break;
1691     }
1692
1693     // Read a record.
1694     Record.clear();
1695     unsigned Code = Stream.readRecord(Entry.ID, Record);
1696     bool IsDistinct = false;
1697     switch (Code) {
1698     default:  // Default behavior: ignore.
1699       break;
1700     case bitc::METADATA_NAME: {
1701       // Read name of the named metadata.
1702       SmallString<8> Name(Record.begin(), Record.end());
1703       Record.clear();
1704       Code = Stream.ReadCode();
1705
1706       unsigned NextBitCode = Stream.readRecord(Code, Record);
1707       if (NextBitCode != bitc::METADATA_NAMED_NODE)
1708         return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1709
1710       // Read named metadata elements.
1711       unsigned Size = Record.size();
1712       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1713       for (unsigned i = 0; i != Size; ++i) {
1714         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1715         if (!MD)
1716           return error("Invalid record");
1717         NMD->addOperand(MD);
1718       }
1719       break;
1720     }
1721     case bitc::METADATA_OLD_FN_NODE: {
1722       // FIXME: Remove in 4.0.
1723       // This is a LocalAsMetadata record, the only type of function-local
1724       // metadata.
1725       if (Record.size() % 2 == 1)
1726         return error("Invalid record");
1727
1728       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
1729       // to be legal, but there's no upgrade path.
1730       auto dropRecord = [&] {
1731         MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1732       };
1733       if (Record.size() != 2) {
1734         dropRecord();
1735         break;
1736       }
1737
1738       Type *Ty = getTypeByID(Record[0]);
1739       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1740         dropRecord();
1741         break;
1742       }
1743
1744       MDValueList.assignValue(
1745           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1746           NextMDValueNo++);
1747       break;
1748     }
1749     case bitc::METADATA_OLD_NODE: {
1750       // FIXME: Remove in 4.0.
1751       if (Record.size() % 2 == 1)
1752         return error("Invalid record");
1753
1754       unsigned Size = Record.size();
1755       SmallVector<Metadata *, 8> Elts;
1756       for (unsigned i = 0; i != Size; i += 2) {
1757         Type *Ty = getTypeByID(Record[i]);
1758         if (!Ty)
1759           return error("Invalid record");
1760         if (Ty->isMetadataTy())
1761           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1762         else if (!Ty->isVoidTy()) {
1763           auto *MD =
1764               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1765           assert(isa<ConstantAsMetadata>(MD) &&
1766                  "Expected non-function-local metadata");
1767           Elts.push_back(MD);
1768         } else
1769           Elts.push_back(nullptr);
1770       }
1771       MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1772       break;
1773     }
1774     case bitc::METADATA_VALUE: {
1775       if (Record.size() != 2)
1776         return error("Invalid record");
1777
1778       Type *Ty = getTypeByID(Record[0]);
1779       if (Ty->isMetadataTy() || Ty->isVoidTy())
1780         return error("Invalid record");
1781
1782       MDValueList.assignValue(
1783           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1784           NextMDValueNo++);
1785       break;
1786     }
1787     case bitc::METADATA_DISTINCT_NODE:
1788       IsDistinct = true;
1789       // fallthrough...
1790     case bitc::METADATA_NODE: {
1791       SmallVector<Metadata *, 8> Elts;
1792       Elts.reserve(Record.size());
1793       for (unsigned ID : Record)
1794         Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1795       MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1796                                          : MDNode::get(Context, Elts),
1797                               NextMDValueNo++);
1798       break;
1799     }
1800     case bitc::METADATA_LOCATION: {
1801       if (Record.size() != 5)
1802         return error("Invalid record");
1803
1804       unsigned Line = Record[1];
1805       unsigned Column = Record[2];
1806       MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1807       Metadata *InlinedAt =
1808           Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1809       MDValueList.assignValue(
1810           GET_OR_DISTINCT(DILocation, Record[0],
1811                           (Context, Line, Column, Scope, InlinedAt)),
1812           NextMDValueNo++);
1813       break;
1814     }
1815     case bitc::METADATA_GENERIC_DEBUG: {
1816       if (Record.size() < 4)
1817         return error("Invalid record");
1818
1819       unsigned Tag = Record[1];
1820       unsigned Version = Record[2];
1821
1822       if (Tag >= 1u << 16 || Version != 0)
1823         return error("Invalid record");
1824
1825       auto *Header = getMDString(Record[3]);
1826       SmallVector<Metadata *, 8> DwarfOps;
1827       for (unsigned I = 4, E = Record.size(); I != E; ++I)
1828         DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1829                                      : nullptr);
1830       MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1831                                               (Context, Tag, Header, DwarfOps)),
1832                               NextMDValueNo++);
1833       break;
1834     }
1835     case bitc::METADATA_SUBRANGE: {
1836       if (Record.size() != 3)
1837         return error("Invalid record");
1838
1839       MDValueList.assignValue(
1840           GET_OR_DISTINCT(DISubrange, Record[0],
1841                           (Context, Record[1], unrotateSign(Record[2]))),
1842           NextMDValueNo++);
1843       break;
1844     }
1845     case bitc::METADATA_ENUMERATOR: {
1846       if (Record.size() != 3)
1847         return error("Invalid record");
1848
1849       MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1850                                               (Context, unrotateSign(Record[1]),
1851                                                getMDString(Record[2]))),
1852                               NextMDValueNo++);
1853       break;
1854     }
1855     case bitc::METADATA_BASIC_TYPE: {
1856       if (Record.size() != 6)
1857         return error("Invalid record");
1858
1859       MDValueList.assignValue(
1860           GET_OR_DISTINCT(DIBasicType, Record[0],
1861                           (Context, Record[1], getMDString(Record[2]),
1862                            Record[3], Record[4], Record[5])),
1863           NextMDValueNo++);
1864       break;
1865     }
1866     case bitc::METADATA_DERIVED_TYPE: {
1867       if (Record.size() != 12)
1868         return error("Invalid record");
1869
1870       MDValueList.assignValue(
1871           GET_OR_DISTINCT(DIDerivedType, Record[0],
1872                           (Context, Record[1], getMDString(Record[2]),
1873                            getMDOrNull(Record[3]), Record[4],
1874                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1875                            Record[7], Record[8], Record[9], Record[10],
1876                            getMDOrNull(Record[11]))),
1877           NextMDValueNo++);
1878       break;
1879     }
1880     case bitc::METADATA_COMPOSITE_TYPE: {
1881       if (Record.size() != 16)
1882         return error("Invalid record");
1883
1884       MDValueList.assignValue(
1885           GET_OR_DISTINCT(DICompositeType, Record[0],
1886                           (Context, Record[1], getMDString(Record[2]),
1887                            getMDOrNull(Record[3]), Record[4],
1888                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1889                            Record[7], Record[8], Record[9], Record[10],
1890                            getMDOrNull(Record[11]), Record[12],
1891                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1892                            getMDString(Record[15]))),
1893           NextMDValueNo++);
1894       break;
1895     }
1896     case bitc::METADATA_SUBROUTINE_TYPE: {
1897       if (Record.size() != 3)
1898         return error("Invalid record");
1899
1900       MDValueList.assignValue(
1901           GET_OR_DISTINCT(DISubroutineType, Record[0],
1902                           (Context, Record[1], getMDOrNull(Record[2]))),
1903           NextMDValueNo++);
1904       break;
1905     }
1906
1907     case bitc::METADATA_MODULE: {
1908       if (Record.size() != 6)
1909         return error("Invalid record");
1910
1911       MDValueList.assignValue(
1912           GET_OR_DISTINCT(DIModule, Record[0],
1913                           (Context, getMDOrNull(Record[1]),
1914                           getMDString(Record[2]), getMDString(Record[3]),
1915                           getMDString(Record[4]), getMDString(Record[5]))),
1916           NextMDValueNo++);
1917       break;
1918     }
1919
1920     case bitc::METADATA_FILE: {
1921       if (Record.size() != 3)
1922         return error("Invalid record");
1923
1924       MDValueList.assignValue(
1925           GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1926                                               getMDString(Record[2]))),
1927           NextMDValueNo++);
1928       break;
1929     }
1930     case bitc::METADATA_COMPILE_UNIT: {
1931       if (Record.size() < 14 || Record.size() > 15)
1932         return error("Invalid record");
1933
1934       // Ignore Record[1], which indicates whether this compile unit is
1935       // distinct.  It's always distinct.
1936       MDValueList.assignValue(
1937           DICompileUnit::getDistinct(
1938               Context, Record[1], getMDOrNull(Record[2]),
1939               getMDString(Record[3]), Record[4], getMDString(Record[5]),
1940               Record[6], getMDString(Record[7]), Record[8],
1941               getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1942               getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1943               getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
1944           NextMDValueNo++);
1945       break;
1946     }
1947     case bitc::METADATA_SUBPROGRAM: {
1948       if (Record.size() != 19)
1949         return error("Invalid record");
1950
1951       MDValueList.assignValue(
1952           GET_OR_DISTINCT(
1953               DISubprogram,
1954               Record[0] || Record[8], // All definitions should be distinct.
1955               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1956                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1957                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1958                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1959                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1960                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1961           NextMDValueNo++);
1962       break;
1963     }
1964     case bitc::METADATA_LEXICAL_BLOCK: {
1965       if (Record.size() != 5)
1966         return error("Invalid record");
1967
1968       MDValueList.assignValue(
1969           GET_OR_DISTINCT(DILexicalBlock, Record[0],
1970                           (Context, getMDOrNull(Record[1]),
1971                            getMDOrNull(Record[2]), Record[3], Record[4])),
1972           NextMDValueNo++);
1973       break;
1974     }
1975     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1976       if (Record.size() != 4)
1977         return error("Invalid record");
1978
1979       MDValueList.assignValue(
1980           GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1981                           (Context, getMDOrNull(Record[1]),
1982                            getMDOrNull(Record[2]), Record[3])),
1983           NextMDValueNo++);
1984       break;
1985     }
1986     case bitc::METADATA_NAMESPACE: {
1987       if (Record.size() != 5)
1988         return error("Invalid record");
1989
1990       MDValueList.assignValue(
1991           GET_OR_DISTINCT(DINamespace, Record[0],
1992                           (Context, getMDOrNull(Record[1]),
1993                            getMDOrNull(Record[2]), getMDString(Record[3]),
1994                            Record[4])),
1995           NextMDValueNo++);
1996       break;
1997     }
1998     case bitc::METADATA_TEMPLATE_TYPE: {
1999       if (Record.size() != 3)
2000         return error("Invalid record");
2001
2002       MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2003                                               Record[0],
2004                                               (Context, getMDString(Record[1]),
2005                                                getMDOrNull(Record[2]))),
2006                               NextMDValueNo++);
2007       break;
2008     }
2009     case bitc::METADATA_TEMPLATE_VALUE: {
2010       if (Record.size() != 5)
2011         return error("Invalid record");
2012
2013       MDValueList.assignValue(
2014           GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2015                           (Context, Record[1], getMDString(Record[2]),
2016                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2017           NextMDValueNo++);
2018       break;
2019     }
2020     case bitc::METADATA_GLOBAL_VAR: {
2021       if (Record.size() != 11)
2022         return error("Invalid record");
2023
2024       MDValueList.assignValue(
2025           GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2026                           (Context, getMDOrNull(Record[1]),
2027                            getMDString(Record[2]), getMDString(Record[3]),
2028                            getMDOrNull(Record[4]), Record[5],
2029                            getMDOrNull(Record[6]), Record[7], Record[8],
2030                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2031           NextMDValueNo++);
2032       break;
2033     }
2034     case bitc::METADATA_LOCAL_VAR: {
2035       // 10th field is for the obseleted 'inlinedAt:' field.
2036       if (Record.size() < 8 || Record.size() > 10)
2037         return error("Invalid record");
2038
2039       // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2040       // DW_TAG_arg_variable.
2041       bool HasTag = Record.size() > 8;
2042       MDValueList.assignValue(
2043           GET_OR_DISTINCT(DILocalVariable, Record[0],
2044                           (Context, getMDOrNull(Record[1 + HasTag]),
2045                            getMDString(Record[2 + HasTag]),
2046                            getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2047                            getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2048                            Record[7 + HasTag])),
2049           NextMDValueNo++);
2050       break;
2051     }
2052     case bitc::METADATA_EXPRESSION: {
2053       if (Record.size() < 1)
2054         return error("Invalid record");
2055
2056       MDValueList.assignValue(
2057           GET_OR_DISTINCT(DIExpression, Record[0],
2058                           (Context, makeArrayRef(Record).slice(1))),
2059           NextMDValueNo++);
2060       break;
2061     }
2062     case bitc::METADATA_OBJC_PROPERTY: {
2063       if (Record.size() != 8)
2064         return error("Invalid record");
2065
2066       MDValueList.assignValue(
2067           GET_OR_DISTINCT(DIObjCProperty, Record[0],
2068                           (Context, getMDString(Record[1]),
2069                            getMDOrNull(Record[2]), Record[3],
2070                            getMDString(Record[4]), getMDString(Record[5]),
2071                            Record[6], getMDOrNull(Record[7]))),
2072           NextMDValueNo++);
2073       break;
2074     }
2075     case bitc::METADATA_IMPORTED_ENTITY: {
2076       if (Record.size() != 6)
2077         return error("Invalid record");
2078
2079       MDValueList.assignValue(
2080           GET_OR_DISTINCT(DIImportedEntity, Record[0],
2081                           (Context, Record[1], getMDOrNull(Record[2]),
2082                            getMDOrNull(Record[3]), Record[4],
2083                            getMDString(Record[5]))),
2084           NextMDValueNo++);
2085       break;
2086     }
2087     case bitc::METADATA_STRING: {
2088       std::string String(Record.begin(), Record.end());
2089       llvm::UpgradeMDStringConstant(String);
2090       Metadata *MD = MDString::get(Context, String);
2091       MDValueList.assignValue(MD, NextMDValueNo++);
2092       break;
2093     }
2094     case bitc::METADATA_KIND: {
2095       if (Record.size() < 2)
2096         return error("Invalid record");
2097
2098       unsigned Kind = Record[0];
2099       SmallString<8> Name(Record.begin()+1, Record.end());
2100
2101       unsigned NewKind = TheModule->getMDKindID(Name.str());
2102       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2103         return error("Conflicting METADATA_KIND records");
2104       break;
2105     }
2106     }
2107   }
2108 #undef GET_OR_DISTINCT
2109 }
2110
2111 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2112 /// encoding.
2113 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2114   if ((V & 1) == 0)
2115     return V >> 1;
2116   if (V != 1)
2117     return -(V >> 1);
2118   // There is no such thing as -0 with integers.  "-0" really means MININT.
2119   return 1ULL << 63;
2120 }
2121
2122 /// Resolve all of the initializers for global values and aliases that we can.
2123 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2124   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2125   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2126   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2127   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2128   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2129
2130   GlobalInitWorklist.swap(GlobalInits);
2131   AliasInitWorklist.swap(AliasInits);
2132   FunctionPrefixWorklist.swap(FunctionPrefixes);
2133   FunctionPrologueWorklist.swap(FunctionPrologues);
2134   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2135
2136   while (!GlobalInitWorklist.empty()) {
2137     unsigned ValID = GlobalInitWorklist.back().second;
2138     if (ValID >= ValueList.size()) {
2139       // Not ready to resolve this yet, it requires something later in the file.
2140       GlobalInits.push_back(GlobalInitWorklist.back());
2141     } else {
2142       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2143         GlobalInitWorklist.back().first->setInitializer(C);
2144       else
2145         return error("Expected a constant");
2146     }
2147     GlobalInitWorklist.pop_back();
2148   }
2149
2150   while (!AliasInitWorklist.empty()) {
2151     unsigned ValID = AliasInitWorklist.back().second;
2152     if (ValID >= ValueList.size()) {
2153       AliasInits.push_back(AliasInitWorklist.back());
2154     } else {
2155       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2156       if (!C)
2157         return error("Expected a constant");
2158       GlobalAlias *Alias = AliasInitWorklist.back().first;
2159       if (C->getType() != Alias->getType())
2160         return error("Alias and aliasee types don't match");
2161       Alias->setAliasee(C);
2162     }
2163     AliasInitWorklist.pop_back();
2164   }
2165
2166   while (!FunctionPrefixWorklist.empty()) {
2167     unsigned ValID = FunctionPrefixWorklist.back().second;
2168     if (ValID >= ValueList.size()) {
2169       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2170     } else {
2171       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2172         FunctionPrefixWorklist.back().first->setPrefixData(C);
2173       else
2174         return error("Expected a constant");
2175     }
2176     FunctionPrefixWorklist.pop_back();
2177   }
2178
2179   while (!FunctionPrologueWorklist.empty()) {
2180     unsigned ValID = FunctionPrologueWorklist.back().second;
2181     if (ValID >= ValueList.size()) {
2182       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2183     } else {
2184       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2185         FunctionPrologueWorklist.back().first->setPrologueData(C);
2186       else
2187         return error("Expected a constant");
2188     }
2189     FunctionPrologueWorklist.pop_back();
2190   }
2191
2192   while (!FunctionPersonalityFnWorklist.empty()) {
2193     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2194     if (ValID >= ValueList.size()) {
2195       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2196     } else {
2197       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2198         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2199       else
2200         return error("Expected a constant");
2201     }
2202     FunctionPersonalityFnWorklist.pop_back();
2203   }
2204
2205   return std::error_code();
2206 }
2207
2208 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2209   SmallVector<uint64_t, 8> Words(Vals.size());
2210   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2211                  BitcodeReader::decodeSignRotatedValue);
2212
2213   return APInt(TypeBits, Words);
2214 }
2215
2216 std::error_code BitcodeReader::parseConstants() {
2217   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2218     return error("Invalid record");
2219
2220   SmallVector<uint64_t, 64> Record;
2221
2222   // Read all the records for this value table.
2223   Type *CurTy = Type::getInt32Ty(Context);
2224   unsigned NextCstNo = ValueList.size();
2225   while (1) {
2226     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2227
2228     switch (Entry.Kind) {
2229     case BitstreamEntry::SubBlock: // Handled for us already.
2230     case BitstreamEntry::Error:
2231       return error("Malformed block");
2232     case BitstreamEntry::EndBlock:
2233       if (NextCstNo != ValueList.size())
2234         return error("Invalid ronstant reference");
2235
2236       // Once all the constants have been read, go through and resolve forward
2237       // references.
2238       ValueList.resolveConstantForwardRefs();
2239       return std::error_code();
2240     case BitstreamEntry::Record:
2241       // The interesting case.
2242       break;
2243     }
2244
2245     // Read a record.
2246     Record.clear();
2247     Value *V = nullptr;
2248     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2249     switch (BitCode) {
2250     default:  // Default behavior: unknown constant
2251     case bitc::CST_CODE_UNDEF:     // UNDEF
2252       V = UndefValue::get(CurTy);
2253       break;
2254     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2255       if (Record.empty())
2256         return error("Invalid record");
2257       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2258         return error("Invalid record");
2259       CurTy = TypeList[Record[0]];
2260       continue;  // Skip the ValueList manipulation.
2261     case bitc::CST_CODE_NULL:      // NULL
2262       V = Constant::getNullValue(CurTy);
2263       break;
2264     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2265       if (!CurTy->isIntegerTy() || Record.empty())
2266         return error("Invalid record");
2267       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2268       break;
2269     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2270       if (!CurTy->isIntegerTy() || Record.empty())
2271         return error("Invalid record");
2272
2273       APInt VInt =
2274           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2275       V = ConstantInt::get(Context, VInt);
2276
2277       break;
2278     }
2279     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2280       if (Record.empty())
2281         return error("Invalid record");
2282       if (CurTy->isHalfTy())
2283         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2284                                              APInt(16, (uint16_t)Record[0])));
2285       else if (CurTy->isFloatTy())
2286         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2287                                              APInt(32, (uint32_t)Record[0])));
2288       else if (CurTy->isDoubleTy())
2289         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2290                                              APInt(64, Record[0])));
2291       else if (CurTy->isX86_FP80Ty()) {
2292         // Bits are not stored the same way as a normal i80 APInt, compensate.
2293         uint64_t Rearrange[2];
2294         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2295         Rearrange[1] = Record[0] >> 48;
2296         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2297                                              APInt(80, Rearrange)));
2298       } else if (CurTy->isFP128Ty())
2299         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2300                                              APInt(128, Record)));
2301       else if (CurTy->isPPC_FP128Ty())
2302         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2303                                              APInt(128, Record)));
2304       else
2305         V = UndefValue::get(CurTy);
2306       break;
2307     }
2308
2309     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2310       if (Record.empty())
2311         return error("Invalid record");
2312
2313       unsigned Size = Record.size();
2314       SmallVector<Constant*, 16> Elts;
2315
2316       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2317         for (unsigned i = 0; i != Size; ++i)
2318           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2319                                                      STy->getElementType(i)));
2320         V = ConstantStruct::get(STy, Elts);
2321       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2322         Type *EltTy = ATy->getElementType();
2323         for (unsigned i = 0; i != Size; ++i)
2324           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2325         V = ConstantArray::get(ATy, Elts);
2326       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2327         Type *EltTy = VTy->getElementType();
2328         for (unsigned i = 0; i != Size; ++i)
2329           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2330         V = ConstantVector::get(Elts);
2331       } else {
2332         V = UndefValue::get(CurTy);
2333       }
2334       break;
2335     }
2336     case bitc::CST_CODE_STRING:    // STRING: [values]
2337     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2338       if (Record.empty())
2339         return error("Invalid record");
2340
2341       SmallString<16> Elts(Record.begin(), Record.end());
2342       V = ConstantDataArray::getString(Context, Elts,
2343                                        BitCode == bitc::CST_CODE_CSTRING);
2344       break;
2345     }
2346     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2347       if (Record.empty())
2348         return error("Invalid record");
2349
2350       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2351       unsigned Size = Record.size();
2352
2353       if (EltTy->isIntegerTy(8)) {
2354         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2355         if (isa<VectorType>(CurTy))
2356           V = ConstantDataVector::get(Context, Elts);
2357         else
2358           V = ConstantDataArray::get(Context, Elts);
2359       } else if (EltTy->isIntegerTy(16)) {
2360         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2361         if (isa<VectorType>(CurTy))
2362           V = ConstantDataVector::get(Context, Elts);
2363         else
2364           V = ConstantDataArray::get(Context, Elts);
2365       } else if (EltTy->isIntegerTy(32)) {
2366         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2367         if (isa<VectorType>(CurTy))
2368           V = ConstantDataVector::get(Context, Elts);
2369         else
2370           V = ConstantDataArray::get(Context, Elts);
2371       } else if (EltTy->isIntegerTy(64)) {
2372         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2373         if (isa<VectorType>(CurTy))
2374           V = ConstantDataVector::get(Context, Elts);
2375         else
2376           V = ConstantDataArray::get(Context, Elts);
2377       } else if (EltTy->isFloatTy()) {
2378         SmallVector<float, 16> Elts(Size);
2379         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2380         if (isa<VectorType>(CurTy))
2381           V = ConstantDataVector::get(Context, Elts);
2382         else
2383           V = ConstantDataArray::get(Context, Elts);
2384       } else if (EltTy->isDoubleTy()) {
2385         SmallVector<double, 16> Elts(Size);
2386         std::transform(Record.begin(), Record.end(), Elts.begin(),
2387                        BitsToDouble);
2388         if (isa<VectorType>(CurTy))
2389           V = ConstantDataVector::get(Context, Elts);
2390         else
2391           V = ConstantDataArray::get(Context, Elts);
2392       } else {
2393         return error("Invalid type for value");
2394       }
2395       break;
2396     }
2397
2398     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2399       if (Record.size() < 3)
2400         return error("Invalid record");
2401       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2402       if (Opc < 0) {
2403         V = UndefValue::get(CurTy);  // Unknown binop.
2404       } else {
2405         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2406         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2407         unsigned Flags = 0;
2408         if (Record.size() >= 4) {
2409           if (Opc == Instruction::Add ||
2410               Opc == Instruction::Sub ||
2411               Opc == Instruction::Mul ||
2412               Opc == Instruction::Shl) {
2413             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2414               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2415             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2416               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2417           } else if (Opc == Instruction::SDiv ||
2418                      Opc == Instruction::UDiv ||
2419                      Opc == Instruction::LShr ||
2420                      Opc == Instruction::AShr) {
2421             if (Record[3] & (1 << bitc::PEO_EXACT))
2422               Flags |= SDivOperator::IsExact;
2423           }
2424         }
2425         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2426       }
2427       break;
2428     }
2429     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2430       if (Record.size() < 3)
2431         return error("Invalid record");
2432       int Opc = getDecodedCastOpcode(Record[0]);
2433       if (Opc < 0) {
2434         V = UndefValue::get(CurTy);  // Unknown cast.
2435       } else {
2436         Type *OpTy = getTypeByID(Record[1]);
2437         if (!OpTy)
2438           return error("Invalid record");
2439         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2440         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2441         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2442       }
2443       break;
2444     }
2445     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2446     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2447       unsigned OpNum = 0;
2448       Type *PointeeType = nullptr;
2449       if (Record.size() % 2)
2450         PointeeType = getTypeByID(Record[OpNum++]);
2451       SmallVector<Constant*, 16> Elts;
2452       while (OpNum != Record.size()) {
2453         Type *ElTy = getTypeByID(Record[OpNum++]);
2454         if (!ElTy)
2455           return error("Invalid record");
2456         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2457       }
2458
2459       if (PointeeType &&
2460           PointeeType !=
2461               cast<SequentialType>(Elts[0]->getType()->getScalarType())
2462                   ->getElementType())
2463         return error("Explicit gep operator type does not match pointee type "
2464                      "of pointer operand");
2465
2466       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2467       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2468                                          BitCode ==
2469                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
2470       break;
2471     }
2472     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2473       if (Record.size() < 3)
2474         return error("Invalid record");
2475
2476       Type *SelectorTy = Type::getInt1Ty(Context);
2477
2478       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2479       // vector. Otherwise, it must be a single bit.
2480       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2481         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2482                                      VTy->getNumElements());
2483
2484       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2485                                                               SelectorTy),
2486                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2487                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2488       break;
2489     }
2490     case bitc::CST_CODE_CE_EXTRACTELT
2491         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2492       if (Record.size() < 3)
2493         return error("Invalid record");
2494       VectorType *OpTy =
2495         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2496       if (!OpTy)
2497         return error("Invalid record");
2498       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2499       Constant *Op1 = nullptr;
2500       if (Record.size() == 4) {
2501         Type *IdxTy = getTypeByID(Record[2]);
2502         if (!IdxTy)
2503           return error("Invalid record");
2504         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2505       } else // TODO: Remove with llvm 4.0
2506         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2507       if (!Op1)
2508         return error("Invalid record");
2509       V = ConstantExpr::getExtractElement(Op0, Op1);
2510       break;
2511     }
2512     case bitc::CST_CODE_CE_INSERTELT
2513         : { // CE_INSERTELT: [opval, opval, opty, opval]
2514       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2515       if (Record.size() < 3 || !OpTy)
2516         return error("Invalid record");
2517       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2518       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2519                                                   OpTy->getElementType());
2520       Constant *Op2 = nullptr;
2521       if (Record.size() == 4) {
2522         Type *IdxTy = getTypeByID(Record[2]);
2523         if (!IdxTy)
2524           return error("Invalid record");
2525         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2526       } else // TODO: Remove with llvm 4.0
2527         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2528       if (!Op2)
2529         return error("Invalid record");
2530       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2531       break;
2532     }
2533     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2534       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2535       if (Record.size() < 3 || !OpTy)
2536         return error("Invalid record");
2537       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2538       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2539       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2540                                                  OpTy->getNumElements());
2541       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2542       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2543       break;
2544     }
2545     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2546       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2547       VectorType *OpTy =
2548         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2549       if (Record.size() < 4 || !RTy || !OpTy)
2550         return error("Invalid record");
2551       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2552       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2553       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2554                                                  RTy->getNumElements());
2555       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2556       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2557       break;
2558     }
2559     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2560       if (Record.size() < 4)
2561         return error("Invalid record");
2562       Type *OpTy = getTypeByID(Record[0]);
2563       if (!OpTy)
2564         return error("Invalid record");
2565       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2566       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2567
2568       if (OpTy->isFPOrFPVectorTy())
2569         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2570       else
2571         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2572       break;
2573     }
2574     // This maintains backward compatibility, pre-asm dialect keywords.
2575     // FIXME: Remove with the 4.0 release.
2576     case bitc::CST_CODE_INLINEASM_OLD: {
2577       if (Record.size() < 2)
2578         return error("Invalid record");
2579       std::string AsmStr, ConstrStr;
2580       bool HasSideEffects = Record[0] & 1;
2581       bool IsAlignStack = Record[0] >> 1;
2582       unsigned AsmStrSize = Record[1];
2583       if (2+AsmStrSize >= Record.size())
2584         return error("Invalid record");
2585       unsigned ConstStrSize = Record[2+AsmStrSize];
2586       if (3+AsmStrSize+ConstStrSize > Record.size())
2587         return error("Invalid record");
2588
2589       for (unsigned i = 0; i != AsmStrSize; ++i)
2590         AsmStr += (char)Record[2+i];
2591       for (unsigned i = 0; i != ConstStrSize; ++i)
2592         ConstrStr += (char)Record[3+AsmStrSize+i];
2593       PointerType *PTy = cast<PointerType>(CurTy);
2594       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2595                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2596       break;
2597     }
2598     // This version adds support for the asm dialect keywords (e.g.,
2599     // inteldialect).
2600     case bitc::CST_CODE_INLINEASM: {
2601       if (Record.size() < 2)
2602         return error("Invalid record");
2603       std::string AsmStr, ConstrStr;
2604       bool HasSideEffects = Record[0] & 1;
2605       bool IsAlignStack = (Record[0] >> 1) & 1;
2606       unsigned AsmDialect = Record[0] >> 2;
2607       unsigned AsmStrSize = Record[1];
2608       if (2+AsmStrSize >= Record.size())
2609         return error("Invalid record");
2610       unsigned ConstStrSize = Record[2+AsmStrSize];
2611       if (3+AsmStrSize+ConstStrSize > Record.size())
2612         return error("Invalid record");
2613
2614       for (unsigned i = 0; i != AsmStrSize; ++i)
2615         AsmStr += (char)Record[2+i];
2616       for (unsigned i = 0; i != ConstStrSize; ++i)
2617         ConstrStr += (char)Record[3+AsmStrSize+i];
2618       PointerType *PTy = cast<PointerType>(CurTy);
2619       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2620                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2621                          InlineAsm::AsmDialect(AsmDialect));
2622       break;
2623     }
2624     case bitc::CST_CODE_BLOCKADDRESS:{
2625       if (Record.size() < 3)
2626         return error("Invalid record");
2627       Type *FnTy = getTypeByID(Record[0]);
2628       if (!FnTy)
2629         return error("Invalid record");
2630       Function *Fn =
2631         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2632       if (!Fn)
2633         return error("Invalid record");
2634
2635       // Don't let Fn get dematerialized.
2636       BlockAddressesTaken.insert(Fn);
2637
2638       // If the function is already parsed we can insert the block address right
2639       // away.
2640       BasicBlock *BB;
2641       unsigned BBID = Record[2];
2642       if (!BBID)
2643         // Invalid reference to entry block.
2644         return error("Invalid ID");
2645       if (!Fn->empty()) {
2646         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2647         for (size_t I = 0, E = BBID; I != E; ++I) {
2648           if (BBI == BBE)
2649             return error("Invalid ID");
2650           ++BBI;
2651         }
2652         BB = BBI;
2653       } else {
2654         // Otherwise insert a placeholder and remember it so it can be inserted
2655         // when the function is parsed.
2656         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2657         if (FwdBBs.empty())
2658           BasicBlockFwdRefQueue.push_back(Fn);
2659         if (FwdBBs.size() < BBID + 1)
2660           FwdBBs.resize(BBID + 1);
2661         if (!FwdBBs[BBID])
2662           FwdBBs[BBID] = BasicBlock::Create(Context);
2663         BB = FwdBBs[BBID];
2664       }
2665       V = BlockAddress::get(Fn, BB);
2666       break;
2667     }
2668     }
2669
2670     if (ValueList.assignValue(V, NextCstNo))
2671       return error("Invalid forward reference");
2672     ++NextCstNo;
2673   }
2674 }
2675
2676 std::error_code BitcodeReader::parseUseLists() {
2677   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2678     return error("Invalid record");
2679
2680   // Read all the records.
2681   SmallVector<uint64_t, 64> Record;
2682   while (1) {
2683     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2684
2685     switch (Entry.Kind) {
2686     case BitstreamEntry::SubBlock: // Handled for us already.
2687     case BitstreamEntry::Error:
2688       return error("Malformed block");
2689     case BitstreamEntry::EndBlock:
2690       return std::error_code();
2691     case BitstreamEntry::Record:
2692       // The interesting case.
2693       break;
2694     }
2695
2696     // Read a use list record.
2697     Record.clear();
2698     bool IsBB = false;
2699     switch (Stream.readRecord(Entry.ID, Record)) {
2700     default:  // Default behavior: unknown type.
2701       break;
2702     case bitc::USELIST_CODE_BB:
2703       IsBB = true;
2704       // fallthrough
2705     case bitc::USELIST_CODE_DEFAULT: {
2706       unsigned RecordLength = Record.size();
2707       if (RecordLength < 3)
2708         // Records should have at least an ID and two indexes.
2709         return error("Invalid record");
2710       unsigned ID = Record.back();
2711       Record.pop_back();
2712
2713       Value *V;
2714       if (IsBB) {
2715         assert(ID < FunctionBBs.size() && "Basic block not found");
2716         V = FunctionBBs[ID];
2717       } else
2718         V = ValueList[ID];
2719       unsigned NumUses = 0;
2720       SmallDenseMap<const Use *, unsigned, 16> Order;
2721       for (const Use &U : V->uses()) {
2722         if (++NumUses > Record.size())
2723           break;
2724         Order[&U] = Record[NumUses - 1];
2725       }
2726       if (Order.size() != Record.size() || NumUses > Record.size())
2727         // Mismatches can happen if the functions are being materialized lazily
2728         // (out-of-order), or a value has been upgraded.
2729         break;
2730
2731       V->sortUseList([&](const Use &L, const Use &R) {
2732         return Order.lookup(&L) < Order.lookup(&R);
2733       });
2734       break;
2735     }
2736     }
2737   }
2738 }
2739
2740 /// When we see the block for metadata, remember where it is and then skip it.
2741 /// This lets us lazily deserialize the metadata.
2742 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2743   // Save the current stream state.
2744   uint64_t CurBit = Stream.GetCurrentBitNo();
2745   DeferredMetadataInfo.push_back(CurBit);
2746
2747   // Skip over the block for now.
2748   if (Stream.SkipBlock())
2749     return error("Invalid record");
2750   return std::error_code();
2751 }
2752
2753 std::error_code BitcodeReader::materializeMetadata() {
2754   for (uint64_t BitPos : DeferredMetadataInfo) {
2755     // Move the bit stream to the saved position.
2756     Stream.JumpToBit(BitPos);
2757     if (std::error_code EC = parseMetadata())
2758       return EC;
2759   }
2760   DeferredMetadataInfo.clear();
2761   return std::error_code();
2762 }
2763
2764 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2765
2766 /// When we see the block for a function body, remember where it is and then
2767 /// skip it.  This lets us lazily deserialize the functions.
2768 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2769   // Get the function we are talking about.
2770   if (FunctionsWithBodies.empty())
2771     return error("Insufficient function protos");
2772
2773   Function *Fn = FunctionsWithBodies.back();
2774   FunctionsWithBodies.pop_back();
2775
2776   // Save the current stream state.
2777   uint64_t CurBit = Stream.GetCurrentBitNo();
2778   DeferredFunctionInfo[Fn] = CurBit;
2779
2780   // Skip over the function block for now.
2781   if (Stream.SkipBlock())
2782     return error("Invalid record");
2783   return std::error_code();
2784 }
2785
2786 std::error_code BitcodeReader::globalCleanup() {
2787   // Patch the initializers for globals and aliases up.
2788   resolveGlobalAndAliasInits();
2789   if (!GlobalInits.empty() || !AliasInits.empty())
2790     return error("Malformed global initializer set");
2791
2792   // Look for intrinsic functions which need to be upgraded at some point
2793   for (Function &F : *TheModule) {
2794     Function *NewFn;
2795     if (UpgradeIntrinsicFunction(&F, NewFn))
2796       UpgradedIntrinsics[&F] = NewFn;
2797   }
2798
2799   // Look for global variables which need to be renamed.
2800   for (GlobalVariable &GV : TheModule->globals())
2801     UpgradeGlobalVariable(&GV);
2802
2803   // Force deallocation of memory for these vectors to favor the client that
2804   // want lazy deserialization.
2805   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2806   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2807   return std::error_code();
2808 }
2809
2810 std::error_code BitcodeReader::parseModule(bool Resume,
2811                                            bool ShouldLazyLoadMetadata) {
2812   if (Resume)
2813     Stream.JumpToBit(NextUnreadBit);
2814   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2815     return error("Invalid record");
2816
2817   SmallVector<uint64_t, 64> Record;
2818   std::vector<std::string> SectionTable;
2819   std::vector<std::string> GCTable;
2820
2821   // Read all the records for this module.
2822   while (1) {
2823     BitstreamEntry Entry = Stream.advance();
2824
2825     switch (Entry.Kind) {
2826     case BitstreamEntry::Error:
2827       return error("Malformed block");
2828     case BitstreamEntry::EndBlock:
2829       return globalCleanup();
2830
2831     case BitstreamEntry::SubBlock:
2832       switch (Entry.ID) {
2833       default:  // Skip unknown content.
2834         if (Stream.SkipBlock())
2835           return error("Invalid record");
2836         break;
2837       case bitc::BLOCKINFO_BLOCK_ID:
2838         if (Stream.ReadBlockInfoBlock())
2839           return error("Malformed block");
2840         break;
2841       case bitc::PARAMATTR_BLOCK_ID:
2842         if (std::error_code EC = parseAttributeBlock())
2843           return EC;
2844         break;
2845       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2846         if (std::error_code EC = parseAttributeGroupBlock())
2847           return EC;
2848         break;
2849       case bitc::TYPE_BLOCK_ID_NEW:
2850         if (std::error_code EC = parseTypeTable())
2851           return EC;
2852         break;
2853       case bitc::VALUE_SYMTAB_BLOCK_ID:
2854         if (std::error_code EC = parseValueSymbolTable())
2855           return EC;
2856         SeenValueSymbolTable = true;
2857         break;
2858       case bitc::CONSTANTS_BLOCK_ID:
2859         if (std::error_code EC = parseConstants())
2860           return EC;
2861         if (std::error_code EC = resolveGlobalAndAliasInits())
2862           return EC;
2863         break;
2864       case bitc::METADATA_BLOCK_ID:
2865         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2866           if (std::error_code EC = rememberAndSkipMetadata())
2867             return EC;
2868           break;
2869         }
2870         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2871         if (std::error_code EC = parseMetadata())
2872           return EC;
2873         break;
2874       case bitc::FUNCTION_BLOCK_ID:
2875         // If this is the first function body we've seen, reverse the
2876         // FunctionsWithBodies list.
2877         if (!SeenFirstFunctionBody) {
2878           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2879           if (std::error_code EC = globalCleanup())
2880             return EC;
2881           SeenFirstFunctionBody = true;
2882         }
2883
2884         if (std::error_code EC = rememberAndSkipFunctionBody())
2885           return EC;
2886         // Suspend parsing when we reach the function bodies. Subsequent
2887         // materialization calls will resume it when necessary. If the bitcode
2888         // file is old, the symbol table will be at the end instead and will not
2889         // have been seen yet. In this case, just finish the parse now.
2890         if (SeenValueSymbolTable) {
2891           NextUnreadBit = Stream.GetCurrentBitNo();
2892           return std::error_code();
2893         }
2894         break;
2895       case bitc::USELIST_BLOCK_ID:
2896         if (std::error_code EC = parseUseLists())
2897           return EC;
2898         break;
2899       }
2900       continue;
2901
2902     case BitstreamEntry::Record:
2903       // The interesting case.
2904       break;
2905     }
2906
2907
2908     // Read a record.
2909     switch (Stream.readRecord(Entry.ID, Record)) {
2910     default: break;  // Default behavior, ignore unknown content.
2911     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2912       if (Record.size() < 1)
2913         return error("Invalid record");
2914       // Only version #0 and #1 are supported so far.
2915       unsigned module_version = Record[0];
2916       switch (module_version) {
2917         default:
2918           return error("Invalid value");
2919         case 0:
2920           UseRelativeIDs = false;
2921           break;
2922         case 1:
2923           UseRelativeIDs = true;
2924           break;
2925       }
2926       break;
2927     }
2928     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2929       std::string S;
2930       if (convertToString(Record, 0, S))
2931         return error("Invalid record");
2932       TheModule->setTargetTriple(S);
2933       break;
2934     }
2935     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2936       std::string S;
2937       if (convertToString(Record, 0, S))
2938         return error("Invalid record");
2939       TheModule->setDataLayout(S);
2940       break;
2941     }
2942     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2943       std::string S;
2944       if (convertToString(Record, 0, S))
2945         return error("Invalid record");
2946       TheModule->setModuleInlineAsm(S);
2947       break;
2948     }
2949     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2950       // FIXME: Remove in 4.0.
2951       std::string S;
2952       if (convertToString(Record, 0, S))
2953         return error("Invalid record");
2954       // Ignore value.
2955       break;
2956     }
2957     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2958       std::string S;
2959       if (convertToString(Record, 0, S))
2960         return error("Invalid record");
2961       SectionTable.push_back(S);
2962       break;
2963     }
2964     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2965       std::string S;
2966       if (convertToString(Record, 0, S))
2967         return error("Invalid record");
2968       GCTable.push_back(S);
2969       break;
2970     }
2971     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2972       if (Record.size() < 2)
2973         return error("Invalid record");
2974       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2975       unsigned ComdatNameSize = Record[1];
2976       std::string ComdatName;
2977       ComdatName.reserve(ComdatNameSize);
2978       for (unsigned i = 0; i != ComdatNameSize; ++i)
2979         ComdatName += (char)Record[2 + i];
2980       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2981       C->setSelectionKind(SK);
2982       ComdatList.push_back(C);
2983       break;
2984     }
2985     // GLOBALVAR: [pointer type, isconst, initid,
2986     //             linkage, alignment, section, visibility, threadlocal,
2987     //             unnamed_addr, externally_initialized, dllstorageclass,
2988     //             comdat]
2989     case bitc::MODULE_CODE_GLOBALVAR: {
2990       if (Record.size() < 6)
2991         return error("Invalid record");
2992       Type *Ty = getTypeByID(Record[0]);
2993       if (!Ty)
2994         return error("Invalid record");
2995       bool isConstant = Record[1] & 1;
2996       bool explicitType = Record[1] & 2;
2997       unsigned AddressSpace;
2998       if (explicitType) {
2999         AddressSpace = Record[1] >> 2;
3000       } else {
3001         if (!Ty->isPointerTy())
3002           return error("Invalid type for value");
3003         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3004         Ty = cast<PointerType>(Ty)->getElementType();
3005       }
3006
3007       uint64_t RawLinkage = Record[3];
3008       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3009       unsigned Alignment;
3010       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3011         return EC;
3012       std::string Section;
3013       if (Record[5]) {
3014         if (Record[5]-1 >= SectionTable.size())
3015           return error("Invalid ID");
3016         Section = SectionTable[Record[5]-1];
3017       }
3018       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3019       // Local linkage must have default visibility.
3020       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3021         // FIXME: Change to an error if non-default in 4.0.
3022         Visibility = getDecodedVisibility(Record[6]);
3023
3024       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3025       if (Record.size() > 7)
3026         TLM = getDecodedThreadLocalMode(Record[7]);
3027
3028       bool UnnamedAddr = false;
3029       if (Record.size() > 8)
3030         UnnamedAddr = Record[8];
3031
3032       bool ExternallyInitialized = false;
3033       if (Record.size() > 9)
3034         ExternallyInitialized = Record[9];
3035
3036       GlobalVariable *NewGV =
3037         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3038                            TLM, AddressSpace, ExternallyInitialized);
3039       NewGV->setAlignment(Alignment);
3040       if (!Section.empty())
3041         NewGV->setSection(Section);
3042       NewGV->setVisibility(Visibility);
3043       NewGV->setUnnamedAddr(UnnamedAddr);
3044
3045       if (Record.size() > 10)
3046         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3047       else
3048         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3049
3050       ValueList.push_back(NewGV);
3051
3052       // Remember which value to use for the global initializer.
3053       if (unsigned InitID = Record[2])
3054         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3055
3056       if (Record.size() > 11) {
3057         if (unsigned ComdatID = Record[11]) {
3058           if (ComdatID > ComdatList.size())
3059             return error("Invalid global variable comdat ID");
3060           NewGV->setComdat(ComdatList[ComdatID - 1]);
3061         }
3062       } else if (hasImplicitComdat(RawLinkage)) {
3063         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3064       }
3065       break;
3066     }
3067     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
3068     //             alignment, section, visibility, gc, unnamed_addr,
3069     //             prologuedata, dllstorageclass, comdat, prefixdata]
3070     case bitc::MODULE_CODE_FUNCTION: {
3071       if (Record.size() < 8)
3072         return error("Invalid record");
3073       Type *Ty = getTypeByID(Record[0]);
3074       if (!Ty)
3075         return error("Invalid record");
3076       if (auto *PTy = dyn_cast<PointerType>(Ty))
3077         Ty = PTy->getElementType();
3078       auto *FTy = dyn_cast<FunctionType>(Ty);
3079       if (!FTy)
3080         return error("Invalid type for value");
3081
3082       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3083                                         "", TheModule);
3084
3085       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3086       bool isProto = Record[2];
3087       uint64_t RawLinkage = Record[3];
3088       Func->setLinkage(getDecodedLinkage(RawLinkage));
3089       Func->setAttributes(getAttributes(Record[4]));
3090
3091       unsigned Alignment;
3092       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3093         return EC;
3094       Func->setAlignment(Alignment);
3095       if (Record[6]) {
3096         if (Record[6]-1 >= SectionTable.size())
3097           return error("Invalid ID");
3098         Func->setSection(SectionTable[Record[6]-1]);
3099       }
3100       // Local linkage must have default visibility.
3101       if (!Func->hasLocalLinkage())
3102         // FIXME: Change to an error if non-default in 4.0.
3103         Func->setVisibility(getDecodedVisibility(Record[7]));
3104       if (Record.size() > 8 && Record[8]) {
3105         if (Record[8]-1 >= GCTable.size())
3106           return error("Invalid ID");
3107         Func->setGC(GCTable[Record[8]-1].c_str());
3108       }
3109       bool UnnamedAddr = false;
3110       if (Record.size() > 9)
3111         UnnamedAddr = Record[9];
3112       Func->setUnnamedAddr(UnnamedAddr);
3113       if (Record.size() > 10 && Record[10] != 0)
3114         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3115
3116       if (Record.size() > 11)
3117         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3118       else
3119         upgradeDLLImportExportLinkage(Func, RawLinkage);
3120
3121       if (Record.size() > 12) {
3122         if (unsigned ComdatID = Record[12]) {
3123           if (ComdatID > ComdatList.size())
3124             return error("Invalid function comdat ID");
3125           Func->setComdat(ComdatList[ComdatID - 1]);
3126         }
3127       } else if (hasImplicitComdat(RawLinkage)) {
3128         Func->setComdat(reinterpret_cast<Comdat *>(1));
3129       }
3130
3131       if (Record.size() > 13 && Record[13] != 0)
3132         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3133
3134       if (Record.size() > 14 && Record[14] != 0)
3135         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3136
3137       ValueList.push_back(Func);
3138
3139       // If this is a function with a body, remember the prototype we are
3140       // creating now, so that we can match up the body with them later.
3141       if (!isProto) {
3142         Func->setIsMaterializable(true);
3143         FunctionsWithBodies.push_back(Func);
3144         DeferredFunctionInfo[Func] = 0;
3145       }
3146       break;
3147     }
3148     // ALIAS: [alias type, aliasee val#, linkage]
3149     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3150     case bitc::MODULE_CODE_ALIAS: {
3151       if (Record.size() < 3)
3152         return error("Invalid record");
3153       Type *Ty = getTypeByID(Record[0]);
3154       if (!Ty)
3155         return error("Invalid record");
3156       auto *PTy = dyn_cast<PointerType>(Ty);
3157       if (!PTy)
3158         return error("Invalid type for value");
3159
3160       auto *NewGA =
3161           GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3162       // Old bitcode files didn't have visibility field.
3163       // Local linkage must have default visibility.
3164       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3165         // FIXME: Change to an error if non-default in 4.0.
3166         NewGA->setVisibility(getDecodedVisibility(Record[3]));
3167       if (Record.size() > 4)
3168         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3169       else
3170         upgradeDLLImportExportLinkage(NewGA, Record[2]);
3171       if (Record.size() > 5)
3172         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3173       if (Record.size() > 6)
3174         NewGA->setUnnamedAddr(Record[6]);
3175       ValueList.push_back(NewGA);
3176       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3177       break;
3178     }
3179     /// MODULE_CODE_PURGEVALS: [numvals]
3180     case bitc::MODULE_CODE_PURGEVALS:
3181       // Trim down the value list to the specified size.
3182       if (Record.size() < 1 || Record[0] > ValueList.size())
3183         return error("Invalid record");
3184       ValueList.shrinkTo(Record[0]);
3185       break;
3186     }
3187     Record.clear();
3188   }
3189 }
3190
3191 std::error_code
3192 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3193                                 Module *M, bool ShouldLazyLoadMetadata) {
3194   TheModule = M;
3195
3196   if (std::error_code EC = initStream(std::move(Streamer)))
3197     return EC;
3198
3199   // Sniff for the signature.
3200   if (Stream.Read(8) != 'B' ||
3201       Stream.Read(8) != 'C' ||
3202       Stream.Read(4) != 0x0 ||
3203       Stream.Read(4) != 0xC ||
3204       Stream.Read(4) != 0xE ||
3205       Stream.Read(4) != 0xD)
3206     return error("Invalid bitcode signature");
3207
3208   // We expect a number of well-defined blocks, though we don't necessarily
3209   // need to understand them all.
3210   while (1) {
3211     if (Stream.AtEndOfStream()) {
3212       // We didn't really read a proper Module.
3213       return error("Malformed IR file");
3214     }
3215
3216     BitstreamEntry Entry =
3217       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3218
3219     if (Entry.Kind != BitstreamEntry::SubBlock)
3220       return error("Malformed block");
3221
3222     if (Entry.ID == bitc::MODULE_BLOCK_ID)
3223       return parseModule(false, ShouldLazyLoadMetadata);
3224
3225     if (Stream.SkipBlock())
3226       return error("Invalid record");
3227   }
3228 }
3229
3230 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3231   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3232     return error("Invalid record");
3233
3234   SmallVector<uint64_t, 64> Record;
3235
3236   std::string Triple;
3237   // Read all the records for this module.
3238   while (1) {
3239     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3240
3241     switch (Entry.Kind) {
3242     case BitstreamEntry::SubBlock: // Handled for us already.
3243     case BitstreamEntry::Error:
3244       return error("Malformed block");
3245     case BitstreamEntry::EndBlock:
3246       return Triple;
3247     case BitstreamEntry::Record:
3248       // The interesting case.
3249       break;
3250     }
3251
3252     // Read a record.
3253     switch (Stream.readRecord(Entry.ID, Record)) {
3254     default: break;  // Default behavior, ignore unknown content.
3255     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3256       std::string S;
3257       if (convertToString(Record, 0, S))
3258         return error("Invalid record");
3259       Triple = S;
3260       break;
3261     }
3262     }
3263     Record.clear();
3264   }
3265   llvm_unreachable("Exit infinite loop");
3266 }
3267
3268 ErrorOr<std::string> BitcodeReader::parseTriple() {
3269   if (std::error_code EC = initStream(nullptr))
3270     return EC;
3271
3272   // Sniff for the signature.
3273   if (Stream.Read(8) != 'B' ||
3274       Stream.Read(8) != 'C' ||
3275       Stream.Read(4) != 0x0 ||
3276       Stream.Read(4) != 0xC ||
3277       Stream.Read(4) != 0xE ||
3278       Stream.Read(4) != 0xD)
3279     return error("Invalid bitcode signature");
3280
3281   // We expect a number of well-defined blocks, though we don't necessarily
3282   // need to understand them all.
3283   while (1) {
3284     BitstreamEntry Entry = Stream.advance();
3285
3286     switch (Entry.Kind) {
3287     case BitstreamEntry::Error:
3288       return error("Malformed block");
3289     case BitstreamEntry::EndBlock:
3290       return std::error_code();
3291
3292     case BitstreamEntry::SubBlock:
3293       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3294         return parseModuleTriple();
3295
3296       // Ignore other sub-blocks.
3297       if (Stream.SkipBlock())
3298         return error("Malformed block");
3299       continue;
3300
3301     case BitstreamEntry::Record:
3302       Stream.skipRecord(Entry.ID);
3303       continue;
3304     }
3305   }
3306 }
3307
3308 /// Parse metadata attachments.
3309 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3310   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3311     return error("Invalid record");
3312
3313   SmallVector<uint64_t, 64> Record;
3314   while (1) {
3315     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3316
3317     switch (Entry.Kind) {
3318     case BitstreamEntry::SubBlock: // Handled for us already.
3319     case BitstreamEntry::Error:
3320       return error("Malformed block");
3321     case BitstreamEntry::EndBlock:
3322       return std::error_code();
3323     case BitstreamEntry::Record:
3324       // The interesting case.
3325       break;
3326     }
3327
3328     // Read a metadata attachment record.
3329     Record.clear();
3330     switch (Stream.readRecord(Entry.ID, Record)) {
3331     default:  // Default behavior: ignore.
3332       break;
3333     case bitc::METADATA_ATTACHMENT: {
3334       unsigned RecordLength = Record.size();
3335       if (Record.empty())
3336         return error("Invalid record");
3337       if (RecordLength % 2 == 0) {
3338         // A function attachment.
3339         for (unsigned I = 0; I != RecordLength; I += 2) {
3340           auto K = MDKindMap.find(Record[I]);
3341           if (K == MDKindMap.end())
3342             return error("Invalid ID");
3343           Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3344           F.setMetadata(K->second, cast<MDNode>(MD));
3345         }
3346         continue;
3347       }
3348
3349       // An instruction attachment.
3350       Instruction *Inst = InstructionList[Record[0]];
3351       for (unsigned i = 1; i != RecordLength; i = i+2) {
3352         unsigned Kind = Record[i];
3353         DenseMap<unsigned, unsigned>::iterator I =
3354           MDKindMap.find(Kind);
3355         if (I == MDKindMap.end())
3356           return error("Invalid ID");
3357         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3358         if (isa<LocalAsMetadata>(Node))
3359           // Drop the attachment.  This used to be legal, but there's no
3360           // upgrade path.
3361           break;
3362         Inst->setMetadata(I->second, cast<MDNode>(Node));
3363         if (I->second == LLVMContext::MD_tbaa)
3364           InstsWithTBAATag.push_back(Inst);
3365       }
3366       break;
3367     }
3368     }
3369   }
3370 }
3371
3372 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3373                                               Type *ValType, Type *PtrType) {
3374   if (!isa<PointerType>(PtrType))
3375     return error(DH, "Load/Store operand is not a pointer type");
3376   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3377
3378   if (ValType && ValType != ElemType)
3379     return error(DH, "Explicit load/store type does not match pointee type of "
3380                      "pointer operand");
3381   if (!PointerType::isLoadableOrStorableType(ElemType))
3382     return error(DH, "Cannot load/store from pointer");
3383   return std::error_code();
3384 }
3385
3386 /// Lazily parse the specified function body block.
3387 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3388   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3389     return error("Invalid record");
3390
3391   InstructionList.clear();
3392   unsigned ModuleValueListSize = ValueList.size();
3393   unsigned ModuleMDValueListSize = MDValueList.size();
3394
3395   // Add all the function arguments to the value table.
3396   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3397     ValueList.push_back(I);
3398
3399   unsigned NextValueNo = ValueList.size();
3400   BasicBlock *CurBB = nullptr;
3401   unsigned CurBBNo = 0;
3402
3403   DebugLoc LastLoc;
3404   auto getLastInstruction = [&]() -> Instruction * {
3405     if (CurBB && !CurBB->empty())
3406       return &CurBB->back();
3407     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3408              !FunctionBBs[CurBBNo - 1]->empty())
3409       return &FunctionBBs[CurBBNo - 1]->back();
3410     return nullptr;
3411   };
3412
3413   // Read all the records.
3414   SmallVector<uint64_t, 64> Record;
3415   while (1) {
3416     BitstreamEntry Entry = Stream.advance();
3417
3418     switch (Entry.Kind) {
3419     case BitstreamEntry::Error:
3420       return error("Malformed block");
3421     case BitstreamEntry::EndBlock:
3422       goto OutOfRecordLoop;
3423
3424     case BitstreamEntry::SubBlock:
3425       switch (Entry.ID) {
3426       default:  // Skip unknown content.
3427         if (Stream.SkipBlock())
3428           return error("Invalid record");
3429         break;
3430       case bitc::CONSTANTS_BLOCK_ID:
3431         if (std::error_code EC = parseConstants())
3432           return EC;
3433         NextValueNo = ValueList.size();
3434         break;
3435       case bitc::VALUE_SYMTAB_BLOCK_ID:
3436         if (std::error_code EC = parseValueSymbolTable())
3437           return EC;
3438         break;
3439       case bitc::METADATA_ATTACHMENT_ID:
3440         if (std::error_code EC = parseMetadataAttachment(*F))
3441           return EC;
3442         break;
3443       case bitc::METADATA_BLOCK_ID:
3444         if (std::error_code EC = parseMetadata())
3445           return EC;
3446         break;
3447       case bitc::USELIST_BLOCK_ID:
3448         if (std::error_code EC = parseUseLists())
3449           return EC;
3450         break;
3451       }
3452       continue;
3453
3454     case BitstreamEntry::Record:
3455       // The interesting case.
3456       break;
3457     }
3458
3459     // Read a record.
3460     Record.clear();
3461     Instruction *I = nullptr;
3462     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3463     switch (BitCode) {
3464     default: // Default behavior: reject
3465       return error("Invalid value");
3466     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3467       if (Record.size() < 1 || Record[0] == 0)
3468         return error("Invalid record");
3469       // Create all the basic blocks for the function.
3470       FunctionBBs.resize(Record[0]);
3471
3472       // See if anything took the address of blocks in this function.
3473       auto BBFRI = BasicBlockFwdRefs.find(F);
3474       if (BBFRI == BasicBlockFwdRefs.end()) {
3475         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3476           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3477       } else {
3478         auto &BBRefs = BBFRI->second;
3479         // Check for invalid basic block references.
3480         if (BBRefs.size() > FunctionBBs.size())
3481           return error("Invalid ID");
3482         assert(!BBRefs.empty() && "Unexpected empty array");
3483         assert(!BBRefs.front() && "Invalid reference to entry block");
3484         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3485              ++I)
3486           if (I < RE && BBRefs[I]) {
3487             BBRefs[I]->insertInto(F);
3488             FunctionBBs[I] = BBRefs[I];
3489           } else {
3490             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3491           }
3492
3493         // Erase from the table.
3494         BasicBlockFwdRefs.erase(BBFRI);
3495       }
3496
3497       CurBB = FunctionBBs[0];
3498       continue;
3499     }
3500
3501     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3502       // This record indicates that the last instruction is at the same
3503       // location as the previous instruction with a location.
3504       I = getLastInstruction();
3505
3506       if (!I)
3507         return error("Invalid record");
3508       I->setDebugLoc(LastLoc);
3509       I = nullptr;
3510       continue;
3511
3512     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3513       I = getLastInstruction();
3514       if (!I || Record.size() < 4)
3515         return error("Invalid record");
3516
3517       unsigned Line = Record[0], Col = Record[1];
3518       unsigned ScopeID = Record[2], IAID = Record[3];
3519
3520       MDNode *Scope = nullptr, *IA = nullptr;
3521       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3522       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3523       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3524       I->setDebugLoc(LastLoc);
3525       I = nullptr;
3526       continue;
3527     }
3528
3529     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3530       unsigned OpNum = 0;
3531       Value *LHS, *RHS;
3532       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3533           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3534           OpNum+1 > Record.size())
3535         return error("Invalid record");
3536
3537       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3538       if (Opc == -1)
3539         return error("Invalid record");
3540       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3541       InstructionList.push_back(I);
3542       if (OpNum < Record.size()) {
3543         if (Opc == Instruction::Add ||
3544             Opc == Instruction::Sub ||
3545             Opc == Instruction::Mul ||
3546             Opc == Instruction::Shl) {
3547           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3548             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3549           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3550             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3551         } else if (Opc == Instruction::SDiv ||
3552                    Opc == Instruction::UDiv ||
3553                    Opc == Instruction::LShr ||
3554                    Opc == Instruction::AShr) {
3555           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3556             cast<BinaryOperator>(I)->setIsExact(true);
3557         } else if (isa<FPMathOperator>(I)) {
3558           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3559           if (FMF.any())
3560             I->setFastMathFlags(FMF);
3561         }
3562
3563       }
3564       break;
3565     }
3566     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3567       unsigned OpNum = 0;
3568       Value *Op;
3569       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3570           OpNum+2 != Record.size())
3571         return error("Invalid record");
3572
3573       Type *ResTy = getTypeByID(Record[OpNum]);
3574       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3575       if (Opc == -1 || !ResTy)
3576         return error("Invalid record");
3577       Instruction *Temp = nullptr;
3578       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3579         if (Temp) {
3580           InstructionList.push_back(Temp);
3581           CurBB->getInstList().push_back(Temp);
3582         }
3583       } else {
3584         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3585       }
3586       InstructionList.push_back(I);
3587       break;
3588     }
3589     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3590     case bitc::FUNC_CODE_INST_GEP_OLD:
3591     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3592       unsigned OpNum = 0;
3593
3594       Type *Ty;
3595       bool InBounds;
3596
3597       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3598         InBounds = Record[OpNum++];
3599         Ty = getTypeByID(Record[OpNum++]);
3600       } else {
3601         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3602         Ty = nullptr;
3603       }
3604
3605       Value *BasePtr;
3606       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3607         return error("Invalid record");
3608
3609       if (!Ty)
3610         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3611                  ->getElementType();
3612       else if (Ty !=
3613                cast<SequentialType>(BasePtr->getType()->getScalarType())
3614                    ->getElementType())
3615         return error(
3616             "Explicit gep type does not match pointee type of pointer operand");
3617
3618       SmallVector<Value*, 16> GEPIdx;
3619       while (OpNum != Record.size()) {
3620         Value *Op;
3621         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3622           return error("Invalid record");
3623         GEPIdx.push_back(Op);
3624       }
3625
3626       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3627
3628       InstructionList.push_back(I);
3629       if (InBounds)
3630         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3631       break;
3632     }
3633
3634     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3635                                        // EXTRACTVAL: [opty, opval, n x indices]
3636       unsigned OpNum = 0;
3637       Value *Agg;
3638       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3639         return error("Invalid record");
3640
3641       unsigned RecSize = Record.size();
3642       if (OpNum == RecSize)
3643         return error("EXTRACTVAL: Invalid instruction with 0 indices");
3644
3645       SmallVector<unsigned, 4> EXTRACTVALIdx;
3646       Type *CurTy = Agg->getType();
3647       for (; OpNum != RecSize; ++OpNum) {
3648         bool IsArray = CurTy->isArrayTy();
3649         bool IsStruct = CurTy->isStructTy();
3650         uint64_t Index = Record[OpNum];
3651
3652         if (!IsStruct && !IsArray)
3653           return error("EXTRACTVAL: Invalid type");
3654         if ((unsigned)Index != Index)
3655           return error("Invalid value");
3656         if (IsStruct && Index >= CurTy->subtypes().size())
3657           return error("EXTRACTVAL: Invalid struct index");
3658         if (IsArray && Index >= CurTy->getArrayNumElements())
3659           return error("EXTRACTVAL: Invalid array index");
3660         EXTRACTVALIdx.push_back((unsigned)Index);
3661
3662         if (IsStruct)
3663           CurTy = CurTy->subtypes()[Index];
3664         else
3665           CurTy = CurTy->subtypes()[0];
3666       }
3667
3668       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3669       InstructionList.push_back(I);
3670       break;
3671     }
3672
3673     case bitc::FUNC_CODE_INST_INSERTVAL: {
3674                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3675       unsigned OpNum = 0;
3676       Value *Agg;
3677       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3678         return error("Invalid record");
3679       Value *Val;
3680       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3681         return error("Invalid record");
3682
3683       unsigned RecSize = Record.size();
3684       if (OpNum == RecSize)
3685         return error("INSERTVAL: Invalid instruction with 0 indices");
3686
3687       SmallVector<unsigned, 4> INSERTVALIdx;
3688       Type *CurTy = Agg->getType();
3689       for (; OpNum != RecSize; ++OpNum) {
3690         bool IsArray = CurTy->isArrayTy();
3691         bool IsStruct = CurTy->isStructTy();
3692         uint64_t Index = Record[OpNum];
3693
3694         if (!IsStruct && !IsArray)
3695           return error("INSERTVAL: Invalid type");
3696         if ((unsigned)Index != Index)
3697           return error("Invalid value");
3698         if (IsStruct && Index >= CurTy->subtypes().size())
3699           return error("INSERTVAL: Invalid struct index");
3700         if (IsArray && Index >= CurTy->getArrayNumElements())
3701           return error("INSERTVAL: Invalid array index");
3702
3703         INSERTVALIdx.push_back((unsigned)Index);
3704         if (IsStruct)
3705           CurTy = CurTy->subtypes()[Index];
3706         else
3707           CurTy = CurTy->subtypes()[0];
3708       }
3709
3710       if (CurTy != Val->getType())
3711         return error("Inserted value type doesn't match aggregate type");
3712
3713       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3714       InstructionList.push_back(I);
3715       break;
3716     }
3717
3718     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3719       // obsolete form of select
3720       // handles select i1 ... in old bitcode
3721       unsigned OpNum = 0;
3722       Value *TrueVal, *FalseVal, *Cond;
3723       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3724           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3725           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3726         return error("Invalid record");
3727
3728       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3729       InstructionList.push_back(I);
3730       break;
3731     }
3732
3733     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3734       // new form of select
3735       // handles select i1 or select [N x i1]
3736       unsigned OpNum = 0;
3737       Value *TrueVal, *FalseVal, *Cond;
3738       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3739           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3740           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3741         return error("Invalid record");
3742
3743       // select condition can be either i1 or [N x i1]
3744       if (VectorType* vector_type =
3745           dyn_cast<VectorType>(Cond->getType())) {
3746         // expect <n x i1>
3747         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3748           return error("Invalid type for value");
3749       } else {
3750         // expect i1
3751         if (Cond->getType() != Type::getInt1Ty(Context))
3752           return error("Invalid type for value");
3753       }
3754
3755       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3756       InstructionList.push_back(I);
3757       break;
3758     }
3759
3760     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3761       unsigned OpNum = 0;
3762       Value *Vec, *Idx;
3763       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3764           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3765         return error("Invalid record");
3766       if (!Vec->getType()->isVectorTy())
3767         return error("Invalid type for value");
3768       I = ExtractElementInst::Create(Vec, Idx);
3769       InstructionList.push_back(I);
3770       break;
3771     }
3772
3773     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3774       unsigned OpNum = 0;
3775       Value *Vec, *Elt, *Idx;
3776       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3777         return error("Invalid record");
3778       if (!Vec->getType()->isVectorTy())
3779         return error("Invalid type for value");
3780       if (popValue(Record, OpNum, NextValueNo,
3781                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3782           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3783         return error("Invalid record");
3784       I = InsertElementInst::Create(Vec, Elt, Idx);
3785       InstructionList.push_back(I);
3786       break;
3787     }
3788
3789     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3790       unsigned OpNum = 0;
3791       Value *Vec1, *Vec2, *Mask;
3792       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3793           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3794         return error("Invalid record");
3795
3796       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3797         return error("Invalid record");
3798       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3799         return error("Invalid type for value");
3800       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3801       InstructionList.push_back(I);
3802       break;
3803     }
3804
3805     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3806       // Old form of ICmp/FCmp returning bool
3807       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3808       // both legal on vectors but had different behaviour.
3809     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3810       // FCmp/ICmp returning bool or vector of bool
3811
3812       unsigned OpNum = 0;
3813       Value *LHS, *RHS;
3814       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3815           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3816         return error("Invalid record");
3817
3818       unsigned PredVal = Record[OpNum];
3819       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3820       FastMathFlags FMF;
3821       if (IsFP && Record.size() > OpNum+1)
3822         FMF = getDecodedFastMathFlags(Record[++OpNum]);
3823
3824       if (OpNum+1 != Record.size())
3825         return error("Invalid record");
3826
3827       if (LHS->getType()->isFPOrFPVectorTy())
3828         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3829       else
3830         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3831
3832       if (FMF.any())
3833         I->setFastMathFlags(FMF);
3834       InstructionList.push_back(I);
3835       break;
3836     }
3837
3838     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3839       {
3840         unsigned Size = Record.size();
3841         if (Size == 0) {
3842           I = ReturnInst::Create(Context);
3843           InstructionList.push_back(I);
3844           break;
3845         }
3846
3847         unsigned OpNum = 0;
3848         Value *Op = nullptr;
3849         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3850           return error("Invalid record");
3851         if (OpNum != Record.size())
3852           return error("Invalid record");
3853
3854         I = ReturnInst::Create(Context, Op);
3855         InstructionList.push_back(I);
3856         break;
3857       }
3858     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3859       if (Record.size() != 1 && Record.size() != 3)
3860         return error("Invalid record");
3861       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3862       if (!TrueDest)
3863         return error("Invalid record");
3864
3865       if (Record.size() == 1) {
3866         I = BranchInst::Create(TrueDest);
3867         InstructionList.push_back(I);
3868       }
3869       else {
3870         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3871         Value *Cond = getValue(Record, 2, NextValueNo,
3872                                Type::getInt1Ty(Context));
3873         if (!FalseDest || !Cond)
3874           return error("Invalid record");
3875         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3876         InstructionList.push_back(I);
3877       }
3878       break;
3879     }
3880     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3881       if (Record.size() != 1 && Record.size() != 2)
3882         return error("Invalid record");
3883       unsigned Idx = 0;
3884       Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
3885                                    Type::getTokenTy(Context), OC_CleanupPad);
3886       if (!CleanupPad)
3887         return error("Invalid record");
3888       BasicBlock *UnwindDest = nullptr;
3889       if (Record.size() == 2) {
3890         UnwindDest = getBasicBlock(Record[Idx++]);
3891         if (!UnwindDest)
3892           return error("Invalid record");
3893       }
3894
3895       I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
3896                                     UnwindDest);
3897       InstructionList.push_back(I);
3898       break;
3899     }
3900     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3901       if (Record.size() != 2)
3902         return error("Invalid record");
3903       unsigned Idx = 0;
3904       Value *CatchPad = getValue(Record, Idx++, NextValueNo,
3905                                  Type::getTokenTy(Context), OC_CatchPad);
3906       if (!CatchPad)
3907         return error("Invalid record");
3908       BasicBlock *BB = getBasicBlock(Record[Idx++]);
3909       if (!BB)
3910         return error("Invalid record");
3911
3912       I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
3913       InstructionList.push_back(I);
3914       break;
3915     }
3916     case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
3917       if (Record.size() < 3)
3918         return error("Invalid record");
3919       unsigned Idx = 0;
3920       BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
3921       if (!NormalBB)
3922         return error("Invalid record");
3923       BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
3924       if (!UnwindBB)
3925         return error("Invalid record");
3926       unsigned NumArgOperands = Record[Idx++];
3927       SmallVector<Value *, 2> Args;
3928       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3929         Value *Val;
3930         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3931           return error("Invalid record");
3932         Args.push_back(Val);
3933       }
3934       if (Record.size() != Idx)
3935         return error("Invalid record");
3936
3937       I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
3938       InstructionList.push_back(I);
3939       break;
3940     }
3941     case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
3942       if (Record.size() < 1)
3943         return error("Invalid record");
3944       unsigned Idx = 0;
3945       bool HasUnwindDest = !!Record[Idx++];
3946       BasicBlock *UnwindDest = nullptr;
3947       if (HasUnwindDest) {
3948         if (Idx == Record.size())
3949           return error("Invalid record");
3950         UnwindDest = getBasicBlock(Record[Idx++]);
3951         if (!UnwindDest)
3952           return error("Invalid record");
3953       }
3954       unsigned NumArgOperands = Record[Idx++];
3955       SmallVector<Value *, 2> Args;
3956       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3957         Value *Val;
3958         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3959           return error("Invalid record");
3960         Args.push_back(Val);
3961       }
3962       if (Record.size() != Idx)
3963         return error("Invalid record");
3964
3965       I = TerminatePadInst::Create(Context, UnwindDest, Args);
3966       InstructionList.push_back(I);
3967       break;
3968     }
3969     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
3970       if (Record.size() < 1)
3971         return error("Invalid record");
3972       unsigned Idx = 0;
3973       unsigned NumArgOperands = Record[Idx++];
3974       SmallVector<Value *, 2> Args;
3975       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3976         Value *Val;
3977         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3978           return error("Invalid record");
3979         Args.push_back(Val);
3980       }
3981       if (Record.size() != Idx)
3982         return error("Invalid record");
3983
3984       I = CleanupPadInst::Create(Context, Args);
3985       InstructionList.push_back(I);
3986       break;
3987     }
3988     case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
3989       if (Record.size() > 1)
3990         return error("Invalid record");
3991       BasicBlock *BB = nullptr;
3992       if (Record.size() == 1) {
3993         BB = getBasicBlock(Record[0]);
3994         if (!BB)
3995           return error("Invalid record");
3996       }
3997       I = CatchEndPadInst::Create(Context, BB);
3998       InstructionList.push_back(I);
3999       break;
4000     }
4001     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4002       // Check magic
4003       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4004         // "New" SwitchInst format with case ranges. The changes to write this
4005         // format were reverted but we still recognize bitcode that uses it.
4006         // Hopefully someday we will have support for case ranges and can use
4007         // this format again.
4008
4009         Type *OpTy = getTypeByID(Record[1]);
4010         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4011
4012         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4013         BasicBlock *Default = getBasicBlock(Record[3]);
4014         if (!OpTy || !Cond || !Default)
4015           return error("Invalid record");
4016
4017         unsigned NumCases = Record[4];
4018
4019         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4020         InstructionList.push_back(SI);
4021
4022         unsigned CurIdx = 5;
4023         for (unsigned i = 0; i != NumCases; ++i) {
4024           SmallVector<ConstantInt*, 1> CaseVals;
4025           unsigned NumItems = Record[CurIdx++];
4026           for (unsigned ci = 0; ci != NumItems; ++ci) {
4027             bool isSingleNumber = Record[CurIdx++];
4028
4029             APInt Low;
4030             unsigned ActiveWords = 1;
4031             if (ValueBitWidth > 64)
4032               ActiveWords = Record[CurIdx++];
4033             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4034                                 ValueBitWidth);
4035             CurIdx += ActiveWords;
4036
4037             if (!isSingleNumber) {
4038               ActiveWords = 1;
4039               if (ValueBitWidth > 64)
4040                 ActiveWords = Record[CurIdx++];
4041               APInt High = readWideAPInt(
4042                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4043               CurIdx += ActiveWords;
4044
4045               // FIXME: It is not clear whether values in the range should be
4046               // compared as signed or unsigned values. The partially
4047               // implemented changes that used this format in the past used
4048               // unsigned comparisons.
4049               for ( ; Low.ule(High); ++Low)
4050                 CaseVals.push_back(ConstantInt::get(Context, Low));
4051             } else
4052               CaseVals.push_back(ConstantInt::get(Context, Low));
4053           }
4054           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4055           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4056                  cve = CaseVals.end(); cvi != cve; ++cvi)
4057             SI->addCase(*cvi, DestBB);
4058         }
4059         I = SI;
4060         break;
4061       }
4062
4063       // Old SwitchInst format without case ranges.
4064
4065       if (Record.size() < 3 || (Record.size() & 1) == 0)
4066         return error("Invalid record");
4067       Type *OpTy = getTypeByID(Record[0]);
4068       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4069       BasicBlock *Default = getBasicBlock(Record[2]);
4070       if (!OpTy || !Cond || !Default)
4071         return error("Invalid record");
4072       unsigned NumCases = (Record.size()-3)/2;
4073       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4074       InstructionList.push_back(SI);
4075       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4076         ConstantInt *CaseVal =
4077           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4078         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4079         if (!CaseVal || !DestBB) {
4080           delete SI;
4081           return error("Invalid record");
4082         }
4083         SI->addCase(CaseVal, DestBB);
4084       }
4085       I = SI;
4086       break;
4087     }
4088     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4089       if (Record.size() < 2)
4090         return error("Invalid record");
4091       Type *OpTy = getTypeByID(Record[0]);
4092       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4093       if (!OpTy || !Address)
4094         return error("Invalid record");
4095       unsigned NumDests = Record.size()-2;
4096       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4097       InstructionList.push_back(IBI);
4098       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4099         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4100           IBI->addDestination(DestBB);
4101         } else {
4102           delete IBI;
4103           return error("Invalid record");
4104         }
4105       }
4106       I = IBI;
4107       break;
4108     }
4109
4110     case bitc::FUNC_CODE_INST_INVOKE: {
4111       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4112       if (Record.size() < 4)
4113         return error("Invalid record");
4114       unsigned OpNum = 0;
4115       AttributeSet PAL = getAttributes(Record[OpNum++]);
4116       unsigned CCInfo = Record[OpNum++];
4117       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4118       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4119
4120       FunctionType *FTy = nullptr;
4121       if (CCInfo >> 13 & 1 &&
4122           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4123         return error("Explicit invoke type is not a function type");
4124
4125       Value *Callee;
4126       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4127         return error("Invalid record");
4128
4129       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4130       if (!CalleeTy)
4131         return error("Callee is not a pointer");
4132       if (!FTy) {
4133         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4134         if (!FTy)
4135           return error("Callee is not of pointer to function type");
4136       } else if (CalleeTy->getElementType() != FTy)
4137         return error("Explicit invoke type does not match pointee type of "
4138                      "callee operand");
4139       if (Record.size() < FTy->getNumParams() + OpNum)
4140         return error("Insufficient operands to call");
4141
4142       SmallVector<Value*, 16> Ops;
4143       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4144         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4145                                FTy->getParamType(i)));
4146         if (!Ops.back())
4147           return error("Invalid record");
4148       }
4149
4150       if (!FTy->isVarArg()) {
4151         if (Record.size() != OpNum)
4152           return error("Invalid record");
4153       } else {
4154         // Read type/value pairs for varargs params.
4155         while (OpNum != Record.size()) {
4156           Value *Op;
4157           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4158             return error("Invalid record");
4159           Ops.push_back(Op);
4160         }
4161       }
4162
4163       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
4164       InstructionList.push_back(I);
4165       cast<InvokeInst>(I)
4166           ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4167       cast<InvokeInst>(I)->setAttributes(PAL);
4168       break;
4169     }
4170     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4171       unsigned Idx = 0;
4172       Value *Val = nullptr;
4173       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4174         return error("Invalid record");
4175       I = ResumeInst::Create(Val);
4176       InstructionList.push_back(I);
4177       break;
4178     }
4179     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4180       I = new UnreachableInst(Context);
4181       InstructionList.push_back(I);
4182       break;
4183     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4184       if (Record.size() < 1 || ((Record.size()-1)&1))
4185         return error("Invalid record");
4186       Type *Ty = getTypeByID(Record[0]);
4187       if (!Ty)
4188         return error("Invalid record");
4189
4190       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4191       InstructionList.push_back(PN);
4192
4193       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4194         Value *V;
4195         // With the new function encoding, it is possible that operands have
4196         // negative IDs (for forward references).  Use a signed VBR
4197         // representation to keep the encoding small.
4198         if (UseRelativeIDs)
4199           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4200         else
4201           V = getValue(Record, 1+i, NextValueNo, Ty);
4202         BasicBlock *BB = getBasicBlock(Record[2+i]);
4203         if (!V || !BB)
4204           return error("Invalid record");
4205         PN->addIncoming(V, BB);
4206       }
4207       I = PN;
4208       break;
4209     }
4210
4211     case bitc::FUNC_CODE_INST_LANDINGPAD:
4212     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4213       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4214       unsigned Idx = 0;
4215       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4216         if (Record.size() < 3)
4217           return error("Invalid record");
4218       } else {
4219         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4220         if (Record.size() < 4)
4221           return error("Invalid record");
4222       }
4223       Type *Ty = getTypeByID(Record[Idx++]);
4224       if (!Ty)
4225         return error("Invalid record");
4226       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4227         Value *PersFn = nullptr;
4228         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4229           return error("Invalid record");
4230
4231         if (!F->hasPersonalityFn())
4232           F->setPersonalityFn(cast<Constant>(PersFn));
4233         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4234           return error("Personality function mismatch");
4235       }
4236
4237       bool IsCleanup = !!Record[Idx++];
4238       unsigned NumClauses = Record[Idx++];
4239       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4240       LP->setCleanup(IsCleanup);
4241       for (unsigned J = 0; J != NumClauses; ++J) {
4242         LandingPadInst::ClauseType CT =
4243           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4244         Value *Val;
4245
4246         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4247           delete LP;
4248           return error("Invalid record");
4249         }
4250
4251         assert((CT != LandingPadInst::Catch ||
4252                 !isa<ArrayType>(Val->getType())) &&
4253                "Catch clause has a invalid type!");
4254         assert((CT != LandingPadInst::Filter ||
4255                 isa<ArrayType>(Val->getType())) &&
4256                "Filter clause has invalid type!");
4257         LP->addClause(cast<Constant>(Val));
4258       }
4259
4260       I = LP;
4261       InstructionList.push_back(I);
4262       break;
4263     }
4264
4265     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4266       if (Record.size() != 4)
4267         return error("Invalid record");
4268       uint64_t AlignRecord = Record[3];
4269       const uint64_t InAllocaMask = uint64_t(1) << 5;
4270       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4271       // Reserve bit 7 for SwiftError flag.
4272       // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4273       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4274       bool InAlloca = AlignRecord & InAllocaMask;
4275       Type *Ty = getTypeByID(Record[0]);
4276       if ((AlignRecord & ExplicitTypeMask) == 0) {
4277         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4278         if (!PTy)
4279           return error("Old-style alloca with a non-pointer type");
4280         Ty = PTy->getElementType();
4281       }
4282       Type *OpTy = getTypeByID(Record[1]);
4283       Value *Size = getFnValueByID(Record[2], OpTy);
4284       unsigned Align;
4285       if (std::error_code EC =
4286               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4287         return EC;
4288       }
4289       if (!Ty || !Size)
4290         return error("Invalid record");
4291       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4292       AI->setUsedWithInAlloca(InAlloca);
4293       I = AI;
4294       InstructionList.push_back(I);
4295       break;
4296     }
4297     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4298       unsigned OpNum = 0;
4299       Value *Op;
4300       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4301           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4302         return error("Invalid record");
4303
4304       Type *Ty = nullptr;
4305       if (OpNum + 3 == Record.size())
4306         Ty = getTypeByID(Record[OpNum++]);
4307       if (std::error_code EC =
4308               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4309         return EC;
4310       if (!Ty)
4311         Ty = cast<PointerType>(Op->getType())->getElementType();
4312
4313       unsigned Align;
4314       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4315         return EC;
4316       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4317
4318       InstructionList.push_back(I);
4319       break;
4320     }
4321     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4322        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4323       unsigned OpNum = 0;
4324       Value *Op;
4325       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4326           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4327         return error("Invalid record");
4328
4329       Type *Ty = nullptr;
4330       if (OpNum + 5 == Record.size())
4331         Ty = getTypeByID(Record[OpNum++]);
4332       if (std::error_code EC =
4333               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4334         return EC;
4335       if (!Ty)
4336         Ty = cast<PointerType>(Op->getType())->getElementType();
4337
4338       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4339       if (Ordering == NotAtomic || Ordering == Release ||
4340           Ordering == AcquireRelease)
4341         return error("Invalid record");
4342       if (Ordering != NotAtomic && Record[OpNum] == 0)
4343         return error("Invalid record");
4344       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4345
4346       unsigned Align;
4347       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4348         return EC;
4349       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4350
4351       InstructionList.push_back(I);
4352       break;
4353     }
4354     case bitc::FUNC_CODE_INST_STORE:
4355     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4356       unsigned OpNum = 0;
4357       Value *Val, *Ptr;
4358       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4359           (BitCode == bitc::FUNC_CODE_INST_STORE
4360                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4361                : popValue(Record, OpNum, NextValueNo,
4362                           cast<PointerType>(Ptr->getType())->getElementType(),
4363                           Val)) ||
4364           OpNum + 2 != Record.size())
4365         return error("Invalid record");
4366
4367       if (std::error_code EC = typeCheckLoadStoreInst(
4368               DiagnosticHandler, Val->getType(), Ptr->getType()))
4369         return EC;
4370       unsigned Align;
4371       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4372         return EC;
4373       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4374       InstructionList.push_back(I);
4375       break;
4376     }
4377     case bitc::FUNC_CODE_INST_STOREATOMIC:
4378     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4379       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4380       unsigned OpNum = 0;
4381       Value *Val, *Ptr;
4382       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4383           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4384                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4385                : popValue(Record, OpNum, NextValueNo,
4386                           cast<PointerType>(Ptr->getType())->getElementType(),
4387                           Val)) ||
4388           OpNum + 4 != Record.size())
4389         return error("Invalid record");
4390
4391       if (std::error_code EC = typeCheckLoadStoreInst(
4392               DiagnosticHandler, Val->getType(), Ptr->getType()))
4393         return EC;
4394       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4395       if (Ordering == NotAtomic || Ordering == Acquire ||
4396           Ordering == AcquireRelease)
4397         return error("Invalid record");
4398       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4399       if (Ordering != NotAtomic && Record[OpNum] == 0)
4400         return error("Invalid record");
4401
4402       unsigned Align;
4403       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4404         return EC;
4405       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4406       InstructionList.push_back(I);
4407       break;
4408     }
4409     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4410     case bitc::FUNC_CODE_INST_CMPXCHG: {
4411       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4412       //          failureordering?, isweak?]
4413       unsigned OpNum = 0;
4414       Value *Ptr, *Cmp, *New;
4415       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4416           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4417                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4418                : popValue(Record, OpNum, NextValueNo,
4419                           cast<PointerType>(Ptr->getType())->getElementType(),
4420                           Cmp)) ||
4421           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4422           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4423         return error("Invalid record");
4424       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4425       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4426         return error("Invalid record");
4427       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4428
4429       if (std::error_code EC = typeCheckLoadStoreInst(
4430               DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4431         return EC;
4432       AtomicOrdering FailureOrdering;
4433       if (Record.size() < 7)
4434         FailureOrdering =
4435             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4436       else
4437         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4438
4439       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4440                                 SynchScope);
4441       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4442
4443       if (Record.size() < 8) {
4444         // Before weak cmpxchgs existed, the instruction simply returned the
4445         // value loaded from memory, so bitcode files from that era will be
4446         // expecting the first component of a modern cmpxchg.
4447         CurBB->getInstList().push_back(I);
4448         I = ExtractValueInst::Create(I, 0);
4449       } else {
4450         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4451       }
4452
4453       InstructionList.push_back(I);
4454       break;
4455     }
4456     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4457       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4458       unsigned OpNum = 0;
4459       Value *Ptr, *Val;
4460       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4461           popValue(Record, OpNum, NextValueNo,
4462                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4463           OpNum+4 != Record.size())
4464         return error("Invalid record");
4465       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4466       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4467           Operation > AtomicRMWInst::LAST_BINOP)
4468         return error("Invalid record");
4469       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4470       if (Ordering == NotAtomic || Ordering == Unordered)
4471         return error("Invalid record");
4472       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4473       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4474       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4475       InstructionList.push_back(I);
4476       break;
4477     }
4478     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4479       if (2 != Record.size())
4480         return error("Invalid record");
4481       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4482       if (Ordering == NotAtomic || Ordering == Unordered ||
4483           Ordering == Monotonic)
4484         return error("Invalid record");
4485       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4486       I = new FenceInst(Context, Ordering, SynchScope);
4487       InstructionList.push_back(I);
4488       break;
4489     }
4490     case bitc::FUNC_CODE_INST_CALL: {
4491       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4492       if (Record.size() < 3)
4493         return error("Invalid record");
4494
4495       unsigned OpNum = 0;
4496       AttributeSet PAL = getAttributes(Record[OpNum++]);
4497       unsigned CCInfo = Record[OpNum++];
4498
4499       FunctionType *FTy = nullptr;
4500       if (CCInfo >> 15 & 1 &&
4501           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4502         return error("Explicit call type is not a function type");
4503
4504       Value *Callee;
4505       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4506         return error("Invalid record");
4507
4508       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4509       if (!OpTy)
4510         return error("Callee is not a pointer type");
4511       if (!FTy) {
4512         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4513         if (!FTy)
4514           return error("Callee is not of pointer to function type");
4515       } else if (OpTy->getElementType() != FTy)
4516         return error("Explicit call type does not match pointee type of "
4517                      "callee operand");
4518       if (Record.size() < FTy->getNumParams() + OpNum)
4519         return error("Insufficient operands to call");
4520
4521       SmallVector<Value*, 16> Args;
4522       // Read the fixed params.
4523       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4524         if (FTy->getParamType(i)->isLabelTy())
4525           Args.push_back(getBasicBlock(Record[OpNum]));
4526         else
4527           Args.push_back(getValue(Record, OpNum, NextValueNo,
4528                                   FTy->getParamType(i)));
4529         if (!Args.back())
4530           return error("Invalid record");
4531       }
4532
4533       // Read type/value pairs for varargs params.
4534       if (!FTy->isVarArg()) {
4535         if (OpNum != Record.size())
4536           return error("Invalid record");
4537       } else {
4538         while (OpNum != Record.size()) {
4539           Value *Op;
4540           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4541             return error("Invalid record");
4542           Args.push_back(Op);
4543         }
4544       }
4545
4546       I = CallInst::Create(FTy, Callee, Args);
4547       InstructionList.push_back(I);
4548       cast<CallInst>(I)->setCallingConv(
4549           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4550       CallInst::TailCallKind TCK = CallInst::TCK_None;
4551       if (CCInfo & 1)
4552         TCK = CallInst::TCK_Tail;
4553       if (CCInfo & (1 << 14))
4554         TCK = CallInst::TCK_MustTail;
4555       cast<CallInst>(I)->setTailCallKind(TCK);
4556       cast<CallInst>(I)->setAttributes(PAL);
4557       break;
4558     }
4559     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4560       if (Record.size() < 3)
4561         return error("Invalid record");
4562       Type *OpTy = getTypeByID(Record[0]);
4563       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4564       Type *ResTy = getTypeByID(Record[2]);
4565       if (!OpTy || !Op || !ResTy)
4566         return error("Invalid record");
4567       I = new VAArgInst(Op, ResTy);
4568       InstructionList.push_back(I);
4569       break;
4570     }
4571     }
4572
4573     // Add instruction to end of current BB.  If there is no current BB, reject
4574     // this file.
4575     if (!CurBB) {
4576       delete I;
4577       return error("Invalid instruction with no BB");
4578     }
4579     CurBB->getInstList().push_back(I);
4580
4581     // If this was a terminator instruction, move to the next block.
4582     if (isa<TerminatorInst>(I)) {
4583       ++CurBBNo;
4584       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4585     }
4586
4587     // Non-void values get registered in the value table for future use.
4588     if (I && !I->getType()->isVoidTy())
4589       if (ValueList.assignValue(I, NextValueNo++))
4590         return error("Invalid forward reference");
4591   }
4592
4593 OutOfRecordLoop:
4594
4595   // Check the function list for unresolved values.
4596   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4597     if (!A->getParent()) {
4598       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4599       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4600         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4601           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4602           delete A;
4603         }
4604       }
4605       return error("Never resolved value found in function");
4606     }
4607   }
4608
4609   // FIXME: Check for unresolved forward-declared metadata references
4610   // and clean up leaks.
4611
4612   // Trim the value list down to the size it was before we parsed this function.
4613   ValueList.shrinkTo(ModuleValueListSize);
4614   MDValueList.shrinkTo(ModuleMDValueListSize);
4615   std::vector<BasicBlock*>().swap(FunctionBBs);
4616   return std::error_code();
4617 }
4618
4619 /// Find the function body in the bitcode stream
4620 std::error_code BitcodeReader::findFunctionInStream(
4621     Function *F,
4622     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4623   while (DeferredFunctionInfoIterator->second == 0) {
4624     if (Stream.AtEndOfStream())
4625       return error("Could not find function in stream");
4626     // ParseModule will parse the next body in the stream and set its
4627     // position in the DeferredFunctionInfo map.
4628     if (std::error_code EC = parseModule(true))
4629       return EC;
4630   }
4631   return std::error_code();
4632 }
4633
4634 //===----------------------------------------------------------------------===//
4635 // GVMaterializer implementation
4636 //===----------------------------------------------------------------------===//
4637
4638 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4639
4640 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4641   if (std::error_code EC = materializeMetadata())
4642     return EC;
4643
4644   Function *F = dyn_cast<Function>(GV);
4645   // If it's not a function or is already material, ignore the request.
4646   if (!F || !F->isMaterializable())
4647     return std::error_code();
4648
4649   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4650   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4651   // If its position is recorded as 0, its body is somewhere in the stream
4652   // but we haven't seen it yet.
4653   if (DFII->second == 0)
4654     if (std::error_code EC = findFunctionInStream(F, DFII))
4655       return EC;
4656
4657   // Move the bit stream to the saved position of the deferred function body.
4658   Stream.JumpToBit(DFII->second);
4659
4660   if (std::error_code EC = parseFunctionBody(F))
4661     return EC;
4662   F->setIsMaterializable(false);
4663
4664   if (StripDebugInfo)
4665     stripDebugInfo(*F);
4666
4667   // Upgrade any old intrinsic calls in the function.
4668   for (auto &I : UpgradedIntrinsics) {
4669     for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4670       User *U = *UI;
4671       ++UI;
4672       if (CallInst *CI = dyn_cast<CallInst>(U))
4673         UpgradeIntrinsicCall(CI, I.second);
4674     }
4675   }
4676
4677   // Bring in any functions that this function forward-referenced via
4678   // blockaddresses.
4679   return materializeForwardReferencedFunctions();
4680 }
4681
4682 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4683   const Function *F = dyn_cast<Function>(GV);
4684   if (!F || F->isDeclaration())
4685     return false;
4686
4687   // Dematerializing F would leave dangling references that wouldn't be
4688   // reconnected on re-materialization.
4689   if (BlockAddressesTaken.count(F))
4690     return false;
4691
4692   return DeferredFunctionInfo.count(const_cast<Function*>(F));
4693 }
4694
4695 void BitcodeReader::dematerialize(GlobalValue *GV) {
4696   Function *F = dyn_cast<Function>(GV);
4697   // If this function isn't dematerializable, this is a noop.
4698   if (!F || !isDematerializable(F))
4699     return;
4700
4701   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4702
4703   // Just forget the function body, we can remat it later.
4704   F->dropAllReferences();
4705   F->setIsMaterializable(true);
4706 }
4707
4708 std::error_code BitcodeReader::materializeModule(Module *M) {
4709   assert(M == TheModule &&
4710          "Can only Materialize the Module this BitcodeReader is attached to.");
4711
4712   if (std::error_code EC = materializeMetadata())
4713     return EC;
4714
4715   // Promise to materialize all forward references.
4716   WillMaterializeAllForwardRefs = true;
4717
4718   // Iterate over the module, deserializing any functions that are still on
4719   // disk.
4720   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4721        F != E; ++F) {
4722     if (std::error_code EC = materialize(F))
4723       return EC;
4724   }
4725   // At this point, if there are any function bodies, the current bit is
4726   // pointing to the END_BLOCK record after them. Now make sure the rest
4727   // of the bits in the module have been read.
4728   if (NextUnreadBit)
4729     parseModule(true);
4730
4731   // Check that all block address forward references got resolved (as we
4732   // promised above).
4733   if (!BasicBlockFwdRefs.empty())
4734     return error("Never resolved function from blockaddress");
4735
4736   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4737   // delete the old functions to clean up. We can't do this unless the entire
4738   // module is materialized because there could always be another function body
4739   // with calls to the old function.
4740   for (auto &I : UpgradedIntrinsics) {
4741     for (auto *U : I.first->users()) {
4742       if (CallInst *CI = dyn_cast<CallInst>(U))
4743         UpgradeIntrinsicCall(CI, I.second);
4744     }
4745     if (!I.first->use_empty())
4746       I.first->replaceAllUsesWith(I.second);
4747     I.first->eraseFromParent();
4748   }
4749   UpgradedIntrinsics.clear();
4750
4751   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4752     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4753
4754   UpgradeDebugInfo(*M);
4755   return std::error_code();
4756 }
4757
4758 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4759   return IdentifiedStructTypes;
4760 }
4761
4762 std::error_code
4763 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4764   if (Streamer)
4765     return initLazyStream(std::move(Streamer));
4766   return initStreamFromBuffer();
4767 }
4768
4769 std::error_code BitcodeReader::initStreamFromBuffer() {
4770   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4771   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4772
4773   if (Buffer->getBufferSize() & 3)
4774     return error("Invalid bitcode signature");
4775
4776   // If we have a wrapper header, parse it and ignore the non-bc file contents.
4777   // The magic number is 0x0B17C0DE stored in little endian.
4778   if (isBitcodeWrapper(BufPtr, BufEnd))
4779     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4780       return error("Invalid bitcode wrapper header");
4781
4782   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4783   Stream.init(&*StreamFile);
4784
4785   return std::error_code();
4786 }
4787
4788 std::error_code
4789 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4790   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4791   // see it.
4792   auto OwnedBytes =
4793       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4794   StreamingMemoryObject &Bytes = *OwnedBytes;
4795   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4796   Stream.init(&*StreamFile);
4797
4798   unsigned char buf[16];
4799   if (Bytes.readBytes(buf, 16, 0) != 16)
4800     return error("Invalid bitcode signature");
4801
4802   if (!isBitcode(buf, buf + 16))
4803     return error("Invalid bitcode signature");
4804
4805   if (isBitcodeWrapper(buf, buf + 4)) {
4806     const unsigned char *bitcodeStart = buf;
4807     const unsigned char *bitcodeEnd = buf + 16;
4808     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4809     Bytes.dropLeadingBytes(bitcodeStart - buf);
4810     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4811   }
4812   return std::error_code();
4813 }
4814
4815 namespace {
4816 class BitcodeErrorCategoryType : public std::error_category {
4817   const char *name() const LLVM_NOEXCEPT override {
4818     return "llvm.bitcode";
4819   }
4820   std::string message(int IE) const override {
4821     BitcodeError E = static_cast<BitcodeError>(IE);
4822     switch (E) {
4823     case BitcodeError::InvalidBitcodeSignature:
4824       return "Invalid bitcode signature";
4825     case BitcodeError::CorruptedBitcode:
4826       return "Corrupted bitcode";
4827     }
4828     llvm_unreachable("Unknown error type!");
4829   }
4830 };
4831 }
4832
4833 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4834
4835 const std::error_category &llvm::BitcodeErrorCategory() {
4836   return *ErrorCategory;
4837 }
4838
4839 //===----------------------------------------------------------------------===//
4840 // External interface
4841 //===----------------------------------------------------------------------===//
4842
4843 static ErrorOr<std::unique_ptr<Module>>
4844 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4845                      BitcodeReader *R, LLVMContext &Context,
4846                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4847   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4848   M->setMaterializer(R);
4849
4850   auto cleanupOnError = [&](std::error_code EC) {
4851     R->releaseBuffer(); // Never take ownership on error.
4852     return EC;
4853   };
4854
4855   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4856   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4857                                                ShouldLazyLoadMetadata))
4858     return cleanupOnError(EC);
4859
4860   if (MaterializeAll) {
4861     // Read in the entire module, and destroy the BitcodeReader.
4862     if (std::error_code EC = M->materializeAllPermanently())
4863       return cleanupOnError(EC);
4864   } else {
4865     // Resolve forward references from blockaddresses.
4866     if (std::error_code EC = R->materializeForwardReferencedFunctions())
4867       return cleanupOnError(EC);
4868   }
4869   return std::move(M);
4870 }
4871
4872 /// \brief Get a lazy one-at-time loading module from bitcode.
4873 ///
4874 /// This isn't always used in a lazy context.  In particular, it's also used by
4875 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
4876 /// in forward-referenced functions from block address references.
4877 ///
4878 /// \param[in] MaterializeAll Set to \c true if we should materialize
4879 /// everything.
4880 static ErrorOr<std::unique_ptr<Module>>
4881 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4882                          LLVMContext &Context, bool MaterializeAll,
4883                          DiagnosticHandlerFunction DiagnosticHandler,
4884                          bool ShouldLazyLoadMetadata = false) {
4885   BitcodeReader *R =
4886       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4887
4888   ErrorOr<std::unique_ptr<Module>> Ret =
4889       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4890                            MaterializeAll, ShouldLazyLoadMetadata);
4891   if (!Ret)
4892     return Ret;
4893
4894   Buffer.release(); // The BitcodeReader owns it now.
4895   return Ret;
4896 }
4897
4898 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4899     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4900     DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
4901   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4902                                   DiagnosticHandler, ShouldLazyLoadMetadata);
4903 }
4904
4905 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4906     StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4907     LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
4908   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4909   BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
4910
4911   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4912                               false);
4913 }
4914
4915 ErrorOr<std::unique_ptr<Module>>
4916 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4917                        DiagnosticHandlerFunction DiagnosticHandler) {
4918   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4919   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4920                                   DiagnosticHandler);
4921   // TODO: Restore the use-lists to the in-memory state when the bitcode was
4922   // written.  We must defer until the Module has been fully materialized.
4923 }
4924
4925 std::string
4926 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4927                              DiagnosticHandlerFunction DiagnosticHandler) {
4928   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4929   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4930                                             DiagnosticHandler);
4931   ErrorOr<std::string> Triple = R->parseTriple();
4932   if (Triple.getError())
4933     return "";
4934   return Triple.get();
4935 }