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