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