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