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