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