xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 2d28f7aa07483ba57428c654170467966581849c)
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   std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
1952   SmallVector<uint64_t, 64> Record;
1953 
1954   auto getMD = [&](unsigned ID) -> Metadata * {
1955     return MetadataList.getMetadataFwdRef(ID);
1956   };
1957   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1958     if (ID)
1959       return getMD(ID - 1);
1960     return nullptr;
1961   };
1962   auto getMDString = [&](unsigned ID) -> MDString *{
1963     // This requires that the ID is not really a forward reference.  In
1964     // particular, the MDString must already have been resolved.
1965     return cast_or_null<MDString>(getMDOrNull(ID));
1966   };
1967 
1968 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
1969   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1970 
1971   // Read all the records.
1972   while (1) {
1973     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1974 
1975     switch (Entry.Kind) {
1976     case BitstreamEntry::SubBlock: // Handled for us already.
1977     case BitstreamEntry::Error:
1978       return error("Malformed block");
1979     case BitstreamEntry::EndBlock:
1980       // Upgrade old-style CU <-> SP pointers to point from SP to CU.
1981       for (auto CU_SP : CUSubprograms)
1982         if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
1983           for (auto &Op : SPs->operands())
1984             if (auto *SP = dyn_cast_or_null<MDNode>(Op))
1985               SP->replaceOperandWith(7, CU_SP.first);
1986 
1987       MetadataList.tryToResolveCycles();
1988       return std::error_code();
1989     case BitstreamEntry::Record:
1990       // The interesting case.
1991       break;
1992     }
1993 
1994     // Read a record.
1995     Record.clear();
1996     StringRef Blob;
1997     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
1998     bool IsDistinct = false;
1999     switch (Code) {
2000     default:  // Default behavior: ignore.
2001       break;
2002     case bitc::METADATA_NAME: {
2003       // Read name of the named metadata.
2004       SmallString<8> Name(Record.begin(), Record.end());
2005       Record.clear();
2006       Code = Stream.ReadCode();
2007 
2008       unsigned NextBitCode = Stream.readRecord(Code, Record);
2009       if (NextBitCode != bitc::METADATA_NAMED_NODE)
2010         return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
2011 
2012       // Read named metadata elements.
2013       unsigned Size = Record.size();
2014       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
2015       for (unsigned i = 0; i != Size; ++i) {
2016         MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
2017         if (!MD)
2018           return error("Invalid record");
2019         NMD->addOperand(MD);
2020       }
2021       break;
2022     }
2023     case bitc::METADATA_OLD_FN_NODE: {
2024       // FIXME: Remove in 4.0.
2025       // This is a LocalAsMetadata record, the only type of function-local
2026       // metadata.
2027       if (Record.size() % 2 == 1)
2028         return error("Invalid record");
2029 
2030       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
2031       // to be legal, but there's no upgrade path.
2032       auto dropRecord = [&] {
2033         MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
2034       };
2035       if (Record.size() != 2) {
2036         dropRecord();
2037         break;
2038       }
2039 
2040       Type *Ty = getTypeByID(Record[0]);
2041       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2042         dropRecord();
2043         break;
2044       }
2045 
2046       MetadataList.assignValue(
2047           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2048           NextMetadataNo++);
2049       break;
2050     }
2051     case bitc::METADATA_OLD_NODE: {
2052       // FIXME: Remove in 4.0.
2053       if (Record.size() % 2 == 1)
2054         return error("Invalid record");
2055 
2056       unsigned Size = Record.size();
2057       SmallVector<Metadata *, 8> Elts;
2058       for (unsigned i = 0; i != Size; i += 2) {
2059         Type *Ty = getTypeByID(Record[i]);
2060         if (!Ty)
2061           return error("Invalid record");
2062         if (Ty->isMetadataTy())
2063           Elts.push_back(MetadataList.getMetadataFwdRef(Record[i + 1]));
2064         else if (!Ty->isVoidTy()) {
2065           auto *MD =
2066               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2067           assert(isa<ConstantAsMetadata>(MD) &&
2068                  "Expected non-function-local metadata");
2069           Elts.push_back(MD);
2070         } else
2071           Elts.push_back(nullptr);
2072       }
2073       MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
2074       break;
2075     }
2076     case bitc::METADATA_VALUE: {
2077       if (Record.size() != 2)
2078         return error("Invalid record");
2079 
2080       Type *Ty = getTypeByID(Record[0]);
2081       if (Ty->isMetadataTy() || Ty->isVoidTy())
2082         return error("Invalid record");
2083 
2084       MetadataList.assignValue(
2085           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2086           NextMetadataNo++);
2087       break;
2088     }
2089     case bitc::METADATA_DISTINCT_NODE:
2090       IsDistinct = true;
2091       // fallthrough...
2092     case bitc::METADATA_NODE: {
2093       SmallVector<Metadata *, 8> Elts;
2094       Elts.reserve(Record.size());
2095       for (unsigned ID : Record)
2096         Elts.push_back(ID ? MetadataList.getMetadataFwdRef(ID - 1) : nullptr);
2097       MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2098                                           : MDNode::get(Context, Elts),
2099                                NextMetadataNo++);
2100       break;
2101     }
2102     case bitc::METADATA_LOCATION: {
2103       if (Record.size() != 5)
2104         return error("Invalid record");
2105 
2106       unsigned Line = Record[1];
2107       unsigned Column = Record[2];
2108       MDNode *Scope = MetadataList.getMDNodeFwdRefOrNull(Record[3]);
2109       if (!Scope)
2110         return error("Invalid record");
2111       Metadata *InlinedAt =
2112           Record[4] ? MetadataList.getMetadataFwdRef(Record[4] - 1) : nullptr;
2113       MetadataList.assignValue(
2114           GET_OR_DISTINCT(DILocation, Record[0],
2115                           (Context, Line, Column, Scope, InlinedAt)),
2116           NextMetadataNo++);
2117       break;
2118     }
2119     case bitc::METADATA_GENERIC_DEBUG: {
2120       if (Record.size() < 4)
2121         return error("Invalid record");
2122 
2123       unsigned Tag = Record[1];
2124       unsigned Version = Record[2];
2125 
2126       if (Tag >= 1u << 16 || Version != 0)
2127         return error("Invalid record");
2128 
2129       auto *Header = getMDString(Record[3]);
2130       SmallVector<Metadata *, 8> DwarfOps;
2131       for (unsigned I = 4, E = Record.size(); I != E; ++I)
2132         DwarfOps.push_back(Record[I]
2133                                ? MetadataList.getMetadataFwdRef(Record[I] - 1)
2134                                : nullptr);
2135       MetadataList.assignValue(
2136           GET_OR_DISTINCT(GenericDINode, Record[0],
2137                           (Context, Tag, Header, DwarfOps)),
2138           NextMetadataNo++);
2139       break;
2140     }
2141     case bitc::METADATA_SUBRANGE: {
2142       if (Record.size() != 3)
2143         return error("Invalid record");
2144 
2145       MetadataList.assignValue(
2146           GET_OR_DISTINCT(DISubrange, Record[0],
2147                           (Context, Record[1], unrotateSign(Record[2]))),
2148           NextMetadataNo++);
2149       break;
2150     }
2151     case bitc::METADATA_ENUMERATOR: {
2152       if (Record.size() != 3)
2153         return error("Invalid record");
2154 
2155       MetadataList.assignValue(
2156           GET_OR_DISTINCT(
2157               DIEnumerator, Record[0],
2158               (Context, unrotateSign(Record[1]), getMDString(Record[2]))),
2159           NextMetadataNo++);
2160       break;
2161     }
2162     case bitc::METADATA_BASIC_TYPE: {
2163       if (Record.size() != 6)
2164         return error("Invalid record");
2165 
2166       MetadataList.assignValue(
2167           GET_OR_DISTINCT(DIBasicType, Record[0],
2168                           (Context, Record[1], getMDString(Record[2]),
2169                            Record[3], Record[4], Record[5])),
2170           NextMetadataNo++);
2171       break;
2172     }
2173     case bitc::METADATA_DERIVED_TYPE: {
2174       if (Record.size() != 12)
2175         return error("Invalid record");
2176 
2177       MetadataList.assignValue(
2178           GET_OR_DISTINCT(DIDerivedType, Record[0],
2179                           (Context, Record[1], getMDString(Record[2]),
2180                            getMDOrNull(Record[3]), Record[4],
2181                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2182                            Record[7], Record[8], Record[9], Record[10],
2183                            getMDOrNull(Record[11]))),
2184           NextMetadataNo++);
2185       break;
2186     }
2187     case bitc::METADATA_COMPOSITE_TYPE: {
2188       if (Record.size() != 16)
2189         return error("Invalid record");
2190 
2191       MetadataList.assignValue(
2192           GET_OR_DISTINCT(DICompositeType, Record[0],
2193                           (Context, Record[1], getMDString(Record[2]),
2194                            getMDOrNull(Record[3]), Record[4],
2195                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2196                            Record[7], Record[8], Record[9], Record[10],
2197                            getMDOrNull(Record[11]), Record[12],
2198                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2199                            getMDString(Record[15]))),
2200           NextMetadataNo++);
2201       break;
2202     }
2203     case bitc::METADATA_SUBROUTINE_TYPE: {
2204       if (Record.size() != 3)
2205         return error("Invalid record");
2206 
2207       MetadataList.assignValue(
2208           GET_OR_DISTINCT(DISubroutineType, Record[0],
2209                           (Context, Record[1], getMDOrNull(Record[2]))),
2210           NextMetadataNo++);
2211       break;
2212     }
2213 
2214     case bitc::METADATA_MODULE: {
2215       if (Record.size() != 6)
2216         return error("Invalid record");
2217 
2218       MetadataList.assignValue(
2219           GET_OR_DISTINCT(DIModule, Record[0],
2220                           (Context, getMDOrNull(Record[1]),
2221                            getMDString(Record[2]), getMDString(Record[3]),
2222                            getMDString(Record[4]), getMDString(Record[5]))),
2223           NextMetadataNo++);
2224       break;
2225     }
2226 
2227     case bitc::METADATA_FILE: {
2228       if (Record.size() != 3)
2229         return error("Invalid record");
2230 
2231       MetadataList.assignValue(
2232           GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2233                                               getMDString(Record[2]))),
2234           NextMetadataNo++);
2235       break;
2236     }
2237     case bitc::METADATA_COMPILE_UNIT: {
2238       if (Record.size() < 14 || Record.size() > 16)
2239         return error("Invalid record");
2240 
2241       // Ignore Record[0], which indicates whether this compile unit is
2242       // distinct.  It's always distinct.
2243       auto *CU = DICompileUnit::getDistinct(
2244           Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2245           Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2246           Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2247           getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2248           Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2249           Record.size() <= 14 ? 0 : Record[14]);
2250 
2251       MetadataList.assignValue(CU, NextMetadataNo++);
2252 
2253       // Move the Upgrade the list of subprograms.
2254       if (Metadata *SPs = getMDOrNull(Record[11]))
2255         CUSubprograms.push_back({CU, SPs});
2256       break;
2257     }
2258     case bitc::METADATA_SUBPROGRAM: {
2259       if (Record.size() != 18 && Record.size() != 19)
2260         return error("Invalid record");
2261 
2262       // Version 1 has a Function as Record[15].
2263       // Version 2 has removed Record[15].
2264       // Version 3 has the Unit as Record[15].
2265       Metadata *CUorFn = getMDOrNull(Record[15]);
2266       unsigned Offset = Record.size() == 19 ? 1 : 0;
2267       bool HasFn = Offset && dyn_cast_or_null<ConstantAsMetadata>(CUorFn);
2268       bool HasCU = Offset && !HasFn;
2269       DISubprogram *SP = GET_OR_DISTINCT(
2270           DISubprogram,
2271           Record[0] || Record[8], // All definitions should be distinct.
2272           (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2273            getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2274            getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2275            getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2276            Record[14], HasCU ? CUorFn : nullptr,
2277            getMDOrNull(Record[15 + Offset]), getMDOrNull(Record[16 + Offset]),
2278            getMDOrNull(Record[17 + Offset])));
2279       MetadataList.assignValue(SP, NextMetadataNo++);
2280 
2281       // Upgrade sp->function mapping to function->sp mapping.
2282       if (HasFn) {
2283         if (auto *CMD = dyn_cast<ConstantAsMetadata>(CUorFn))
2284           if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2285             if (F->isMaterializable())
2286               // Defer until materialized; unmaterialized functions may not have
2287               // metadata.
2288               FunctionsWithSPs[F] = SP;
2289             else if (!F->empty())
2290               F->setSubprogram(SP);
2291           }
2292       }
2293       break;
2294     }
2295     case bitc::METADATA_LEXICAL_BLOCK: {
2296       if (Record.size() != 5)
2297         return error("Invalid record");
2298 
2299       MetadataList.assignValue(
2300           GET_OR_DISTINCT(DILexicalBlock, Record[0],
2301                           (Context, getMDOrNull(Record[1]),
2302                            getMDOrNull(Record[2]), Record[3], Record[4])),
2303           NextMetadataNo++);
2304       break;
2305     }
2306     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2307       if (Record.size() != 4)
2308         return error("Invalid record");
2309 
2310       MetadataList.assignValue(
2311           GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2312                           (Context, getMDOrNull(Record[1]),
2313                            getMDOrNull(Record[2]), Record[3])),
2314           NextMetadataNo++);
2315       break;
2316     }
2317     case bitc::METADATA_NAMESPACE: {
2318       if (Record.size() != 5)
2319         return error("Invalid record");
2320 
2321       MetadataList.assignValue(
2322           GET_OR_DISTINCT(DINamespace, Record[0],
2323                           (Context, getMDOrNull(Record[1]),
2324                            getMDOrNull(Record[2]), getMDString(Record[3]),
2325                            Record[4])),
2326           NextMetadataNo++);
2327       break;
2328     }
2329     case bitc::METADATA_MACRO: {
2330       if (Record.size() != 5)
2331         return error("Invalid record");
2332 
2333       MetadataList.assignValue(
2334           GET_OR_DISTINCT(DIMacro, Record[0],
2335                           (Context, Record[1], Record[2],
2336                            getMDString(Record[3]), getMDString(Record[4]))),
2337           NextMetadataNo++);
2338       break;
2339     }
2340     case bitc::METADATA_MACRO_FILE: {
2341       if (Record.size() != 5)
2342         return error("Invalid record");
2343 
2344       MetadataList.assignValue(
2345           GET_OR_DISTINCT(DIMacroFile, Record[0],
2346                           (Context, Record[1], Record[2],
2347                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2348           NextMetadataNo++);
2349       break;
2350     }
2351     case bitc::METADATA_TEMPLATE_TYPE: {
2352       if (Record.size() != 3)
2353         return error("Invalid record");
2354 
2355       MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2356                                                Record[0],
2357                                                (Context, getMDString(Record[1]),
2358                                                 getMDOrNull(Record[2]))),
2359                                NextMetadataNo++);
2360       break;
2361     }
2362     case bitc::METADATA_TEMPLATE_VALUE: {
2363       if (Record.size() != 5)
2364         return error("Invalid record");
2365 
2366       MetadataList.assignValue(
2367           GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2368                           (Context, Record[1], getMDString(Record[2]),
2369                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2370           NextMetadataNo++);
2371       break;
2372     }
2373     case bitc::METADATA_GLOBAL_VAR: {
2374       if (Record.size() != 11)
2375         return error("Invalid record");
2376 
2377       MetadataList.assignValue(
2378           GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2379                           (Context, getMDOrNull(Record[1]),
2380                            getMDString(Record[2]), getMDString(Record[3]),
2381                            getMDOrNull(Record[4]), Record[5],
2382                            getMDOrNull(Record[6]), Record[7], Record[8],
2383                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2384           NextMetadataNo++);
2385       break;
2386     }
2387     case bitc::METADATA_LOCAL_VAR: {
2388       // 10th field is for the obseleted 'inlinedAt:' field.
2389       if (Record.size() < 8 || Record.size() > 10)
2390         return error("Invalid record");
2391 
2392       // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2393       // DW_TAG_arg_variable.
2394       bool HasTag = Record.size() > 8;
2395       MetadataList.assignValue(
2396           GET_OR_DISTINCT(DILocalVariable, Record[0],
2397                           (Context, getMDOrNull(Record[1 + HasTag]),
2398                            getMDString(Record[2 + HasTag]),
2399                            getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2400                            getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2401                            Record[7 + HasTag])),
2402           NextMetadataNo++);
2403       break;
2404     }
2405     case bitc::METADATA_EXPRESSION: {
2406       if (Record.size() < 1)
2407         return error("Invalid record");
2408 
2409       MetadataList.assignValue(
2410           GET_OR_DISTINCT(DIExpression, Record[0],
2411                           (Context, makeArrayRef(Record).slice(1))),
2412           NextMetadataNo++);
2413       break;
2414     }
2415     case bitc::METADATA_OBJC_PROPERTY: {
2416       if (Record.size() != 8)
2417         return error("Invalid record");
2418 
2419       MetadataList.assignValue(
2420           GET_OR_DISTINCT(DIObjCProperty, Record[0],
2421                           (Context, getMDString(Record[1]),
2422                            getMDOrNull(Record[2]), Record[3],
2423                            getMDString(Record[4]), getMDString(Record[5]),
2424                            Record[6], getMDOrNull(Record[7]))),
2425           NextMetadataNo++);
2426       break;
2427     }
2428     case bitc::METADATA_IMPORTED_ENTITY: {
2429       if (Record.size() != 6)
2430         return error("Invalid record");
2431 
2432       MetadataList.assignValue(
2433           GET_OR_DISTINCT(DIImportedEntity, Record[0],
2434                           (Context, Record[1], getMDOrNull(Record[2]),
2435                            getMDOrNull(Record[3]), Record[4],
2436                            getMDString(Record[5]))),
2437           NextMetadataNo++);
2438       break;
2439     }
2440     case bitc::METADATA_STRING_OLD: {
2441       std::string String(Record.begin(), Record.end());
2442 
2443       // Test for upgrading !llvm.loop.
2444       HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2445 
2446       Metadata *MD = MDString::get(Context, String);
2447       MetadataList.assignValue(MD, NextMetadataNo++);
2448       break;
2449     }
2450     case bitc::METADATA_STRINGS:
2451       if (std::error_code EC =
2452               parseMetadataStrings(Record, Blob, NextMetadataNo))
2453         return EC;
2454       break;
2455     case bitc::METADATA_KIND: {
2456       // Support older bitcode files that had METADATA_KIND records in a
2457       // block with METADATA_BLOCK_ID.
2458       if (std::error_code EC = parseMetadataKindRecord(Record))
2459         return EC;
2460       break;
2461     }
2462     }
2463   }
2464 #undef GET_OR_DISTINCT
2465 }
2466 
2467 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2468 std::error_code BitcodeReader::parseMetadataKinds() {
2469   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2470     return error("Invalid record");
2471 
2472   SmallVector<uint64_t, 64> Record;
2473 
2474   // Read all the records.
2475   while (1) {
2476     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2477 
2478     switch (Entry.Kind) {
2479     case BitstreamEntry::SubBlock: // Handled for us already.
2480     case BitstreamEntry::Error:
2481       return error("Malformed block");
2482     case BitstreamEntry::EndBlock:
2483       return std::error_code();
2484     case BitstreamEntry::Record:
2485       // The interesting case.
2486       break;
2487     }
2488 
2489     // Read a record.
2490     Record.clear();
2491     unsigned Code = Stream.readRecord(Entry.ID, Record);
2492     switch (Code) {
2493     default: // Default behavior: ignore.
2494       break;
2495     case bitc::METADATA_KIND: {
2496       if (std::error_code EC = parseMetadataKindRecord(Record))
2497         return EC;
2498       break;
2499     }
2500     }
2501   }
2502 }
2503 
2504 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2505 /// encoding.
2506 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2507   if ((V & 1) == 0)
2508     return V >> 1;
2509   if (V != 1)
2510     return -(V >> 1);
2511   // There is no such thing as -0 with integers.  "-0" really means MININT.
2512   return 1ULL << 63;
2513 }
2514 
2515 /// Resolve all of the initializers for global values and aliases that we can.
2516 std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2517   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2518   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2519       IndirectSymbolInitWorklist;
2520   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2521   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2522   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2523 
2524   GlobalInitWorklist.swap(GlobalInits);
2525   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2526   FunctionPrefixWorklist.swap(FunctionPrefixes);
2527   FunctionPrologueWorklist.swap(FunctionPrologues);
2528   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2529 
2530   while (!GlobalInitWorklist.empty()) {
2531     unsigned ValID = GlobalInitWorklist.back().second;
2532     if (ValID >= ValueList.size()) {
2533       // Not ready to resolve this yet, it requires something later in the file.
2534       GlobalInits.push_back(GlobalInitWorklist.back());
2535     } else {
2536       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2537         GlobalInitWorklist.back().first->setInitializer(C);
2538       else
2539         return error("Expected a constant");
2540     }
2541     GlobalInitWorklist.pop_back();
2542   }
2543 
2544   while (!IndirectSymbolInitWorklist.empty()) {
2545     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2546     if (ValID >= ValueList.size()) {
2547       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2548     } else {
2549       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2550       if (!C)
2551         return error("Expected a constant");
2552       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2553       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2554         return error("Alias and aliasee types don't match");
2555       GIS->setIndirectSymbol(C);
2556     }
2557     IndirectSymbolInitWorklist.pop_back();
2558   }
2559 
2560   while (!FunctionPrefixWorklist.empty()) {
2561     unsigned ValID = FunctionPrefixWorklist.back().second;
2562     if (ValID >= ValueList.size()) {
2563       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2564     } else {
2565       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2566         FunctionPrefixWorklist.back().first->setPrefixData(C);
2567       else
2568         return error("Expected a constant");
2569     }
2570     FunctionPrefixWorklist.pop_back();
2571   }
2572 
2573   while (!FunctionPrologueWorklist.empty()) {
2574     unsigned ValID = FunctionPrologueWorklist.back().second;
2575     if (ValID >= ValueList.size()) {
2576       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2577     } else {
2578       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2579         FunctionPrologueWorklist.back().first->setPrologueData(C);
2580       else
2581         return error("Expected a constant");
2582     }
2583     FunctionPrologueWorklist.pop_back();
2584   }
2585 
2586   while (!FunctionPersonalityFnWorklist.empty()) {
2587     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2588     if (ValID >= ValueList.size()) {
2589       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2590     } else {
2591       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2592         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2593       else
2594         return error("Expected a constant");
2595     }
2596     FunctionPersonalityFnWorklist.pop_back();
2597   }
2598 
2599   return std::error_code();
2600 }
2601 
2602 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2603   SmallVector<uint64_t, 8> Words(Vals.size());
2604   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2605                  BitcodeReader::decodeSignRotatedValue);
2606 
2607   return APInt(TypeBits, Words);
2608 }
2609 
2610 std::error_code BitcodeReader::parseConstants() {
2611   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2612     return error("Invalid record");
2613 
2614   SmallVector<uint64_t, 64> Record;
2615 
2616   // Read all the records for this value table.
2617   Type *CurTy = Type::getInt32Ty(Context);
2618   unsigned NextCstNo = ValueList.size();
2619   while (1) {
2620     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2621 
2622     switch (Entry.Kind) {
2623     case BitstreamEntry::SubBlock: // Handled for us already.
2624     case BitstreamEntry::Error:
2625       return error("Malformed block");
2626     case BitstreamEntry::EndBlock:
2627       if (NextCstNo != ValueList.size())
2628         return error("Invalid constant reference");
2629 
2630       // Once all the constants have been read, go through and resolve forward
2631       // references.
2632       ValueList.resolveConstantForwardRefs();
2633       return std::error_code();
2634     case BitstreamEntry::Record:
2635       // The interesting case.
2636       break;
2637     }
2638 
2639     // Read a record.
2640     Record.clear();
2641     Value *V = nullptr;
2642     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2643     switch (BitCode) {
2644     default:  // Default behavior: unknown constant
2645     case bitc::CST_CODE_UNDEF:     // UNDEF
2646       V = UndefValue::get(CurTy);
2647       break;
2648     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2649       if (Record.empty())
2650         return error("Invalid record");
2651       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2652         return error("Invalid record");
2653       CurTy = TypeList[Record[0]];
2654       continue;  // Skip the ValueList manipulation.
2655     case bitc::CST_CODE_NULL:      // NULL
2656       V = Constant::getNullValue(CurTy);
2657       break;
2658     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2659       if (!CurTy->isIntegerTy() || Record.empty())
2660         return error("Invalid record");
2661       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2662       break;
2663     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2664       if (!CurTy->isIntegerTy() || Record.empty())
2665         return error("Invalid record");
2666 
2667       APInt VInt =
2668           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2669       V = ConstantInt::get(Context, VInt);
2670 
2671       break;
2672     }
2673     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2674       if (Record.empty())
2675         return error("Invalid record");
2676       if (CurTy->isHalfTy())
2677         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2678                                              APInt(16, (uint16_t)Record[0])));
2679       else if (CurTy->isFloatTy())
2680         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2681                                              APInt(32, (uint32_t)Record[0])));
2682       else if (CurTy->isDoubleTy())
2683         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2684                                              APInt(64, Record[0])));
2685       else if (CurTy->isX86_FP80Ty()) {
2686         // Bits are not stored the same way as a normal i80 APInt, compensate.
2687         uint64_t Rearrange[2];
2688         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2689         Rearrange[1] = Record[0] >> 48;
2690         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2691                                              APInt(80, Rearrange)));
2692       } else if (CurTy->isFP128Ty())
2693         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2694                                              APInt(128, Record)));
2695       else if (CurTy->isPPC_FP128Ty())
2696         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2697                                              APInt(128, Record)));
2698       else
2699         V = UndefValue::get(CurTy);
2700       break;
2701     }
2702 
2703     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2704       if (Record.empty())
2705         return error("Invalid record");
2706 
2707       unsigned Size = Record.size();
2708       SmallVector<Constant*, 16> Elts;
2709 
2710       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2711         for (unsigned i = 0; i != Size; ++i)
2712           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2713                                                      STy->getElementType(i)));
2714         V = ConstantStruct::get(STy, Elts);
2715       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2716         Type *EltTy = ATy->getElementType();
2717         for (unsigned i = 0; i != Size; ++i)
2718           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2719         V = ConstantArray::get(ATy, Elts);
2720       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2721         Type *EltTy = VTy->getElementType();
2722         for (unsigned i = 0; i != Size; ++i)
2723           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2724         V = ConstantVector::get(Elts);
2725       } else {
2726         V = UndefValue::get(CurTy);
2727       }
2728       break;
2729     }
2730     case bitc::CST_CODE_STRING:    // STRING: [values]
2731     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2732       if (Record.empty())
2733         return error("Invalid record");
2734 
2735       SmallString<16> Elts(Record.begin(), Record.end());
2736       V = ConstantDataArray::getString(Context, Elts,
2737                                        BitCode == bitc::CST_CODE_CSTRING);
2738       break;
2739     }
2740     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2741       if (Record.empty())
2742         return error("Invalid record");
2743 
2744       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2745       if (EltTy->isIntegerTy(8)) {
2746         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2747         if (isa<VectorType>(CurTy))
2748           V = ConstantDataVector::get(Context, Elts);
2749         else
2750           V = ConstantDataArray::get(Context, Elts);
2751       } else if (EltTy->isIntegerTy(16)) {
2752         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2753         if (isa<VectorType>(CurTy))
2754           V = ConstantDataVector::get(Context, Elts);
2755         else
2756           V = ConstantDataArray::get(Context, Elts);
2757       } else if (EltTy->isIntegerTy(32)) {
2758         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2759         if (isa<VectorType>(CurTy))
2760           V = ConstantDataVector::get(Context, Elts);
2761         else
2762           V = ConstantDataArray::get(Context, Elts);
2763       } else if (EltTy->isIntegerTy(64)) {
2764         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2765         if (isa<VectorType>(CurTy))
2766           V = ConstantDataVector::get(Context, Elts);
2767         else
2768           V = ConstantDataArray::get(Context, Elts);
2769       } else if (EltTy->isHalfTy()) {
2770         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2771         if (isa<VectorType>(CurTy))
2772           V = ConstantDataVector::getFP(Context, Elts);
2773         else
2774           V = ConstantDataArray::getFP(Context, Elts);
2775       } else if (EltTy->isFloatTy()) {
2776         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2777         if (isa<VectorType>(CurTy))
2778           V = ConstantDataVector::getFP(Context, Elts);
2779         else
2780           V = ConstantDataArray::getFP(Context, Elts);
2781       } else if (EltTy->isDoubleTy()) {
2782         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2783         if (isa<VectorType>(CurTy))
2784           V = ConstantDataVector::getFP(Context, Elts);
2785         else
2786           V = ConstantDataArray::getFP(Context, Elts);
2787       } else {
2788         return error("Invalid type for value");
2789       }
2790       break;
2791     }
2792     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2793       if (Record.size() < 3)
2794         return error("Invalid record");
2795       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2796       if (Opc < 0) {
2797         V = UndefValue::get(CurTy);  // Unknown binop.
2798       } else {
2799         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2800         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2801         unsigned Flags = 0;
2802         if (Record.size() >= 4) {
2803           if (Opc == Instruction::Add ||
2804               Opc == Instruction::Sub ||
2805               Opc == Instruction::Mul ||
2806               Opc == Instruction::Shl) {
2807             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2808               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2809             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2810               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2811           } else if (Opc == Instruction::SDiv ||
2812                      Opc == Instruction::UDiv ||
2813                      Opc == Instruction::LShr ||
2814                      Opc == Instruction::AShr) {
2815             if (Record[3] & (1 << bitc::PEO_EXACT))
2816               Flags |= SDivOperator::IsExact;
2817           }
2818         }
2819         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2820       }
2821       break;
2822     }
2823     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2824       if (Record.size() < 3)
2825         return error("Invalid record");
2826       int Opc = getDecodedCastOpcode(Record[0]);
2827       if (Opc < 0) {
2828         V = UndefValue::get(CurTy);  // Unknown cast.
2829       } else {
2830         Type *OpTy = getTypeByID(Record[1]);
2831         if (!OpTy)
2832           return error("Invalid record");
2833         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2834         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2835         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2836       }
2837       break;
2838     }
2839     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2840     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2841       unsigned OpNum = 0;
2842       Type *PointeeType = nullptr;
2843       if (Record.size() % 2)
2844         PointeeType = getTypeByID(Record[OpNum++]);
2845       SmallVector<Constant*, 16> Elts;
2846       while (OpNum != Record.size()) {
2847         Type *ElTy = getTypeByID(Record[OpNum++]);
2848         if (!ElTy)
2849           return error("Invalid record");
2850         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2851       }
2852 
2853       if (PointeeType &&
2854           PointeeType !=
2855               cast<SequentialType>(Elts[0]->getType()->getScalarType())
2856                   ->getElementType())
2857         return error("Explicit gep operator type does not match pointee type "
2858                      "of pointer operand");
2859 
2860       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2861       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2862                                          BitCode ==
2863                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
2864       break;
2865     }
2866     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2867       if (Record.size() < 3)
2868         return error("Invalid record");
2869 
2870       Type *SelectorTy = Type::getInt1Ty(Context);
2871 
2872       // The selector might be an i1 or an <n x i1>
2873       // Get the type from the ValueList before getting a forward ref.
2874       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2875         if (Value *V = ValueList[Record[0]])
2876           if (SelectorTy != V->getType())
2877             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2878 
2879       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2880                                                               SelectorTy),
2881                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2882                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2883       break;
2884     }
2885     case bitc::CST_CODE_CE_EXTRACTELT
2886         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2887       if (Record.size() < 3)
2888         return error("Invalid record");
2889       VectorType *OpTy =
2890         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2891       if (!OpTy)
2892         return error("Invalid record");
2893       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2894       Constant *Op1 = nullptr;
2895       if (Record.size() == 4) {
2896         Type *IdxTy = getTypeByID(Record[2]);
2897         if (!IdxTy)
2898           return error("Invalid record");
2899         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2900       } else // TODO: Remove with llvm 4.0
2901         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2902       if (!Op1)
2903         return error("Invalid record");
2904       V = ConstantExpr::getExtractElement(Op0, Op1);
2905       break;
2906     }
2907     case bitc::CST_CODE_CE_INSERTELT
2908         : { // CE_INSERTELT: [opval, opval, opty, opval]
2909       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2910       if (Record.size() < 3 || !OpTy)
2911         return error("Invalid record");
2912       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2913       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2914                                                   OpTy->getElementType());
2915       Constant *Op2 = nullptr;
2916       if (Record.size() == 4) {
2917         Type *IdxTy = getTypeByID(Record[2]);
2918         if (!IdxTy)
2919           return error("Invalid record");
2920         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2921       } else // TODO: Remove with llvm 4.0
2922         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2923       if (!Op2)
2924         return error("Invalid record");
2925       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2926       break;
2927     }
2928     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2929       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2930       if (Record.size() < 3 || !OpTy)
2931         return error("Invalid record");
2932       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2933       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2934       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2935                                                  OpTy->getNumElements());
2936       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2937       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2938       break;
2939     }
2940     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2941       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2942       VectorType *OpTy =
2943         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2944       if (Record.size() < 4 || !RTy || !OpTy)
2945         return error("Invalid record");
2946       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2947       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2948       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2949                                                  RTy->getNumElements());
2950       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2951       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2952       break;
2953     }
2954     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2955       if (Record.size() < 4)
2956         return error("Invalid record");
2957       Type *OpTy = getTypeByID(Record[0]);
2958       if (!OpTy)
2959         return error("Invalid record");
2960       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2961       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2962 
2963       if (OpTy->isFPOrFPVectorTy())
2964         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2965       else
2966         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2967       break;
2968     }
2969     // This maintains backward compatibility, pre-asm dialect keywords.
2970     // FIXME: Remove with the 4.0 release.
2971     case bitc::CST_CODE_INLINEASM_OLD: {
2972       if (Record.size() < 2)
2973         return error("Invalid record");
2974       std::string AsmStr, ConstrStr;
2975       bool HasSideEffects = Record[0] & 1;
2976       bool IsAlignStack = Record[0] >> 1;
2977       unsigned AsmStrSize = Record[1];
2978       if (2+AsmStrSize >= Record.size())
2979         return error("Invalid record");
2980       unsigned ConstStrSize = Record[2+AsmStrSize];
2981       if (3+AsmStrSize+ConstStrSize > Record.size())
2982         return error("Invalid record");
2983 
2984       for (unsigned i = 0; i != AsmStrSize; ++i)
2985         AsmStr += (char)Record[2+i];
2986       for (unsigned i = 0; i != ConstStrSize; ++i)
2987         ConstrStr += (char)Record[3+AsmStrSize+i];
2988       PointerType *PTy = cast<PointerType>(CurTy);
2989       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2990                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2991       break;
2992     }
2993     // This version adds support for the asm dialect keywords (e.g.,
2994     // inteldialect).
2995     case bitc::CST_CODE_INLINEASM: {
2996       if (Record.size() < 2)
2997         return error("Invalid record");
2998       std::string AsmStr, ConstrStr;
2999       bool HasSideEffects = Record[0] & 1;
3000       bool IsAlignStack = (Record[0] >> 1) & 1;
3001       unsigned AsmDialect = Record[0] >> 2;
3002       unsigned AsmStrSize = Record[1];
3003       if (2+AsmStrSize >= Record.size())
3004         return error("Invalid record");
3005       unsigned ConstStrSize = Record[2+AsmStrSize];
3006       if (3+AsmStrSize+ConstStrSize > Record.size())
3007         return error("Invalid record");
3008 
3009       for (unsigned i = 0; i != AsmStrSize; ++i)
3010         AsmStr += (char)Record[2+i];
3011       for (unsigned i = 0; i != ConstStrSize; ++i)
3012         ConstrStr += (char)Record[3+AsmStrSize+i];
3013       PointerType *PTy = cast<PointerType>(CurTy);
3014       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3015                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3016                          InlineAsm::AsmDialect(AsmDialect));
3017       break;
3018     }
3019     case bitc::CST_CODE_BLOCKADDRESS:{
3020       if (Record.size() < 3)
3021         return error("Invalid record");
3022       Type *FnTy = getTypeByID(Record[0]);
3023       if (!FnTy)
3024         return error("Invalid record");
3025       Function *Fn =
3026         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
3027       if (!Fn)
3028         return error("Invalid record");
3029 
3030       // If the function is already parsed we can insert the block address right
3031       // away.
3032       BasicBlock *BB;
3033       unsigned BBID = Record[2];
3034       if (!BBID)
3035         // Invalid reference to entry block.
3036         return error("Invalid ID");
3037       if (!Fn->empty()) {
3038         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
3039         for (size_t I = 0, E = BBID; I != E; ++I) {
3040           if (BBI == BBE)
3041             return error("Invalid ID");
3042           ++BBI;
3043         }
3044         BB = &*BBI;
3045       } else {
3046         // Otherwise insert a placeholder and remember it so it can be inserted
3047         // when the function is parsed.
3048         auto &FwdBBs = BasicBlockFwdRefs[Fn];
3049         if (FwdBBs.empty())
3050           BasicBlockFwdRefQueue.push_back(Fn);
3051         if (FwdBBs.size() < BBID + 1)
3052           FwdBBs.resize(BBID + 1);
3053         if (!FwdBBs[BBID])
3054           FwdBBs[BBID] = BasicBlock::Create(Context);
3055         BB = FwdBBs[BBID];
3056       }
3057       V = BlockAddress::get(Fn, BB);
3058       break;
3059     }
3060     }
3061 
3062     ValueList.assignValue(V, NextCstNo);
3063     ++NextCstNo;
3064   }
3065 }
3066 
3067 std::error_code BitcodeReader::parseUseLists() {
3068   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3069     return error("Invalid record");
3070 
3071   // Read all the records.
3072   SmallVector<uint64_t, 64> Record;
3073   while (1) {
3074     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3075 
3076     switch (Entry.Kind) {
3077     case BitstreamEntry::SubBlock: // Handled for us already.
3078     case BitstreamEntry::Error:
3079       return error("Malformed block");
3080     case BitstreamEntry::EndBlock:
3081       return std::error_code();
3082     case BitstreamEntry::Record:
3083       // The interesting case.
3084       break;
3085     }
3086 
3087     // Read a use list record.
3088     Record.clear();
3089     bool IsBB = false;
3090     switch (Stream.readRecord(Entry.ID, Record)) {
3091     default:  // Default behavior: unknown type.
3092       break;
3093     case bitc::USELIST_CODE_BB:
3094       IsBB = true;
3095       // fallthrough
3096     case bitc::USELIST_CODE_DEFAULT: {
3097       unsigned RecordLength = Record.size();
3098       if (RecordLength < 3)
3099         // Records should have at least an ID and two indexes.
3100         return error("Invalid record");
3101       unsigned ID = Record.back();
3102       Record.pop_back();
3103 
3104       Value *V;
3105       if (IsBB) {
3106         assert(ID < FunctionBBs.size() && "Basic block not found");
3107         V = FunctionBBs[ID];
3108       } else
3109         V = ValueList[ID];
3110       unsigned NumUses = 0;
3111       SmallDenseMap<const Use *, unsigned, 16> Order;
3112       for (const Use &U : V->materialized_uses()) {
3113         if (++NumUses > Record.size())
3114           break;
3115         Order[&U] = Record[NumUses - 1];
3116       }
3117       if (Order.size() != Record.size() || NumUses > Record.size())
3118         // Mismatches can happen if the functions are being materialized lazily
3119         // (out-of-order), or a value has been upgraded.
3120         break;
3121 
3122       V->sortUseList([&](const Use &L, const Use &R) {
3123         return Order.lookup(&L) < Order.lookup(&R);
3124       });
3125       break;
3126     }
3127     }
3128   }
3129 }
3130 
3131 /// When we see the block for metadata, remember where it is and then skip it.
3132 /// This lets us lazily deserialize the metadata.
3133 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3134   // Save the current stream state.
3135   uint64_t CurBit = Stream.GetCurrentBitNo();
3136   DeferredMetadataInfo.push_back(CurBit);
3137 
3138   // Skip over the block for now.
3139   if (Stream.SkipBlock())
3140     return error("Invalid record");
3141   return std::error_code();
3142 }
3143 
3144 std::error_code BitcodeReader::materializeMetadata() {
3145   for (uint64_t BitPos : DeferredMetadataInfo) {
3146     // Move the bit stream to the saved position.
3147     Stream.JumpToBit(BitPos);
3148     if (std::error_code EC = parseMetadata(true))
3149       return EC;
3150   }
3151   DeferredMetadataInfo.clear();
3152   return std::error_code();
3153 }
3154 
3155 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3156 
3157 /// When we see the block for a function body, remember where it is and then
3158 /// skip it.  This lets us lazily deserialize the functions.
3159 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3160   // Get the function we are talking about.
3161   if (FunctionsWithBodies.empty())
3162     return error("Insufficient function protos");
3163 
3164   Function *Fn = FunctionsWithBodies.back();
3165   FunctionsWithBodies.pop_back();
3166 
3167   // Save the current stream state.
3168   uint64_t CurBit = Stream.GetCurrentBitNo();
3169   assert(
3170       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3171       "Mismatch between VST and scanned function offsets");
3172   DeferredFunctionInfo[Fn] = CurBit;
3173 
3174   // Skip over the function block for now.
3175   if (Stream.SkipBlock())
3176     return error("Invalid record");
3177   return std::error_code();
3178 }
3179 
3180 std::error_code BitcodeReader::globalCleanup() {
3181   // Patch the initializers for globals and aliases up.
3182   resolveGlobalAndIndirectSymbolInits();
3183   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3184     return error("Malformed global initializer set");
3185 
3186   // Look for intrinsic functions which need to be upgraded at some point
3187   for (Function &F : *TheModule) {
3188     Function *NewFn;
3189     if (UpgradeIntrinsicFunction(&F, NewFn))
3190       UpgradedIntrinsics[&F] = NewFn;
3191   }
3192 
3193   // Look for global variables which need to be renamed.
3194   for (GlobalVariable &GV : TheModule->globals())
3195     UpgradeGlobalVariable(&GV);
3196 
3197   // Force deallocation of memory for these vectors to favor the client that
3198   // want lazy deserialization.
3199   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3200   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3201       IndirectSymbolInits);
3202   return std::error_code();
3203 }
3204 
3205 /// Support for lazy parsing of function bodies. This is required if we
3206 /// either have an old bitcode file without a VST forward declaration record,
3207 /// or if we have an anonymous function being materialized, since anonymous
3208 /// functions do not have a name and are therefore not in the VST.
3209 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3210   Stream.JumpToBit(NextUnreadBit);
3211 
3212   if (Stream.AtEndOfStream())
3213     return error("Could not find function in stream");
3214 
3215   if (!SeenFirstFunctionBody)
3216     return error("Trying to materialize functions before seeing function blocks");
3217 
3218   // An old bitcode file with the symbol table at the end would have
3219   // finished the parse greedily.
3220   assert(SeenValueSymbolTable);
3221 
3222   SmallVector<uint64_t, 64> Record;
3223 
3224   while (1) {
3225     BitstreamEntry Entry = Stream.advance();
3226     switch (Entry.Kind) {
3227     default:
3228       return error("Expect SubBlock");
3229     case BitstreamEntry::SubBlock:
3230       switch (Entry.ID) {
3231       default:
3232         return error("Expect function block");
3233       case bitc::FUNCTION_BLOCK_ID:
3234         if (std::error_code EC = rememberAndSkipFunctionBody())
3235           return EC;
3236         NextUnreadBit = Stream.GetCurrentBitNo();
3237         return std::error_code();
3238       }
3239     }
3240   }
3241 }
3242 
3243 std::error_code BitcodeReader::parseBitcodeVersion() {
3244   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3245     return error("Invalid record");
3246 
3247   // Read all the records.
3248   SmallVector<uint64_t, 64> Record;
3249   while (1) {
3250     BitstreamEntry Entry = Stream.advance();
3251 
3252     switch (Entry.Kind) {
3253     default:
3254     case BitstreamEntry::Error:
3255       return error("Malformed block");
3256     case BitstreamEntry::EndBlock:
3257       return std::error_code();
3258     case BitstreamEntry::Record:
3259       // The interesting case.
3260       break;
3261     }
3262 
3263     // Read a record.
3264     Record.clear();
3265     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3266     switch (BitCode) {
3267     default: // Default behavior: reject
3268       return error("Invalid value");
3269     case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION:      [strchr x
3270                                              // N]
3271       convertToString(Record, 0, ProducerIdentification);
3272       break;
3273     }
3274     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH:      [epoch#]
3275       unsigned epoch = (unsigned)Record[0];
3276       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3277         return error(
3278           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3279           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3280       }
3281     }
3282     }
3283   }
3284 }
3285 
3286 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3287                                            bool ShouldLazyLoadMetadata) {
3288   if (ResumeBit)
3289     Stream.JumpToBit(ResumeBit);
3290   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3291     return error("Invalid record");
3292 
3293   SmallVector<uint64_t, 64> Record;
3294   std::vector<std::string> SectionTable;
3295   std::vector<std::string> GCTable;
3296 
3297   // Read all the records for this module.
3298   while (1) {
3299     BitstreamEntry Entry = Stream.advance();
3300 
3301     switch (Entry.Kind) {
3302     case BitstreamEntry::Error:
3303       return error("Malformed block");
3304     case BitstreamEntry::EndBlock:
3305       return globalCleanup();
3306 
3307     case BitstreamEntry::SubBlock:
3308       switch (Entry.ID) {
3309       default:  // Skip unknown content.
3310         if (Stream.SkipBlock())
3311           return error("Invalid record");
3312         break;
3313       case bitc::BLOCKINFO_BLOCK_ID:
3314         if (Stream.ReadBlockInfoBlock())
3315           return error("Malformed block");
3316         break;
3317       case bitc::PARAMATTR_BLOCK_ID:
3318         if (std::error_code EC = parseAttributeBlock())
3319           return EC;
3320         break;
3321       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3322         if (std::error_code EC = parseAttributeGroupBlock())
3323           return EC;
3324         break;
3325       case bitc::TYPE_BLOCK_ID_NEW:
3326         if (std::error_code EC = parseTypeTable())
3327           return EC;
3328         break;
3329       case bitc::VALUE_SYMTAB_BLOCK_ID:
3330         if (!SeenValueSymbolTable) {
3331           // Either this is an old form VST without function index and an
3332           // associated VST forward declaration record (which would have caused
3333           // the VST to be jumped to and parsed before it was encountered
3334           // normally in the stream), or there were no function blocks to
3335           // trigger an earlier parsing of the VST.
3336           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3337           if (std::error_code EC = parseValueSymbolTable())
3338             return EC;
3339           SeenValueSymbolTable = true;
3340         } else {
3341           // We must have had a VST forward declaration record, which caused
3342           // the parser to jump to and parse the VST earlier.
3343           assert(VSTOffset > 0);
3344           if (Stream.SkipBlock())
3345             return error("Invalid record");
3346         }
3347         break;
3348       case bitc::CONSTANTS_BLOCK_ID:
3349         if (std::error_code EC = parseConstants())
3350           return EC;
3351         if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
3352           return EC;
3353         break;
3354       case bitc::METADATA_BLOCK_ID:
3355         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3356           if (std::error_code EC = rememberAndSkipMetadata())
3357             return EC;
3358           break;
3359         }
3360         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3361         if (std::error_code EC = parseMetadata(true))
3362           return EC;
3363         break;
3364       case bitc::METADATA_KIND_BLOCK_ID:
3365         if (std::error_code EC = parseMetadataKinds())
3366           return EC;
3367         break;
3368       case bitc::FUNCTION_BLOCK_ID:
3369         // If this is the first function body we've seen, reverse the
3370         // FunctionsWithBodies list.
3371         if (!SeenFirstFunctionBody) {
3372           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3373           if (std::error_code EC = globalCleanup())
3374             return EC;
3375           SeenFirstFunctionBody = true;
3376         }
3377 
3378         if (VSTOffset > 0) {
3379           // If we have a VST forward declaration record, make sure we
3380           // parse the VST now if we haven't already. It is needed to
3381           // set up the DeferredFunctionInfo vector for lazy reading.
3382           if (!SeenValueSymbolTable) {
3383             if (std::error_code EC =
3384                     BitcodeReader::parseValueSymbolTable(VSTOffset))
3385               return EC;
3386             SeenValueSymbolTable = true;
3387             // Fall through so that we record the NextUnreadBit below.
3388             // This is necessary in case we have an anonymous function that
3389             // is later materialized. Since it will not have a VST entry we
3390             // need to fall back to the lazy parse to find its offset.
3391           } else {
3392             // If we have a VST forward declaration record, but have already
3393             // parsed the VST (just above, when the first function body was
3394             // encountered here), then we are resuming the parse after
3395             // materializing functions. The ResumeBit points to the
3396             // start of the last function block recorded in the
3397             // DeferredFunctionInfo map. Skip it.
3398             if (Stream.SkipBlock())
3399               return error("Invalid record");
3400             continue;
3401           }
3402         }
3403 
3404         // Support older bitcode files that did not have the function
3405         // index in the VST, nor a VST forward declaration record, as
3406         // well as anonymous functions that do not have VST entries.
3407         // Build the DeferredFunctionInfo vector on the fly.
3408         if (std::error_code EC = rememberAndSkipFunctionBody())
3409           return EC;
3410 
3411         // Suspend parsing when we reach the function bodies. Subsequent
3412         // materialization calls will resume it when necessary. If the bitcode
3413         // file is old, the symbol table will be at the end instead and will not
3414         // have been seen yet. In this case, just finish the parse now.
3415         if (SeenValueSymbolTable) {
3416           NextUnreadBit = Stream.GetCurrentBitNo();
3417           return std::error_code();
3418         }
3419         break;
3420       case bitc::USELIST_BLOCK_ID:
3421         if (std::error_code EC = parseUseLists())
3422           return EC;
3423         break;
3424       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3425         if (std::error_code EC = parseOperandBundleTags())
3426           return EC;
3427         break;
3428       }
3429       continue;
3430 
3431     case BitstreamEntry::Record:
3432       // The interesting case.
3433       break;
3434     }
3435 
3436     // Read a record.
3437     auto BitCode = Stream.readRecord(Entry.ID, Record);
3438     switch (BitCode) {
3439     default: break;  // Default behavior, ignore unknown content.
3440     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
3441       if (Record.size() < 1)
3442         return error("Invalid record");
3443       // Only version #0 and #1 are supported so far.
3444       unsigned module_version = Record[0];
3445       switch (module_version) {
3446         default:
3447           return error("Invalid value");
3448         case 0:
3449           UseRelativeIDs = false;
3450           break;
3451         case 1:
3452           UseRelativeIDs = true;
3453           break;
3454       }
3455       break;
3456     }
3457     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3458       std::string S;
3459       if (convertToString(Record, 0, S))
3460         return error("Invalid record");
3461       TheModule->setTargetTriple(S);
3462       break;
3463     }
3464     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3465       std::string S;
3466       if (convertToString(Record, 0, S))
3467         return error("Invalid record");
3468       TheModule->setDataLayout(S);
3469       break;
3470     }
3471     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3472       std::string S;
3473       if (convertToString(Record, 0, S))
3474         return error("Invalid record");
3475       TheModule->setModuleInlineAsm(S);
3476       break;
3477     }
3478     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3479       // FIXME: Remove in 4.0.
3480       std::string S;
3481       if (convertToString(Record, 0, S))
3482         return error("Invalid record");
3483       // Ignore value.
3484       break;
3485     }
3486     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3487       std::string S;
3488       if (convertToString(Record, 0, S))
3489         return error("Invalid record");
3490       SectionTable.push_back(S);
3491       break;
3492     }
3493     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3494       std::string S;
3495       if (convertToString(Record, 0, S))
3496         return error("Invalid record");
3497       GCTable.push_back(S);
3498       break;
3499     }
3500     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3501       if (Record.size() < 2)
3502         return error("Invalid record");
3503       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3504       unsigned ComdatNameSize = Record[1];
3505       std::string ComdatName;
3506       ComdatName.reserve(ComdatNameSize);
3507       for (unsigned i = 0; i != ComdatNameSize; ++i)
3508         ComdatName += (char)Record[2 + i];
3509       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3510       C->setSelectionKind(SK);
3511       ComdatList.push_back(C);
3512       break;
3513     }
3514     // GLOBALVAR: [pointer type, isconst, initid,
3515     //             linkage, alignment, section, visibility, threadlocal,
3516     //             unnamed_addr, externally_initialized, dllstorageclass,
3517     //             comdat]
3518     case bitc::MODULE_CODE_GLOBALVAR: {
3519       if (Record.size() < 6)
3520         return error("Invalid record");
3521       Type *Ty = getTypeByID(Record[0]);
3522       if (!Ty)
3523         return error("Invalid record");
3524       bool isConstant = Record[1] & 1;
3525       bool explicitType = Record[1] & 2;
3526       unsigned AddressSpace;
3527       if (explicitType) {
3528         AddressSpace = Record[1] >> 2;
3529       } else {
3530         if (!Ty->isPointerTy())
3531           return error("Invalid type for value");
3532         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3533         Ty = cast<PointerType>(Ty)->getElementType();
3534       }
3535 
3536       uint64_t RawLinkage = Record[3];
3537       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3538       unsigned Alignment;
3539       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3540         return EC;
3541       std::string Section;
3542       if (Record[5]) {
3543         if (Record[5]-1 >= SectionTable.size())
3544           return error("Invalid ID");
3545         Section = SectionTable[Record[5]-1];
3546       }
3547       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3548       // Local linkage must have default visibility.
3549       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3550         // FIXME: Change to an error if non-default in 4.0.
3551         Visibility = getDecodedVisibility(Record[6]);
3552 
3553       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3554       if (Record.size() > 7)
3555         TLM = getDecodedThreadLocalMode(Record[7]);
3556 
3557       bool UnnamedAddr = false;
3558       if (Record.size() > 8)
3559         UnnamedAddr = Record[8];
3560 
3561       bool ExternallyInitialized = false;
3562       if (Record.size() > 9)
3563         ExternallyInitialized = Record[9];
3564 
3565       GlobalVariable *NewGV =
3566         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3567                            TLM, AddressSpace, ExternallyInitialized);
3568       NewGV->setAlignment(Alignment);
3569       if (!Section.empty())
3570         NewGV->setSection(Section);
3571       NewGV->setVisibility(Visibility);
3572       NewGV->setUnnamedAddr(UnnamedAddr);
3573 
3574       if (Record.size() > 10)
3575         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3576       else
3577         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3578 
3579       ValueList.push_back(NewGV);
3580 
3581       // Remember which value to use for the global initializer.
3582       if (unsigned InitID = Record[2])
3583         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3584 
3585       if (Record.size() > 11) {
3586         if (unsigned ComdatID = Record[11]) {
3587           if (ComdatID > ComdatList.size())
3588             return error("Invalid global variable comdat ID");
3589           NewGV->setComdat(ComdatList[ComdatID - 1]);
3590         }
3591       } else if (hasImplicitComdat(RawLinkage)) {
3592         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3593       }
3594       break;
3595     }
3596     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
3597     //             alignment, section, visibility, gc, unnamed_addr,
3598     //             prologuedata, dllstorageclass, comdat, prefixdata]
3599     case bitc::MODULE_CODE_FUNCTION: {
3600       if (Record.size() < 8)
3601         return error("Invalid record");
3602       Type *Ty = getTypeByID(Record[0]);
3603       if (!Ty)
3604         return error("Invalid record");
3605       if (auto *PTy = dyn_cast<PointerType>(Ty))
3606         Ty = PTy->getElementType();
3607       auto *FTy = dyn_cast<FunctionType>(Ty);
3608       if (!FTy)
3609         return error("Invalid type for value");
3610       auto CC = static_cast<CallingConv::ID>(Record[1]);
3611       if (CC & ~CallingConv::MaxID)
3612         return error("Invalid calling convention ID");
3613 
3614       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3615                                         "", TheModule);
3616 
3617       Func->setCallingConv(CC);
3618       bool isProto = Record[2];
3619       uint64_t RawLinkage = Record[3];
3620       Func->setLinkage(getDecodedLinkage(RawLinkage));
3621       Func->setAttributes(getAttributes(Record[4]));
3622 
3623       unsigned Alignment;
3624       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3625         return EC;
3626       Func->setAlignment(Alignment);
3627       if (Record[6]) {
3628         if (Record[6]-1 >= SectionTable.size())
3629           return error("Invalid ID");
3630         Func->setSection(SectionTable[Record[6]-1]);
3631       }
3632       // Local linkage must have default visibility.
3633       if (!Func->hasLocalLinkage())
3634         // FIXME: Change to an error if non-default in 4.0.
3635         Func->setVisibility(getDecodedVisibility(Record[7]));
3636       if (Record.size() > 8 && Record[8]) {
3637         if (Record[8]-1 >= GCTable.size())
3638           return error("Invalid ID");
3639         Func->setGC(GCTable[Record[8]-1].c_str());
3640       }
3641       bool UnnamedAddr = false;
3642       if (Record.size() > 9)
3643         UnnamedAddr = Record[9];
3644       Func->setUnnamedAddr(UnnamedAddr);
3645       if (Record.size() > 10 && Record[10] != 0)
3646         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3647 
3648       if (Record.size() > 11)
3649         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3650       else
3651         upgradeDLLImportExportLinkage(Func, RawLinkage);
3652 
3653       if (Record.size() > 12) {
3654         if (unsigned ComdatID = Record[12]) {
3655           if (ComdatID > ComdatList.size())
3656             return error("Invalid function comdat ID");
3657           Func->setComdat(ComdatList[ComdatID - 1]);
3658         }
3659       } else if (hasImplicitComdat(RawLinkage)) {
3660         Func->setComdat(reinterpret_cast<Comdat *>(1));
3661       }
3662 
3663       if (Record.size() > 13 && Record[13] != 0)
3664         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3665 
3666       if (Record.size() > 14 && Record[14] != 0)
3667         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3668 
3669       ValueList.push_back(Func);
3670 
3671       // If this is a function with a body, remember the prototype we are
3672       // creating now, so that we can match up the body with them later.
3673       if (!isProto) {
3674         Func->setIsMaterializable(true);
3675         FunctionsWithBodies.push_back(Func);
3676         DeferredFunctionInfo[Func] = 0;
3677       }
3678       break;
3679     }
3680     // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3681     // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3682     // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3683     case bitc::MODULE_CODE_IFUNC:
3684     case bitc::MODULE_CODE_ALIAS:
3685     case bitc::MODULE_CODE_ALIAS_OLD: {
3686       bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3687       if (Record.size() < (3 + (unsigned)NewRecord))
3688         return error("Invalid record");
3689       unsigned OpNum = 0;
3690       Type *Ty = getTypeByID(Record[OpNum++]);
3691       if (!Ty)
3692         return error("Invalid record");
3693 
3694       unsigned AddrSpace;
3695       if (!NewRecord) {
3696         auto *PTy = dyn_cast<PointerType>(Ty);
3697         if (!PTy)
3698           return error("Invalid type for value");
3699         Ty = PTy->getElementType();
3700         AddrSpace = PTy->getAddressSpace();
3701       } else {
3702         AddrSpace = Record[OpNum++];
3703       }
3704 
3705       auto Val = Record[OpNum++];
3706       auto Linkage = Record[OpNum++];
3707       GlobalIndirectSymbol *NewGA;
3708       if (BitCode == bitc::MODULE_CODE_ALIAS ||
3709           BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3710         NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3711                                     "", TheModule);
3712       else
3713         NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3714                                     "", nullptr, TheModule);
3715       // Old bitcode files didn't have visibility field.
3716       // Local linkage must have default visibility.
3717       if (OpNum != Record.size()) {
3718         auto VisInd = OpNum++;
3719         if (!NewGA->hasLocalLinkage())
3720           // FIXME: Change to an error if non-default in 4.0.
3721           NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3722       }
3723       if (OpNum != Record.size())
3724         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3725       else
3726         upgradeDLLImportExportLinkage(NewGA, Linkage);
3727       if (OpNum != Record.size())
3728         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3729       if (OpNum != Record.size())
3730         NewGA->setUnnamedAddr(Record[OpNum++]);
3731       ValueList.push_back(NewGA);
3732       IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3733       break;
3734     }
3735     /// MODULE_CODE_PURGEVALS: [numvals]
3736     case bitc::MODULE_CODE_PURGEVALS:
3737       // Trim down the value list to the specified size.
3738       if (Record.size() < 1 || Record[0] > ValueList.size())
3739         return error("Invalid record");
3740       ValueList.shrinkTo(Record[0]);
3741       break;
3742     /// MODULE_CODE_VSTOFFSET: [offset]
3743     case bitc::MODULE_CODE_VSTOFFSET:
3744       if (Record.size() < 1)
3745         return error("Invalid record");
3746       VSTOffset = Record[0];
3747       break;
3748     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3749     case bitc::MODULE_CODE_SOURCE_FILENAME:
3750       SmallString<128> ValueName;
3751       if (convertToString(Record, 0, ValueName))
3752         return error("Invalid record");
3753       TheModule->setSourceFileName(ValueName);
3754       break;
3755     }
3756     Record.clear();
3757   }
3758 }
3759 
3760 /// Helper to read the header common to all bitcode files.
3761 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3762   // Sniff for the signature.
3763   if (Stream.Read(8) != 'B' ||
3764       Stream.Read(8) != 'C' ||
3765       Stream.Read(4) != 0x0 ||
3766       Stream.Read(4) != 0xC ||
3767       Stream.Read(4) != 0xE ||
3768       Stream.Read(4) != 0xD)
3769     return false;
3770   return true;
3771 }
3772 
3773 std::error_code
3774 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3775                                 Module *M, bool ShouldLazyLoadMetadata) {
3776   TheModule = M;
3777 
3778   if (std::error_code EC = initStream(std::move(Streamer)))
3779     return EC;
3780 
3781   // Sniff for the signature.
3782   if (!hasValidBitcodeHeader(Stream))
3783     return error("Invalid bitcode signature");
3784 
3785   // We expect a number of well-defined blocks, though we don't necessarily
3786   // need to understand them all.
3787   while (1) {
3788     if (Stream.AtEndOfStream()) {
3789       // We didn't really read a proper Module.
3790       return error("Malformed IR file");
3791     }
3792 
3793     BitstreamEntry Entry =
3794       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3795 
3796     if (Entry.Kind != BitstreamEntry::SubBlock)
3797       return error("Malformed block");
3798 
3799     if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3800       parseBitcodeVersion();
3801       continue;
3802     }
3803 
3804     if (Entry.ID == bitc::MODULE_BLOCK_ID)
3805       return parseModule(0, ShouldLazyLoadMetadata);
3806 
3807     if (Stream.SkipBlock())
3808       return error("Invalid record");
3809   }
3810 }
3811 
3812 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3813   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3814     return error("Invalid record");
3815 
3816   SmallVector<uint64_t, 64> Record;
3817 
3818   std::string Triple;
3819   // Read all the records for this module.
3820   while (1) {
3821     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3822 
3823     switch (Entry.Kind) {
3824     case BitstreamEntry::SubBlock: // Handled for us already.
3825     case BitstreamEntry::Error:
3826       return error("Malformed block");
3827     case BitstreamEntry::EndBlock:
3828       return Triple;
3829     case BitstreamEntry::Record:
3830       // The interesting case.
3831       break;
3832     }
3833 
3834     // Read a record.
3835     switch (Stream.readRecord(Entry.ID, Record)) {
3836     default: break;  // Default behavior, ignore unknown content.
3837     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3838       std::string S;
3839       if (convertToString(Record, 0, S))
3840         return error("Invalid record");
3841       Triple = S;
3842       break;
3843     }
3844     }
3845     Record.clear();
3846   }
3847   llvm_unreachable("Exit infinite loop");
3848 }
3849 
3850 ErrorOr<std::string> BitcodeReader::parseTriple() {
3851   if (std::error_code EC = initStream(nullptr))
3852     return EC;
3853 
3854   // Sniff for the signature.
3855   if (!hasValidBitcodeHeader(Stream))
3856     return error("Invalid bitcode signature");
3857 
3858   // We expect a number of well-defined blocks, though we don't necessarily
3859   // need to understand them all.
3860   while (1) {
3861     BitstreamEntry Entry = Stream.advance();
3862 
3863     switch (Entry.Kind) {
3864     case BitstreamEntry::Error:
3865       return error("Malformed block");
3866     case BitstreamEntry::EndBlock:
3867       return std::error_code();
3868 
3869     case BitstreamEntry::SubBlock:
3870       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3871         return parseModuleTriple();
3872 
3873       // Ignore other sub-blocks.
3874       if (Stream.SkipBlock())
3875         return error("Malformed block");
3876       continue;
3877 
3878     case BitstreamEntry::Record:
3879       Stream.skipRecord(Entry.ID);
3880       continue;
3881     }
3882   }
3883 }
3884 
3885 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3886   if (std::error_code EC = initStream(nullptr))
3887     return EC;
3888 
3889   // Sniff for the signature.
3890   if (!hasValidBitcodeHeader(Stream))
3891     return error("Invalid bitcode signature");
3892 
3893   // We expect a number of well-defined blocks, though we don't necessarily
3894   // need to understand them all.
3895   while (1) {
3896     BitstreamEntry Entry = Stream.advance();
3897     switch (Entry.Kind) {
3898     case BitstreamEntry::Error:
3899       return error("Malformed block");
3900     case BitstreamEntry::EndBlock:
3901       return std::error_code();
3902 
3903     case BitstreamEntry::SubBlock:
3904       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3905         if (std::error_code EC = parseBitcodeVersion())
3906           return EC;
3907         return ProducerIdentification;
3908       }
3909       // Ignore other sub-blocks.
3910       if (Stream.SkipBlock())
3911         return error("Malformed block");
3912       continue;
3913     case BitstreamEntry::Record:
3914       Stream.skipRecord(Entry.ID);
3915       continue;
3916     }
3917   }
3918 }
3919 
3920 /// Parse metadata attachments.
3921 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3922   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3923     return error("Invalid record");
3924 
3925   SmallVector<uint64_t, 64> Record;
3926   while (1) {
3927     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3928 
3929     switch (Entry.Kind) {
3930     case BitstreamEntry::SubBlock: // Handled for us already.
3931     case BitstreamEntry::Error:
3932       return error("Malformed block");
3933     case BitstreamEntry::EndBlock:
3934       return std::error_code();
3935     case BitstreamEntry::Record:
3936       // The interesting case.
3937       break;
3938     }
3939 
3940     // Read a metadata attachment record.
3941     Record.clear();
3942     switch (Stream.readRecord(Entry.ID, Record)) {
3943     default:  // Default behavior: ignore.
3944       break;
3945     case bitc::METADATA_ATTACHMENT: {
3946       unsigned RecordLength = Record.size();
3947       if (Record.empty())
3948         return error("Invalid record");
3949       if (RecordLength % 2 == 0) {
3950         // A function attachment.
3951         for (unsigned I = 0; I != RecordLength; I += 2) {
3952           auto K = MDKindMap.find(Record[I]);
3953           if (K == MDKindMap.end())
3954             return error("Invalid ID");
3955           MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
3956           if (!MD)
3957             return error("Invalid metadata attachment");
3958           F.setMetadata(K->second, MD);
3959         }
3960         continue;
3961       }
3962 
3963       // An instruction attachment.
3964       Instruction *Inst = InstructionList[Record[0]];
3965       for (unsigned i = 1; i != RecordLength; i = i+2) {
3966         unsigned Kind = Record[i];
3967         DenseMap<unsigned, unsigned>::iterator I =
3968           MDKindMap.find(Kind);
3969         if (I == MDKindMap.end())
3970           return error("Invalid ID");
3971         Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
3972         if (isa<LocalAsMetadata>(Node))
3973           // Drop the attachment.  This used to be legal, but there's no
3974           // upgrade path.
3975           break;
3976         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
3977         if (!MD)
3978           return error("Invalid metadata attachment");
3979 
3980         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
3981           MD = upgradeInstructionLoopAttachment(*MD);
3982 
3983         Inst->setMetadata(I->second, MD);
3984         if (I->second == LLVMContext::MD_tbaa) {
3985           InstsWithTBAATag.push_back(Inst);
3986           continue;
3987         }
3988       }
3989       break;
3990     }
3991     }
3992   }
3993 }
3994 
3995 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3996   LLVMContext &Context = PtrType->getContext();
3997   if (!isa<PointerType>(PtrType))
3998     return error(Context, "Load/Store operand is not a pointer type");
3999   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4000 
4001   if (ValType && ValType != ElemType)
4002     return error(Context, "Explicit load/store type does not match pointee "
4003                           "type of pointer operand");
4004   if (!PointerType::isLoadableOrStorableType(ElemType))
4005     return error(Context, "Cannot load/store from pointer");
4006   return std::error_code();
4007 }
4008 
4009 /// Lazily parse the specified function body block.
4010 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
4011   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4012     return error("Invalid record");
4013 
4014   // Unexpected unresolved metadata when parsing function.
4015   if (MetadataList.hasFwdRefs())
4016     return error("Invalid function metadata: incoming forward references");
4017 
4018   InstructionList.clear();
4019   unsigned ModuleValueListSize = ValueList.size();
4020   unsigned ModuleMetadataListSize = MetadataList.size();
4021 
4022   // Add all the function arguments to the value table.
4023   for (Argument &I : F->args())
4024     ValueList.push_back(&I);
4025 
4026   unsigned NextValueNo = ValueList.size();
4027   BasicBlock *CurBB = nullptr;
4028   unsigned CurBBNo = 0;
4029 
4030   DebugLoc LastLoc;
4031   auto getLastInstruction = [&]() -> Instruction * {
4032     if (CurBB && !CurBB->empty())
4033       return &CurBB->back();
4034     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4035              !FunctionBBs[CurBBNo - 1]->empty())
4036       return &FunctionBBs[CurBBNo - 1]->back();
4037     return nullptr;
4038   };
4039 
4040   std::vector<OperandBundleDef> OperandBundles;
4041 
4042   // Read all the records.
4043   SmallVector<uint64_t, 64> Record;
4044   while (1) {
4045     BitstreamEntry Entry = Stream.advance();
4046 
4047     switch (Entry.Kind) {
4048     case BitstreamEntry::Error:
4049       return error("Malformed block");
4050     case BitstreamEntry::EndBlock:
4051       goto OutOfRecordLoop;
4052 
4053     case BitstreamEntry::SubBlock:
4054       switch (Entry.ID) {
4055       default:  // Skip unknown content.
4056         if (Stream.SkipBlock())
4057           return error("Invalid record");
4058         break;
4059       case bitc::CONSTANTS_BLOCK_ID:
4060         if (std::error_code EC = parseConstants())
4061           return EC;
4062         NextValueNo = ValueList.size();
4063         break;
4064       case bitc::VALUE_SYMTAB_BLOCK_ID:
4065         if (std::error_code EC = parseValueSymbolTable())
4066           return EC;
4067         break;
4068       case bitc::METADATA_ATTACHMENT_ID:
4069         if (std::error_code EC = parseMetadataAttachment(*F))
4070           return EC;
4071         break;
4072       case bitc::METADATA_BLOCK_ID:
4073         if (std::error_code EC = parseMetadata())
4074           return EC;
4075         break;
4076       case bitc::USELIST_BLOCK_ID:
4077         if (std::error_code EC = parseUseLists())
4078           return EC;
4079         break;
4080       }
4081       continue;
4082 
4083     case BitstreamEntry::Record:
4084       // The interesting case.
4085       break;
4086     }
4087 
4088     // Read a record.
4089     Record.clear();
4090     Instruction *I = nullptr;
4091     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4092     switch (BitCode) {
4093     default: // Default behavior: reject
4094       return error("Invalid value");
4095     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4096       if (Record.size() < 1 || Record[0] == 0)
4097         return error("Invalid record");
4098       // Create all the basic blocks for the function.
4099       FunctionBBs.resize(Record[0]);
4100 
4101       // See if anything took the address of blocks in this function.
4102       auto BBFRI = BasicBlockFwdRefs.find(F);
4103       if (BBFRI == BasicBlockFwdRefs.end()) {
4104         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4105           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4106       } else {
4107         auto &BBRefs = BBFRI->second;
4108         // Check for invalid basic block references.
4109         if (BBRefs.size() > FunctionBBs.size())
4110           return error("Invalid ID");
4111         assert(!BBRefs.empty() && "Unexpected empty array");
4112         assert(!BBRefs.front() && "Invalid reference to entry block");
4113         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4114              ++I)
4115           if (I < RE && BBRefs[I]) {
4116             BBRefs[I]->insertInto(F);
4117             FunctionBBs[I] = BBRefs[I];
4118           } else {
4119             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4120           }
4121 
4122         // Erase from the table.
4123         BasicBlockFwdRefs.erase(BBFRI);
4124       }
4125 
4126       CurBB = FunctionBBs[0];
4127       continue;
4128     }
4129 
4130     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4131       // This record indicates that the last instruction is at the same
4132       // location as the previous instruction with a location.
4133       I = getLastInstruction();
4134 
4135       if (!I)
4136         return error("Invalid record");
4137       I->setDebugLoc(LastLoc);
4138       I = nullptr;
4139       continue;
4140 
4141     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4142       I = getLastInstruction();
4143       if (!I || Record.size() < 4)
4144         return error("Invalid record");
4145 
4146       unsigned Line = Record[0], Col = Record[1];
4147       unsigned ScopeID = Record[2], IAID = Record[3];
4148 
4149       MDNode *Scope = nullptr, *IA = nullptr;
4150       if (ScopeID) {
4151         Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4152         if (!Scope)
4153           return error("Invalid record");
4154       }
4155       if (IAID) {
4156         IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4157         if (!IA)
4158           return error("Invalid record");
4159       }
4160       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4161       I->setDebugLoc(LastLoc);
4162       I = nullptr;
4163       continue;
4164     }
4165 
4166     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4167       unsigned OpNum = 0;
4168       Value *LHS, *RHS;
4169       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4170           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4171           OpNum+1 > Record.size())
4172         return error("Invalid record");
4173 
4174       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4175       if (Opc == -1)
4176         return error("Invalid record");
4177       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4178       InstructionList.push_back(I);
4179       if (OpNum < Record.size()) {
4180         if (Opc == Instruction::Add ||
4181             Opc == Instruction::Sub ||
4182             Opc == Instruction::Mul ||
4183             Opc == Instruction::Shl) {
4184           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4185             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4186           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4187             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4188         } else if (Opc == Instruction::SDiv ||
4189                    Opc == Instruction::UDiv ||
4190                    Opc == Instruction::LShr ||
4191                    Opc == Instruction::AShr) {
4192           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4193             cast<BinaryOperator>(I)->setIsExact(true);
4194         } else if (isa<FPMathOperator>(I)) {
4195           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4196           if (FMF.any())
4197             I->setFastMathFlags(FMF);
4198         }
4199 
4200       }
4201       break;
4202     }
4203     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4204       unsigned OpNum = 0;
4205       Value *Op;
4206       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4207           OpNum+2 != Record.size())
4208         return error("Invalid record");
4209 
4210       Type *ResTy = getTypeByID(Record[OpNum]);
4211       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4212       if (Opc == -1 || !ResTy)
4213         return error("Invalid record");
4214       Instruction *Temp = nullptr;
4215       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4216         if (Temp) {
4217           InstructionList.push_back(Temp);
4218           CurBB->getInstList().push_back(Temp);
4219         }
4220       } else {
4221         auto CastOp = (Instruction::CastOps)Opc;
4222         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4223           return error("Invalid cast");
4224         I = CastInst::Create(CastOp, Op, ResTy);
4225       }
4226       InstructionList.push_back(I);
4227       break;
4228     }
4229     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4230     case bitc::FUNC_CODE_INST_GEP_OLD:
4231     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4232       unsigned OpNum = 0;
4233 
4234       Type *Ty;
4235       bool InBounds;
4236 
4237       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4238         InBounds = Record[OpNum++];
4239         Ty = getTypeByID(Record[OpNum++]);
4240       } else {
4241         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4242         Ty = nullptr;
4243       }
4244 
4245       Value *BasePtr;
4246       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4247         return error("Invalid record");
4248 
4249       if (!Ty)
4250         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4251                  ->getElementType();
4252       else if (Ty !=
4253                cast<SequentialType>(BasePtr->getType()->getScalarType())
4254                    ->getElementType())
4255         return error(
4256             "Explicit gep type does not match pointee type of pointer operand");
4257 
4258       SmallVector<Value*, 16> GEPIdx;
4259       while (OpNum != Record.size()) {
4260         Value *Op;
4261         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4262           return error("Invalid record");
4263         GEPIdx.push_back(Op);
4264       }
4265 
4266       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4267 
4268       InstructionList.push_back(I);
4269       if (InBounds)
4270         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4271       break;
4272     }
4273 
4274     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4275                                        // EXTRACTVAL: [opty, opval, n x indices]
4276       unsigned OpNum = 0;
4277       Value *Agg;
4278       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4279         return error("Invalid record");
4280 
4281       unsigned RecSize = Record.size();
4282       if (OpNum == RecSize)
4283         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4284 
4285       SmallVector<unsigned, 4> EXTRACTVALIdx;
4286       Type *CurTy = Agg->getType();
4287       for (; OpNum != RecSize; ++OpNum) {
4288         bool IsArray = CurTy->isArrayTy();
4289         bool IsStruct = CurTy->isStructTy();
4290         uint64_t Index = Record[OpNum];
4291 
4292         if (!IsStruct && !IsArray)
4293           return error("EXTRACTVAL: Invalid type");
4294         if ((unsigned)Index != Index)
4295           return error("Invalid value");
4296         if (IsStruct && Index >= CurTy->subtypes().size())
4297           return error("EXTRACTVAL: Invalid struct index");
4298         if (IsArray && Index >= CurTy->getArrayNumElements())
4299           return error("EXTRACTVAL: Invalid array index");
4300         EXTRACTVALIdx.push_back((unsigned)Index);
4301 
4302         if (IsStruct)
4303           CurTy = CurTy->subtypes()[Index];
4304         else
4305           CurTy = CurTy->subtypes()[0];
4306       }
4307 
4308       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4309       InstructionList.push_back(I);
4310       break;
4311     }
4312 
4313     case bitc::FUNC_CODE_INST_INSERTVAL: {
4314                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4315       unsigned OpNum = 0;
4316       Value *Agg;
4317       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4318         return error("Invalid record");
4319       Value *Val;
4320       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4321         return error("Invalid record");
4322 
4323       unsigned RecSize = Record.size();
4324       if (OpNum == RecSize)
4325         return error("INSERTVAL: Invalid instruction with 0 indices");
4326 
4327       SmallVector<unsigned, 4> INSERTVALIdx;
4328       Type *CurTy = Agg->getType();
4329       for (; OpNum != RecSize; ++OpNum) {
4330         bool IsArray = CurTy->isArrayTy();
4331         bool IsStruct = CurTy->isStructTy();
4332         uint64_t Index = Record[OpNum];
4333 
4334         if (!IsStruct && !IsArray)
4335           return error("INSERTVAL: Invalid type");
4336         if ((unsigned)Index != Index)
4337           return error("Invalid value");
4338         if (IsStruct && Index >= CurTy->subtypes().size())
4339           return error("INSERTVAL: Invalid struct index");
4340         if (IsArray && Index >= CurTy->getArrayNumElements())
4341           return error("INSERTVAL: Invalid array index");
4342 
4343         INSERTVALIdx.push_back((unsigned)Index);
4344         if (IsStruct)
4345           CurTy = CurTy->subtypes()[Index];
4346         else
4347           CurTy = CurTy->subtypes()[0];
4348       }
4349 
4350       if (CurTy != Val->getType())
4351         return error("Inserted value type doesn't match aggregate type");
4352 
4353       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4354       InstructionList.push_back(I);
4355       break;
4356     }
4357 
4358     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4359       // obsolete form of select
4360       // handles select i1 ... in old bitcode
4361       unsigned OpNum = 0;
4362       Value *TrueVal, *FalseVal, *Cond;
4363       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4364           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4365           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4366         return error("Invalid record");
4367 
4368       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4369       InstructionList.push_back(I);
4370       break;
4371     }
4372 
4373     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4374       // new form of select
4375       // handles select i1 or select [N x i1]
4376       unsigned OpNum = 0;
4377       Value *TrueVal, *FalseVal, *Cond;
4378       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4379           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4380           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4381         return error("Invalid record");
4382 
4383       // select condition can be either i1 or [N x i1]
4384       if (VectorType* vector_type =
4385           dyn_cast<VectorType>(Cond->getType())) {
4386         // expect <n x i1>
4387         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4388           return error("Invalid type for value");
4389       } else {
4390         // expect i1
4391         if (Cond->getType() != Type::getInt1Ty(Context))
4392           return error("Invalid type for value");
4393       }
4394 
4395       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4396       InstructionList.push_back(I);
4397       break;
4398     }
4399 
4400     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4401       unsigned OpNum = 0;
4402       Value *Vec, *Idx;
4403       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4404           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4405         return error("Invalid record");
4406       if (!Vec->getType()->isVectorTy())
4407         return error("Invalid type for value");
4408       I = ExtractElementInst::Create(Vec, Idx);
4409       InstructionList.push_back(I);
4410       break;
4411     }
4412 
4413     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4414       unsigned OpNum = 0;
4415       Value *Vec, *Elt, *Idx;
4416       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4417         return error("Invalid record");
4418       if (!Vec->getType()->isVectorTy())
4419         return error("Invalid type for value");
4420       if (popValue(Record, OpNum, NextValueNo,
4421                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4422           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4423         return error("Invalid record");
4424       I = InsertElementInst::Create(Vec, Elt, Idx);
4425       InstructionList.push_back(I);
4426       break;
4427     }
4428 
4429     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4430       unsigned OpNum = 0;
4431       Value *Vec1, *Vec2, *Mask;
4432       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4433           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4434         return error("Invalid record");
4435 
4436       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4437         return error("Invalid record");
4438       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4439         return error("Invalid type for value");
4440       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4441       InstructionList.push_back(I);
4442       break;
4443     }
4444 
4445     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4446       // Old form of ICmp/FCmp returning bool
4447       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4448       // both legal on vectors but had different behaviour.
4449     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4450       // FCmp/ICmp returning bool or vector of bool
4451 
4452       unsigned OpNum = 0;
4453       Value *LHS, *RHS;
4454       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4455           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4456         return error("Invalid record");
4457 
4458       unsigned PredVal = Record[OpNum];
4459       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4460       FastMathFlags FMF;
4461       if (IsFP && Record.size() > OpNum+1)
4462         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4463 
4464       if (OpNum+1 != Record.size())
4465         return error("Invalid record");
4466 
4467       if (LHS->getType()->isFPOrFPVectorTy())
4468         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4469       else
4470         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4471 
4472       if (FMF.any())
4473         I->setFastMathFlags(FMF);
4474       InstructionList.push_back(I);
4475       break;
4476     }
4477 
4478     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4479       {
4480         unsigned Size = Record.size();
4481         if (Size == 0) {
4482           I = ReturnInst::Create(Context);
4483           InstructionList.push_back(I);
4484           break;
4485         }
4486 
4487         unsigned OpNum = 0;
4488         Value *Op = nullptr;
4489         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4490           return error("Invalid record");
4491         if (OpNum != Record.size())
4492           return error("Invalid record");
4493 
4494         I = ReturnInst::Create(Context, Op);
4495         InstructionList.push_back(I);
4496         break;
4497       }
4498     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4499       if (Record.size() != 1 && Record.size() != 3)
4500         return error("Invalid record");
4501       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4502       if (!TrueDest)
4503         return error("Invalid record");
4504 
4505       if (Record.size() == 1) {
4506         I = BranchInst::Create(TrueDest);
4507         InstructionList.push_back(I);
4508       }
4509       else {
4510         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4511         Value *Cond = getValue(Record, 2, NextValueNo,
4512                                Type::getInt1Ty(Context));
4513         if (!FalseDest || !Cond)
4514           return error("Invalid record");
4515         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4516         InstructionList.push_back(I);
4517       }
4518       break;
4519     }
4520     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4521       if (Record.size() != 1 && Record.size() != 2)
4522         return error("Invalid record");
4523       unsigned Idx = 0;
4524       Value *CleanupPad =
4525           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4526       if (!CleanupPad)
4527         return error("Invalid record");
4528       BasicBlock *UnwindDest = nullptr;
4529       if (Record.size() == 2) {
4530         UnwindDest = getBasicBlock(Record[Idx++]);
4531         if (!UnwindDest)
4532           return error("Invalid record");
4533       }
4534 
4535       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4536       InstructionList.push_back(I);
4537       break;
4538     }
4539     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4540       if (Record.size() != 2)
4541         return error("Invalid record");
4542       unsigned Idx = 0;
4543       Value *CatchPad =
4544           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4545       if (!CatchPad)
4546         return error("Invalid record");
4547       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4548       if (!BB)
4549         return error("Invalid record");
4550 
4551       I = CatchReturnInst::Create(CatchPad, BB);
4552       InstructionList.push_back(I);
4553       break;
4554     }
4555     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4556       // We must have, at minimum, the outer scope and the number of arguments.
4557       if (Record.size() < 2)
4558         return error("Invalid record");
4559 
4560       unsigned Idx = 0;
4561 
4562       Value *ParentPad =
4563           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4564 
4565       unsigned NumHandlers = Record[Idx++];
4566 
4567       SmallVector<BasicBlock *, 2> Handlers;
4568       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4569         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4570         if (!BB)
4571           return error("Invalid record");
4572         Handlers.push_back(BB);
4573       }
4574 
4575       BasicBlock *UnwindDest = nullptr;
4576       if (Idx + 1 == Record.size()) {
4577         UnwindDest = getBasicBlock(Record[Idx++]);
4578         if (!UnwindDest)
4579           return error("Invalid record");
4580       }
4581 
4582       if (Record.size() != Idx)
4583         return error("Invalid record");
4584 
4585       auto *CatchSwitch =
4586           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4587       for (BasicBlock *Handler : Handlers)
4588         CatchSwitch->addHandler(Handler);
4589       I = CatchSwitch;
4590       InstructionList.push_back(I);
4591       break;
4592     }
4593     case bitc::FUNC_CODE_INST_CATCHPAD:
4594     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4595       // We must have, at minimum, the outer scope and the number of arguments.
4596       if (Record.size() < 2)
4597         return error("Invalid record");
4598 
4599       unsigned Idx = 0;
4600 
4601       Value *ParentPad =
4602           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4603 
4604       unsigned NumArgOperands = Record[Idx++];
4605 
4606       SmallVector<Value *, 2> Args;
4607       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4608         Value *Val;
4609         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4610           return error("Invalid record");
4611         Args.push_back(Val);
4612       }
4613 
4614       if (Record.size() != Idx)
4615         return error("Invalid record");
4616 
4617       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4618         I = CleanupPadInst::Create(ParentPad, Args);
4619       else
4620         I = CatchPadInst::Create(ParentPad, Args);
4621       InstructionList.push_back(I);
4622       break;
4623     }
4624     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4625       // Check magic
4626       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4627         // "New" SwitchInst format with case ranges. The changes to write this
4628         // format were reverted but we still recognize bitcode that uses it.
4629         // Hopefully someday we will have support for case ranges and can use
4630         // this format again.
4631 
4632         Type *OpTy = getTypeByID(Record[1]);
4633         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4634 
4635         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4636         BasicBlock *Default = getBasicBlock(Record[3]);
4637         if (!OpTy || !Cond || !Default)
4638           return error("Invalid record");
4639 
4640         unsigned NumCases = Record[4];
4641 
4642         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4643         InstructionList.push_back(SI);
4644 
4645         unsigned CurIdx = 5;
4646         for (unsigned i = 0; i != NumCases; ++i) {
4647           SmallVector<ConstantInt*, 1> CaseVals;
4648           unsigned NumItems = Record[CurIdx++];
4649           for (unsigned ci = 0; ci != NumItems; ++ci) {
4650             bool isSingleNumber = Record[CurIdx++];
4651 
4652             APInt Low;
4653             unsigned ActiveWords = 1;
4654             if (ValueBitWidth > 64)
4655               ActiveWords = Record[CurIdx++];
4656             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4657                                 ValueBitWidth);
4658             CurIdx += ActiveWords;
4659 
4660             if (!isSingleNumber) {
4661               ActiveWords = 1;
4662               if (ValueBitWidth > 64)
4663                 ActiveWords = Record[CurIdx++];
4664               APInt High = readWideAPInt(
4665                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4666               CurIdx += ActiveWords;
4667 
4668               // FIXME: It is not clear whether values in the range should be
4669               // compared as signed or unsigned values. The partially
4670               // implemented changes that used this format in the past used
4671               // unsigned comparisons.
4672               for ( ; Low.ule(High); ++Low)
4673                 CaseVals.push_back(ConstantInt::get(Context, Low));
4674             } else
4675               CaseVals.push_back(ConstantInt::get(Context, Low));
4676           }
4677           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4678           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4679                  cve = CaseVals.end(); cvi != cve; ++cvi)
4680             SI->addCase(*cvi, DestBB);
4681         }
4682         I = SI;
4683         break;
4684       }
4685 
4686       // Old SwitchInst format without case ranges.
4687 
4688       if (Record.size() < 3 || (Record.size() & 1) == 0)
4689         return error("Invalid record");
4690       Type *OpTy = getTypeByID(Record[0]);
4691       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4692       BasicBlock *Default = getBasicBlock(Record[2]);
4693       if (!OpTy || !Cond || !Default)
4694         return error("Invalid record");
4695       unsigned NumCases = (Record.size()-3)/2;
4696       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4697       InstructionList.push_back(SI);
4698       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4699         ConstantInt *CaseVal =
4700           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4701         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4702         if (!CaseVal || !DestBB) {
4703           delete SI;
4704           return error("Invalid record");
4705         }
4706         SI->addCase(CaseVal, DestBB);
4707       }
4708       I = SI;
4709       break;
4710     }
4711     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4712       if (Record.size() < 2)
4713         return error("Invalid record");
4714       Type *OpTy = getTypeByID(Record[0]);
4715       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4716       if (!OpTy || !Address)
4717         return error("Invalid record");
4718       unsigned NumDests = Record.size()-2;
4719       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4720       InstructionList.push_back(IBI);
4721       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4722         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4723           IBI->addDestination(DestBB);
4724         } else {
4725           delete IBI;
4726           return error("Invalid record");
4727         }
4728       }
4729       I = IBI;
4730       break;
4731     }
4732 
4733     case bitc::FUNC_CODE_INST_INVOKE: {
4734       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4735       if (Record.size() < 4)
4736         return error("Invalid record");
4737       unsigned OpNum = 0;
4738       AttributeSet PAL = getAttributes(Record[OpNum++]);
4739       unsigned CCInfo = Record[OpNum++];
4740       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4741       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4742 
4743       FunctionType *FTy = nullptr;
4744       if (CCInfo >> 13 & 1 &&
4745           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4746         return error("Explicit invoke type is not a function type");
4747 
4748       Value *Callee;
4749       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4750         return error("Invalid record");
4751 
4752       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4753       if (!CalleeTy)
4754         return error("Callee is not a pointer");
4755       if (!FTy) {
4756         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4757         if (!FTy)
4758           return error("Callee is not of pointer to function type");
4759       } else if (CalleeTy->getElementType() != FTy)
4760         return error("Explicit invoke type does not match pointee type of "
4761                      "callee operand");
4762       if (Record.size() < FTy->getNumParams() + OpNum)
4763         return error("Insufficient operands to call");
4764 
4765       SmallVector<Value*, 16> Ops;
4766       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4767         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4768                                FTy->getParamType(i)));
4769         if (!Ops.back())
4770           return error("Invalid record");
4771       }
4772 
4773       if (!FTy->isVarArg()) {
4774         if (Record.size() != OpNum)
4775           return error("Invalid record");
4776       } else {
4777         // Read type/value pairs for varargs params.
4778         while (OpNum != Record.size()) {
4779           Value *Op;
4780           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4781             return error("Invalid record");
4782           Ops.push_back(Op);
4783         }
4784       }
4785 
4786       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4787       OperandBundles.clear();
4788       InstructionList.push_back(I);
4789       cast<InvokeInst>(I)->setCallingConv(
4790           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4791       cast<InvokeInst>(I)->setAttributes(PAL);
4792       break;
4793     }
4794     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4795       unsigned Idx = 0;
4796       Value *Val = nullptr;
4797       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4798         return error("Invalid record");
4799       I = ResumeInst::Create(Val);
4800       InstructionList.push_back(I);
4801       break;
4802     }
4803     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4804       I = new UnreachableInst(Context);
4805       InstructionList.push_back(I);
4806       break;
4807     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4808       if (Record.size() < 1 || ((Record.size()-1)&1))
4809         return error("Invalid record");
4810       Type *Ty = getTypeByID(Record[0]);
4811       if (!Ty)
4812         return error("Invalid record");
4813 
4814       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4815       InstructionList.push_back(PN);
4816 
4817       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4818         Value *V;
4819         // With the new function encoding, it is possible that operands have
4820         // negative IDs (for forward references).  Use a signed VBR
4821         // representation to keep the encoding small.
4822         if (UseRelativeIDs)
4823           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4824         else
4825           V = getValue(Record, 1+i, NextValueNo, Ty);
4826         BasicBlock *BB = getBasicBlock(Record[2+i]);
4827         if (!V || !BB)
4828           return error("Invalid record");
4829         PN->addIncoming(V, BB);
4830       }
4831       I = PN;
4832       break;
4833     }
4834 
4835     case bitc::FUNC_CODE_INST_LANDINGPAD:
4836     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4837       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4838       unsigned Idx = 0;
4839       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4840         if (Record.size() < 3)
4841           return error("Invalid record");
4842       } else {
4843         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4844         if (Record.size() < 4)
4845           return error("Invalid record");
4846       }
4847       Type *Ty = getTypeByID(Record[Idx++]);
4848       if (!Ty)
4849         return error("Invalid record");
4850       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4851         Value *PersFn = nullptr;
4852         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4853           return error("Invalid record");
4854 
4855         if (!F->hasPersonalityFn())
4856           F->setPersonalityFn(cast<Constant>(PersFn));
4857         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4858           return error("Personality function mismatch");
4859       }
4860 
4861       bool IsCleanup = !!Record[Idx++];
4862       unsigned NumClauses = Record[Idx++];
4863       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4864       LP->setCleanup(IsCleanup);
4865       for (unsigned J = 0; J != NumClauses; ++J) {
4866         LandingPadInst::ClauseType CT =
4867           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4868         Value *Val;
4869 
4870         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4871           delete LP;
4872           return error("Invalid record");
4873         }
4874 
4875         assert((CT != LandingPadInst::Catch ||
4876                 !isa<ArrayType>(Val->getType())) &&
4877                "Catch clause has a invalid type!");
4878         assert((CT != LandingPadInst::Filter ||
4879                 isa<ArrayType>(Val->getType())) &&
4880                "Filter clause has invalid type!");
4881         LP->addClause(cast<Constant>(Val));
4882       }
4883 
4884       I = LP;
4885       InstructionList.push_back(I);
4886       break;
4887     }
4888 
4889     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4890       if (Record.size() != 4)
4891         return error("Invalid record");
4892       uint64_t AlignRecord = Record[3];
4893       const uint64_t InAllocaMask = uint64_t(1) << 5;
4894       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4895       const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4896       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4897                                 SwiftErrorMask;
4898       bool InAlloca = AlignRecord & InAllocaMask;
4899       bool SwiftError = AlignRecord & SwiftErrorMask;
4900       Type *Ty = getTypeByID(Record[0]);
4901       if ((AlignRecord & ExplicitTypeMask) == 0) {
4902         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4903         if (!PTy)
4904           return error("Old-style alloca with a non-pointer type");
4905         Ty = PTy->getElementType();
4906       }
4907       Type *OpTy = getTypeByID(Record[1]);
4908       Value *Size = getFnValueByID(Record[2], OpTy);
4909       unsigned Align;
4910       if (std::error_code EC =
4911               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4912         return EC;
4913       }
4914       if (!Ty || !Size)
4915         return error("Invalid record");
4916       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4917       AI->setUsedWithInAlloca(InAlloca);
4918       AI->setSwiftError(SwiftError);
4919       I = AI;
4920       InstructionList.push_back(I);
4921       break;
4922     }
4923     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4924       unsigned OpNum = 0;
4925       Value *Op;
4926       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4927           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4928         return error("Invalid record");
4929 
4930       Type *Ty = nullptr;
4931       if (OpNum + 3 == Record.size())
4932         Ty = getTypeByID(Record[OpNum++]);
4933       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4934         return EC;
4935       if (!Ty)
4936         Ty = cast<PointerType>(Op->getType())->getElementType();
4937 
4938       unsigned Align;
4939       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4940         return EC;
4941       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4942 
4943       InstructionList.push_back(I);
4944       break;
4945     }
4946     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4947        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4948       unsigned OpNum = 0;
4949       Value *Op;
4950       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4951           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4952         return error("Invalid record");
4953 
4954       Type *Ty = nullptr;
4955       if (OpNum + 5 == Record.size())
4956         Ty = getTypeByID(Record[OpNum++]);
4957       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4958         return EC;
4959       if (!Ty)
4960         Ty = cast<PointerType>(Op->getType())->getElementType();
4961 
4962       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4963       if (Ordering == AtomicOrdering::NotAtomic ||
4964           Ordering == AtomicOrdering::Release ||
4965           Ordering == AtomicOrdering::AcquireRelease)
4966         return error("Invalid record");
4967       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4968         return error("Invalid record");
4969       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4970 
4971       unsigned Align;
4972       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4973         return EC;
4974       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4975 
4976       InstructionList.push_back(I);
4977       break;
4978     }
4979     case bitc::FUNC_CODE_INST_STORE:
4980     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4981       unsigned OpNum = 0;
4982       Value *Val, *Ptr;
4983       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4984           (BitCode == bitc::FUNC_CODE_INST_STORE
4985                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4986                : popValue(Record, OpNum, NextValueNo,
4987                           cast<PointerType>(Ptr->getType())->getElementType(),
4988                           Val)) ||
4989           OpNum + 2 != Record.size())
4990         return error("Invalid record");
4991 
4992       if (std::error_code EC =
4993               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4994         return EC;
4995       unsigned Align;
4996       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4997         return EC;
4998       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4999       InstructionList.push_back(I);
5000       break;
5001     }
5002     case bitc::FUNC_CODE_INST_STOREATOMIC:
5003     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5004       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5005       unsigned OpNum = 0;
5006       Value *Val, *Ptr;
5007       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5008           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5009                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5010                : popValue(Record, OpNum, NextValueNo,
5011                           cast<PointerType>(Ptr->getType())->getElementType(),
5012                           Val)) ||
5013           OpNum + 4 != Record.size())
5014         return error("Invalid record");
5015 
5016       if (std::error_code EC =
5017               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5018         return EC;
5019       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5020       if (Ordering == AtomicOrdering::NotAtomic ||
5021           Ordering == AtomicOrdering::Acquire ||
5022           Ordering == AtomicOrdering::AcquireRelease)
5023         return error("Invalid record");
5024       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5025       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5026         return error("Invalid record");
5027 
5028       unsigned Align;
5029       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5030         return EC;
5031       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
5032       InstructionList.push_back(I);
5033       break;
5034     }
5035     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
5036     case bitc::FUNC_CODE_INST_CMPXCHG: {
5037       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
5038       //          failureordering?, isweak?]
5039       unsigned OpNum = 0;
5040       Value *Ptr, *Cmp, *New;
5041       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5042           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5043                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5044                : popValue(Record, OpNum, NextValueNo,
5045                           cast<PointerType>(Ptr->getType())->getElementType(),
5046                           Cmp)) ||
5047           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5048           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
5049         return error("Invalid record");
5050       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
5051       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5052           SuccessOrdering == AtomicOrdering::Unordered)
5053         return error("Invalid record");
5054       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
5055 
5056       if (std::error_code EC =
5057               typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5058         return EC;
5059       AtomicOrdering FailureOrdering;
5060       if (Record.size() < 7)
5061         FailureOrdering =
5062             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5063       else
5064         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
5065 
5066       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5067                                 SynchScope);
5068       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5069 
5070       if (Record.size() < 8) {
5071         // Before weak cmpxchgs existed, the instruction simply returned the
5072         // value loaded from memory, so bitcode files from that era will be
5073         // expecting the first component of a modern cmpxchg.
5074         CurBB->getInstList().push_back(I);
5075         I = ExtractValueInst::Create(I, 0);
5076       } else {
5077         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5078       }
5079 
5080       InstructionList.push_back(I);
5081       break;
5082     }
5083     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5084       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5085       unsigned OpNum = 0;
5086       Value *Ptr, *Val;
5087       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5088           popValue(Record, OpNum, NextValueNo,
5089                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5090           OpNum+4 != Record.size())
5091         return error("Invalid record");
5092       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5093       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5094           Operation > AtomicRMWInst::LAST_BINOP)
5095         return error("Invalid record");
5096       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5097       if (Ordering == AtomicOrdering::NotAtomic ||
5098           Ordering == AtomicOrdering::Unordered)
5099         return error("Invalid record");
5100       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5101       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5102       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5103       InstructionList.push_back(I);
5104       break;
5105     }
5106     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5107       if (2 != Record.size())
5108         return error("Invalid record");
5109       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5110       if (Ordering == AtomicOrdering::NotAtomic ||
5111           Ordering == AtomicOrdering::Unordered ||
5112           Ordering == AtomicOrdering::Monotonic)
5113         return error("Invalid record");
5114       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5115       I = new FenceInst(Context, Ordering, SynchScope);
5116       InstructionList.push_back(I);
5117       break;
5118     }
5119     case bitc::FUNC_CODE_INST_CALL: {
5120       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5121       if (Record.size() < 3)
5122         return error("Invalid record");
5123 
5124       unsigned OpNum = 0;
5125       AttributeSet PAL = getAttributes(Record[OpNum++]);
5126       unsigned CCInfo = Record[OpNum++];
5127 
5128       FastMathFlags FMF;
5129       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5130         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5131         if (!FMF.any())
5132           return error("Fast math flags indicator set for call with no FMF");
5133       }
5134 
5135       FunctionType *FTy = nullptr;
5136       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5137           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5138         return error("Explicit call type is not a function type");
5139 
5140       Value *Callee;
5141       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5142         return error("Invalid record");
5143 
5144       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5145       if (!OpTy)
5146         return error("Callee is not a pointer type");
5147       if (!FTy) {
5148         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5149         if (!FTy)
5150           return error("Callee is not of pointer to function type");
5151       } else if (OpTy->getElementType() != FTy)
5152         return error("Explicit call type does not match pointee type of "
5153                      "callee operand");
5154       if (Record.size() < FTy->getNumParams() + OpNum)
5155         return error("Insufficient operands to call");
5156 
5157       SmallVector<Value*, 16> Args;
5158       // Read the fixed params.
5159       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5160         if (FTy->getParamType(i)->isLabelTy())
5161           Args.push_back(getBasicBlock(Record[OpNum]));
5162         else
5163           Args.push_back(getValue(Record, OpNum, NextValueNo,
5164                                   FTy->getParamType(i)));
5165         if (!Args.back())
5166           return error("Invalid record");
5167       }
5168 
5169       // Read type/value pairs for varargs params.
5170       if (!FTy->isVarArg()) {
5171         if (OpNum != Record.size())
5172           return error("Invalid record");
5173       } else {
5174         while (OpNum != Record.size()) {
5175           Value *Op;
5176           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5177             return error("Invalid record");
5178           Args.push_back(Op);
5179         }
5180       }
5181 
5182       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5183       OperandBundles.clear();
5184       InstructionList.push_back(I);
5185       cast<CallInst>(I)->setCallingConv(
5186           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5187       CallInst::TailCallKind TCK = CallInst::TCK_None;
5188       if (CCInfo & 1 << bitc::CALL_TAIL)
5189         TCK = CallInst::TCK_Tail;
5190       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5191         TCK = CallInst::TCK_MustTail;
5192       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5193         TCK = CallInst::TCK_NoTail;
5194       cast<CallInst>(I)->setTailCallKind(TCK);
5195       cast<CallInst>(I)->setAttributes(PAL);
5196       if (FMF.any()) {
5197         if (!isa<FPMathOperator>(I))
5198           return error("Fast-math-flags specified for call without "
5199                        "floating-point scalar or vector return type");
5200         I->setFastMathFlags(FMF);
5201       }
5202       break;
5203     }
5204     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5205       if (Record.size() < 3)
5206         return error("Invalid record");
5207       Type *OpTy = getTypeByID(Record[0]);
5208       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5209       Type *ResTy = getTypeByID(Record[2]);
5210       if (!OpTy || !Op || !ResTy)
5211         return error("Invalid record");
5212       I = new VAArgInst(Op, ResTy);
5213       InstructionList.push_back(I);
5214       break;
5215     }
5216 
5217     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5218       // A call or an invoke can be optionally prefixed with some variable
5219       // number of operand bundle blocks.  These blocks are read into
5220       // OperandBundles and consumed at the next call or invoke instruction.
5221 
5222       if (Record.size() < 1 || Record[0] >= BundleTags.size())
5223         return error("Invalid record");
5224 
5225       std::vector<Value *> Inputs;
5226 
5227       unsigned OpNum = 1;
5228       while (OpNum != Record.size()) {
5229         Value *Op;
5230         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5231           return error("Invalid record");
5232         Inputs.push_back(Op);
5233       }
5234 
5235       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5236       continue;
5237     }
5238     }
5239 
5240     // Add instruction to end of current BB.  If there is no current BB, reject
5241     // this file.
5242     if (!CurBB) {
5243       delete I;
5244       return error("Invalid instruction with no BB");
5245     }
5246     if (!OperandBundles.empty()) {
5247       delete I;
5248       return error("Operand bundles found with no consumer");
5249     }
5250     CurBB->getInstList().push_back(I);
5251 
5252     // If this was a terminator instruction, move to the next block.
5253     if (isa<TerminatorInst>(I)) {
5254       ++CurBBNo;
5255       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5256     }
5257 
5258     // Non-void values get registered in the value table for future use.
5259     if (I && !I->getType()->isVoidTy())
5260       ValueList.assignValue(I, NextValueNo++);
5261   }
5262 
5263 OutOfRecordLoop:
5264 
5265   if (!OperandBundles.empty())
5266     return error("Operand bundles found with no consumer");
5267 
5268   // Check the function list for unresolved values.
5269   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5270     if (!A->getParent()) {
5271       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5272       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5273         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5274           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5275           delete A;
5276         }
5277       }
5278       return error("Never resolved value found in function");
5279     }
5280   }
5281 
5282   // Unexpected unresolved metadata about to be dropped.
5283   if (MetadataList.hasFwdRefs())
5284     return error("Invalid function metadata: outgoing forward refs");
5285 
5286   // Trim the value list down to the size it was before we parsed this function.
5287   ValueList.shrinkTo(ModuleValueListSize);
5288   MetadataList.shrinkTo(ModuleMetadataListSize);
5289   std::vector<BasicBlock*>().swap(FunctionBBs);
5290   return std::error_code();
5291 }
5292 
5293 /// Find the function body in the bitcode stream
5294 std::error_code BitcodeReader::findFunctionInStream(
5295     Function *F,
5296     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5297   while (DeferredFunctionInfoIterator->second == 0) {
5298     // This is the fallback handling for the old format bitcode that
5299     // didn't contain the function index in the VST, or when we have
5300     // an anonymous function which would not have a VST entry.
5301     // Assert that we have one of those two cases.
5302     assert(VSTOffset == 0 || !F->hasName());
5303     // Parse the next body in the stream and set its position in the
5304     // DeferredFunctionInfo map.
5305     if (std::error_code EC = rememberAndSkipFunctionBodies())
5306       return EC;
5307   }
5308   return std::error_code();
5309 }
5310 
5311 //===----------------------------------------------------------------------===//
5312 // GVMaterializer implementation
5313 //===----------------------------------------------------------------------===//
5314 
5315 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5316 
5317 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5318   if (std::error_code EC = materializeMetadata())
5319     return EC;
5320 
5321   Function *F = dyn_cast<Function>(GV);
5322   // If it's not a function or is already material, ignore the request.
5323   if (!F || !F->isMaterializable())
5324     return std::error_code();
5325 
5326   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5327   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5328   // If its position is recorded as 0, its body is somewhere in the stream
5329   // but we haven't seen it yet.
5330   if (DFII->second == 0)
5331     if (std::error_code EC = findFunctionInStream(F, DFII))
5332       return EC;
5333 
5334   // Move the bit stream to the saved position of the deferred function body.
5335   Stream.JumpToBit(DFII->second);
5336 
5337   if (std::error_code EC = parseFunctionBody(F))
5338     return EC;
5339   F->setIsMaterializable(false);
5340 
5341   if (StripDebugInfo)
5342     stripDebugInfo(*F);
5343 
5344   // Upgrade any old intrinsic calls in the function.
5345   for (auto &I : UpgradedIntrinsics) {
5346     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5347          UI != UE;) {
5348       User *U = *UI;
5349       ++UI;
5350       if (CallInst *CI = dyn_cast<CallInst>(U))
5351         UpgradeIntrinsicCall(CI, I.second);
5352     }
5353   }
5354 
5355   // Finish fn->subprogram upgrade for materialized functions.
5356   if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5357     F->setSubprogram(SP);
5358 
5359   // Bring in any functions that this function forward-referenced via
5360   // blockaddresses.
5361   return materializeForwardReferencedFunctions();
5362 }
5363 
5364 std::error_code BitcodeReader::materializeModule() {
5365   if (std::error_code EC = materializeMetadata())
5366     return EC;
5367 
5368   // Promise to materialize all forward references.
5369   WillMaterializeAllForwardRefs = true;
5370 
5371   // Iterate over the module, deserializing any functions that are still on
5372   // disk.
5373   for (Function &F : *TheModule) {
5374     if (std::error_code EC = materialize(&F))
5375       return EC;
5376   }
5377   // At this point, if there are any function bodies, parse the rest of
5378   // the bits in the module past the last function block we have recorded
5379   // through either lazy scanning or the VST.
5380   if (LastFunctionBlockBit || NextUnreadBit)
5381     parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5382                                                      : NextUnreadBit);
5383 
5384   // Check that all block address forward references got resolved (as we
5385   // promised above).
5386   if (!BasicBlockFwdRefs.empty())
5387     return error("Never resolved function from blockaddress");
5388 
5389   // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5390   // to prevent this instructions with TBAA tags should be upgraded first.
5391   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5392     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5393 
5394   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5395   // delete the old functions to clean up. We can't do this unless the entire
5396   // module is materialized because there could always be another function body
5397   // with calls to the old function.
5398   for (auto &I : UpgradedIntrinsics) {
5399     for (auto *U : I.first->users()) {
5400       if (CallInst *CI = dyn_cast<CallInst>(U))
5401         UpgradeIntrinsicCall(CI, I.second);
5402     }
5403     if (!I.first->use_empty())
5404       I.first->replaceAllUsesWith(I.second);
5405     I.first->eraseFromParent();
5406   }
5407   UpgradedIntrinsics.clear();
5408 
5409   UpgradeDebugInfo(*TheModule);
5410   return std::error_code();
5411 }
5412 
5413 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5414   return IdentifiedStructTypes;
5415 }
5416 
5417 std::error_code
5418 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5419   if (Streamer)
5420     return initLazyStream(std::move(Streamer));
5421   return initStreamFromBuffer();
5422 }
5423 
5424 std::error_code BitcodeReader::initStreamFromBuffer() {
5425   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5426   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5427 
5428   if (Buffer->getBufferSize() & 3)
5429     return error("Invalid bitcode signature");
5430 
5431   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5432   // The magic number is 0x0B17C0DE stored in little endian.
5433   if (isBitcodeWrapper(BufPtr, BufEnd))
5434     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5435       return error("Invalid bitcode wrapper header");
5436 
5437   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5438   Stream.init(&*StreamFile);
5439 
5440   return std::error_code();
5441 }
5442 
5443 std::error_code
5444 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5445   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5446   // see it.
5447   auto OwnedBytes =
5448       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5449   StreamingMemoryObject &Bytes = *OwnedBytes;
5450   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5451   Stream.init(&*StreamFile);
5452 
5453   unsigned char buf[16];
5454   if (Bytes.readBytes(buf, 16, 0) != 16)
5455     return error("Invalid bitcode signature");
5456 
5457   if (!isBitcode(buf, buf + 16))
5458     return error("Invalid bitcode signature");
5459 
5460   if (isBitcodeWrapper(buf, buf + 4)) {
5461     const unsigned char *bitcodeStart = buf;
5462     const unsigned char *bitcodeEnd = buf + 16;
5463     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5464     Bytes.dropLeadingBytes(bitcodeStart - buf);
5465     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5466   }
5467   return std::error_code();
5468 }
5469 
5470 std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E,
5471                                                        const Twine &Message) {
5472   return ::error(DiagnosticHandler, make_error_code(E), Message);
5473 }
5474 
5475 std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
5476   return ::error(DiagnosticHandler,
5477                  make_error_code(BitcodeError::CorruptedBitcode), Message);
5478 }
5479 
5480 std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) {
5481   return ::error(DiagnosticHandler, make_error_code(E));
5482 }
5483 
5484 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5485     MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5486     bool IsLazy, bool CheckGlobalValSummaryPresenceOnly)
5487     : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5488       CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
5489 
5490 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5491     DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5492     bool CheckGlobalValSummaryPresenceOnly)
5493     : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5494       CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
5495 
5496 void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
5497 
5498 void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5499 
5500 GlobalValue::GUID
5501 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
5502   auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5503   assert(VGI != ValueIdToCallGraphGUIDMap.end());
5504   return VGI->second;
5505 }
5506 
5507 GlobalValueInfo *
5508 ModuleSummaryIndexBitcodeReader::getInfoFromSummaryOffset(uint64_t Offset) {
5509   auto I = SummaryOffsetToInfoMap.find(Offset);
5510   assert(I != SummaryOffsetToInfoMap.end());
5511   return I->second;
5512 }
5513 
5514 // Specialized value symbol table parser used when reading module index
5515 // blocks where we don't actually create global values.
5516 // At the end of this routine the module index is populated with a map
5517 // from global value name to GlobalValueInfo. The global value info contains
5518 // the function block's bitcode offset (if applicable), or the offset into the
5519 // summary section for the combined index.
5520 std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5521     uint64_t Offset,
5522     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5523   assert(Offset > 0 && "Expected non-zero VST offset");
5524   uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5525 
5526   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5527     return error("Invalid record");
5528 
5529   SmallVector<uint64_t, 64> Record;
5530 
5531   // Read all the records for this value table.
5532   SmallString<128> ValueName;
5533   while (1) {
5534     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5535 
5536     switch (Entry.Kind) {
5537     case BitstreamEntry::SubBlock: // Handled for us already.
5538     case BitstreamEntry::Error:
5539       return error("Malformed block");
5540     case BitstreamEntry::EndBlock:
5541       // Done parsing VST, jump back to wherever we came from.
5542       Stream.JumpToBit(CurrentBit);
5543       return std::error_code();
5544     case BitstreamEntry::Record:
5545       // The interesting case.
5546       break;
5547     }
5548 
5549     // Read a record.
5550     Record.clear();
5551     switch (Stream.readRecord(Entry.ID, Record)) {
5552     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5553       break;
5554     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5555       if (convertToString(Record, 1, ValueName))
5556         return error("Invalid record");
5557       unsigned ValueID = Record[0];
5558       std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5559           llvm::make_unique<GlobalValueInfo>();
5560       assert(!SourceFileName.empty());
5561       auto VLI = ValueIdToLinkageMap.find(ValueID);
5562       assert(VLI != ValueIdToLinkageMap.end() &&
5563              "No linkage found for VST entry?");
5564       std::string GlobalId = GlobalValue::getGlobalIdentifier(
5565           ValueName, VLI->second, SourceFileName);
5566       auto ValueGUID = GlobalValue::getGUID(GlobalId);
5567       if (PrintSummaryGUIDs)
5568         dbgs() << "GUID " << ValueGUID << " is " << ValueName << "\n";
5569       TheIndex->addGlobalValueInfo(ValueGUID, std::move(GlobalValInfo));
5570       ValueIdToCallGraphGUIDMap[ValueID] = ValueGUID;
5571       ValueName.clear();
5572       break;
5573     }
5574     case bitc::VST_CODE_FNENTRY: {
5575       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5576       if (convertToString(Record, 2, ValueName))
5577         return error("Invalid record");
5578       unsigned ValueID = Record[0];
5579       uint64_t FuncOffset = Record[1];
5580       assert(!IsLazy && "Lazy summary read only supported for combined index");
5581       std::unique_ptr<GlobalValueInfo> FuncInfo =
5582           llvm::make_unique<GlobalValueInfo>(FuncOffset);
5583       assert(!SourceFileName.empty());
5584       auto VLI = ValueIdToLinkageMap.find(ValueID);
5585       assert(VLI != ValueIdToLinkageMap.end() &&
5586              "No linkage found for VST entry?");
5587       std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5588           ValueName, VLI->second, SourceFileName);
5589       auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
5590       if (PrintSummaryGUIDs)
5591         dbgs() << "GUID " << FunctionGUID << " is " << ValueName << "\n";
5592       TheIndex->addGlobalValueInfo(FunctionGUID, std::move(FuncInfo));
5593       ValueIdToCallGraphGUIDMap[ValueID] = FunctionGUID;
5594 
5595       ValueName.clear();
5596       break;
5597     }
5598     case bitc::VST_CODE_COMBINED_GVDEFENTRY: {
5599       // VST_CODE_COMBINED_GVDEFENTRY: [valueid, offset, guid]
5600       unsigned ValueID = Record[0];
5601       uint64_t GlobalValSummaryOffset = Record[1];
5602       GlobalValue::GUID GlobalValGUID = Record[2];
5603       std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5604           llvm::make_unique<GlobalValueInfo>(GlobalValSummaryOffset);
5605       SummaryOffsetToInfoMap[GlobalValSummaryOffset] = GlobalValInfo.get();
5606       TheIndex->addGlobalValueInfo(GlobalValGUID, std::move(GlobalValInfo));
5607       ValueIdToCallGraphGUIDMap[ValueID] = GlobalValGUID;
5608       break;
5609     }
5610     case bitc::VST_CODE_COMBINED_ENTRY: {
5611       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5612       unsigned ValueID = Record[0];
5613       GlobalValue::GUID RefGUID = Record[1];
5614       ValueIdToCallGraphGUIDMap[ValueID] = RefGUID;
5615       break;
5616     }
5617     }
5618   }
5619 }
5620 
5621 // Parse just the blocks needed for building the index out of the module.
5622 // At the end of this routine the module Index is populated with a map
5623 // from global value name to GlobalValueInfo. The global value info contains
5624 // either the parsed summary information (when parsing summaries
5625 // eagerly), or just to the summary record's offset
5626 // if parsing lazily (IsLazy).
5627 std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
5628   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5629     return error("Invalid record");
5630 
5631   SmallVector<uint64_t, 64> Record;
5632   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5633   unsigned ValueId = 0;
5634 
5635   // Read the index for this module.
5636   while (1) {
5637     BitstreamEntry Entry = Stream.advance();
5638 
5639     switch (Entry.Kind) {
5640     case BitstreamEntry::Error:
5641       return error("Malformed block");
5642     case BitstreamEntry::EndBlock:
5643       return std::error_code();
5644 
5645     case BitstreamEntry::SubBlock:
5646       if (CheckGlobalValSummaryPresenceOnly) {
5647         if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5648           SeenGlobalValSummary = true;
5649           // No need to parse the rest since we found the summary.
5650           return std::error_code();
5651         }
5652         if (Stream.SkipBlock())
5653           return error("Invalid record");
5654         continue;
5655       }
5656       switch (Entry.ID) {
5657       default: // Skip unknown content.
5658         if (Stream.SkipBlock())
5659           return error("Invalid record");
5660         break;
5661       case bitc::BLOCKINFO_BLOCK_ID:
5662         // Need to parse these to get abbrev ids (e.g. for VST)
5663         if (Stream.ReadBlockInfoBlock())
5664           return error("Malformed block");
5665         break;
5666       case bitc::VALUE_SYMTAB_BLOCK_ID:
5667         // Should have been parsed earlier via VSTOffset, unless there
5668         // is no summary section.
5669         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5670                 !SeenGlobalValSummary) &&
5671                "Expected early VST parse via VSTOffset record");
5672         if (Stream.SkipBlock())
5673           return error("Invalid record");
5674         break;
5675       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5676         assert(VSTOffset > 0 && "Expected non-zero VST offset");
5677         assert(!SeenValueSymbolTable &&
5678                "Already read VST when parsing summary block?");
5679         if (std::error_code EC =
5680                 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5681           return EC;
5682         SeenValueSymbolTable = true;
5683         SeenGlobalValSummary = true;
5684         if (IsLazy) {
5685           // Lazy parsing of summary info, skip it.
5686           if (Stream.SkipBlock())
5687             return error("Invalid record");
5688         } else if (std::error_code EC = parseEntireSummary())
5689           return EC;
5690         break;
5691       case bitc::MODULE_STRTAB_BLOCK_ID:
5692         if (std::error_code EC = parseModuleStringTable())
5693           return EC;
5694         break;
5695       }
5696       continue;
5697 
5698     case BitstreamEntry::Record: {
5699         Record.clear();
5700         auto BitCode = Stream.readRecord(Entry.ID, Record);
5701         switch (BitCode) {
5702         default:
5703           break; // Default behavior, ignore unknown content.
5704         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5705         case bitc::MODULE_CODE_SOURCE_FILENAME: {
5706           SmallString<128> ValueName;
5707           if (convertToString(Record, 0, ValueName))
5708             return error("Invalid record");
5709           SourceFileName = ValueName.c_str();
5710           break;
5711         }
5712         /// MODULE_CODE_HASH: [5*i32]
5713         case bitc::MODULE_CODE_HASH: {
5714           if (Record.size() != 5)
5715             return error("Invalid hash length " + Twine(Record.size()).str());
5716           if (!TheIndex)
5717             break;
5718           if (TheIndex->modulePaths().empty())
5719             // Does not have any summary emitted.
5720             break;
5721           if (TheIndex->modulePaths().size() != 1)
5722             return error("Don't expect multiple modules defined?");
5723           auto &Hash = TheIndex->modulePaths().begin()->second.second;
5724           int Pos = 0;
5725           for (auto &Val : Record) {
5726             assert(!(Val >> 32) && "Unexpected high bits set");
5727             Hash[Pos++] = Val;
5728           }
5729           break;
5730         }
5731         /// MODULE_CODE_VSTOFFSET: [offset]
5732         case bitc::MODULE_CODE_VSTOFFSET:
5733           if (Record.size() < 1)
5734             return error("Invalid record");
5735           VSTOffset = Record[0];
5736           break;
5737         // GLOBALVAR: [pointer type, isconst, initid,
5738         //             linkage, alignment, section, visibility, threadlocal,
5739         //             unnamed_addr, externally_initialized, dllstorageclass,
5740         //             comdat]
5741         case bitc::MODULE_CODE_GLOBALVAR: {
5742           if (Record.size() < 6)
5743             return error("Invalid record");
5744           uint64_t RawLinkage = Record[3];
5745           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5746           ValueIdToLinkageMap[ValueId++] = Linkage;
5747           break;
5748         }
5749         // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
5750         //             alignment, section, visibility, gc, unnamed_addr,
5751         //             prologuedata, dllstorageclass, comdat, prefixdata]
5752         case bitc::MODULE_CODE_FUNCTION: {
5753           if (Record.size() < 8)
5754             return error("Invalid record");
5755           uint64_t RawLinkage = Record[3];
5756           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5757           ValueIdToLinkageMap[ValueId++] = Linkage;
5758           break;
5759         }
5760         // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
5761         // dllstorageclass]
5762         case bitc::MODULE_CODE_ALIAS: {
5763           if (Record.size() < 6)
5764             return error("Invalid record");
5765           uint64_t RawLinkage = Record[3];
5766           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5767           ValueIdToLinkageMap[ValueId++] = Linkage;
5768           break;
5769         }
5770         }
5771       }
5772       continue;
5773     }
5774   }
5775 }
5776 
5777 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5778 // objects in the index.
5779 std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
5780   if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
5781     return error("Invalid record");
5782 
5783   SmallVector<uint64_t, 64> Record;
5784 
5785   bool Combined = false;
5786   while (1) {
5787     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5788 
5789     switch (Entry.Kind) {
5790     case BitstreamEntry::SubBlock: // Handled for us already.
5791     case BitstreamEntry::Error:
5792       return error("Malformed block");
5793     case BitstreamEntry::EndBlock:
5794       // For a per-module index, remove any entries that still have empty
5795       // summaries. The VST parsing creates entries eagerly for all symbols,
5796       // but not all have associated summaries (e.g. it doesn't know how to
5797       // distinguish between VST_CODE_ENTRY for function declarations vs global
5798       // variables with initializers that end up with a summary). Remove those
5799       // entries now so that we don't need to rely on the combined index merger
5800       // to clean them up (especially since that may not run for the first
5801       // module's index if we merge into that).
5802       if (!Combined)
5803         TheIndex->removeEmptySummaryEntries();
5804       return std::error_code();
5805     case BitstreamEntry::Record:
5806       // The interesting case.
5807       break;
5808     }
5809 
5810     // Read a record. The record format depends on whether this
5811     // is a per-module index or a combined index file. In the per-module
5812     // case the records contain the associated value's ID for correlation
5813     // with VST entries. In the combined index the correlation is done
5814     // via the bitcode offset of the summary records (which were saved
5815     // in the combined index VST entries). The records also contain
5816     // information used for ThinLTO renaming and importing.
5817     Record.clear();
5818     uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5819     auto BitCode = Stream.readRecord(Entry.ID, Record);
5820     switch (BitCode) {
5821     default: // Default behavior: ignore.
5822       break;
5823     // FS_PERMODULE: [valueid, linkage, instcount, numrefs, numrefs x valueid,
5824     //                n x (valueid, callsitecount)]
5825     // FS_PERMODULE_PROFILE: [valueid, linkage, instcount, numrefs,
5826     //                        numrefs x valueid,
5827     //                        n x (valueid, callsitecount, profilecount)]
5828     case bitc::FS_PERMODULE:
5829     case bitc::FS_PERMODULE_PROFILE: {
5830       unsigned ValueID = Record[0];
5831       uint64_t RawLinkage = Record[1];
5832       unsigned InstCount = Record[2];
5833       unsigned NumRefs = Record[3];
5834       std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5835           getDecodedLinkage(RawLinkage), InstCount);
5836       // The module path string ref set in the summary must be owned by the
5837       // index's module string table. Since we don't have a module path
5838       // string table section in the per-module index, we create a single
5839       // module path string table entry with an empty (0) ID to take
5840       // ownership.
5841       FS->setModulePath(
5842           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
5843       static int RefListStartIndex = 4;
5844       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5845       assert(Record.size() >= RefListStartIndex + NumRefs &&
5846              "Record size inconsistent with number of references");
5847       for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5848         unsigned RefValueId = Record[I];
5849         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
5850         FS->addRefEdge(RefGUID);
5851       }
5852       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5853       for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5854            ++I) {
5855         unsigned CalleeValueId = Record[I];
5856         unsigned CallsiteCount = Record[++I];
5857         uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
5858         GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
5859         FS->addCallGraphEdge(CalleeGUID,
5860                              CalleeInfo(CallsiteCount, ProfileCount));
5861       }
5862       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
5863       auto *Info = TheIndex->getGlobalValueInfo(GUID);
5864       assert(!Info->summary() && "Expected a single summary per VST entry");
5865       Info->setSummary(std::move(FS));
5866       break;
5867     }
5868     // FS_ALIAS: [valueid, linkage, valueid]
5869     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5870     // they expect all aliasee summaries to be available.
5871     case bitc::FS_ALIAS: {
5872       unsigned ValueID = Record[0];
5873       uint64_t RawLinkage = Record[1];
5874       unsigned AliaseeID = Record[2];
5875       std::unique_ptr<AliasSummary> AS =
5876           llvm::make_unique<AliasSummary>(getDecodedLinkage(RawLinkage));
5877       // The module path string ref set in the summary must be owned by the
5878       // index's module string table. Since we don't have a module path
5879       // string table section in the per-module index, we create a single
5880       // module path string table entry with an empty (0) ID to take
5881       // ownership.
5882       AS->setModulePath(
5883           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
5884 
5885       GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID);
5886       auto *AliaseeInfo = TheIndex->getGlobalValueInfo(AliaseeGUID);
5887       if (!AliaseeInfo->summary())
5888         return error("Alias expects aliasee summary to be parsed");
5889       AS->setAliasee(AliaseeInfo->summary());
5890 
5891       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
5892       auto *Info = TheIndex->getGlobalValueInfo(GUID);
5893       assert(!Info->summary() && "Expected a single summary per VST entry");
5894       Info->setSummary(std::move(AS));
5895       break;
5896     }
5897     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, linkage, n x valueid]
5898     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5899       unsigned ValueID = Record[0];
5900       uint64_t RawLinkage = Record[1];
5901       std::unique_ptr<GlobalVarSummary> FS =
5902           llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5903       FS->setModulePath(
5904           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
5905       for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5906         unsigned RefValueId = Record[I];
5907         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
5908         FS->addRefEdge(RefGUID);
5909       }
5910       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
5911       auto *Info = TheIndex->getGlobalValueInfo(GUID);
5912       assert(!Info->summary() && "Expected a single summary per VST entry");
5913       Info->setSummary(std::move(FS));
5914       break;
5915     }
5916     // FS_COMBINED: [modid, linkage, instcount, numrefs, numrefs x valueid,
5917     //               n x (valueid, callsitecount)]
5918     // FS_COMBINED_PROFILE: [modid, linkage, instcount, numrefs,
5919     //                       numrefs x valueid,
5920     //                       n x (valueid, callsitecount, profilecount)]
5921     case bitc::FS_COMBINED:
5922     case bitc::FS_COMBINED_PROFILE: {
5923       uint64_t ModuleId = Record[0];
5924       uint64_t RawLinkage = Record[1];
5925       unsigned InstCount = Record[2];
5926       unsigned NumRefs = Record[3];
5927       std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5928           getDecodedLinkage(RawLinkage), InstCount);
5929       FS->setModulePath(ModuleIdMap[ModuleId]);
5930       static int RefListStartIndex = 4;
5931       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5932       assert(Record.size() >= RefListStartIndex + NumRefs &&
5933              "Record size inconsistent with number of references");
5934       for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5935         unsigned RefValueId = Record[I];
5936         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
5937         FS->addRefEdge(RefGUID);
5938       }
5939       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5940       for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5941            ++I) {
5942         unsigned CalleeValueId = Record[I];
5943         unsigned CallsiteCount = Record[++I];
5944         uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
5945         GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
5946         FS->addCallGraphEdge(CalleeGUID,
5947                              CalleeInfo(CallsiteCount, ProfileCount));
5948       }
5949       auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5950       assert(!Info->summary() && "Expected a single summary per VST entry");
5951       Info->setSummary(std::move(FS));
5952       Combined = true;
5953       break;
5954     }
5955     // FS_COMBINED_ALIAS: [modid, linkage, offset]
5956     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5957     // they expect all aliasee summaries to be available.
5958     case bitc::FS_COMBINED_ALIAS: {
5959       uint64_t ModuleId = Record[0];
5960       uint64_t RawLinkage = Record[1];
5961       uint64_t AliaseeSummaryOffset = Record[2];
5962       std::unique_ptr<AliasSummary> AS =
5963           llvm::make_unique<AliasSummary>(getDecodedLinkage(RawLinkage));
5964       AS->setModulePath(ModuleIdMap[ModuleId]);
5965 
5966       auto *AliaseeInfo = getInfoFromSummaryOffset(AliaseeSummaryOffset);
5967       if (!AliaseeInfo->summary())
5968         return error("Alias expects aliasee summary to be parsed");
5969       AS->setAliasee(AliaseeInfo->summary());
5970 
5971       auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5972       assert(!Info->summary() && "Expected a single summary per VST entry");
5973       Info->setSummary(std::move(AS));
5974       Combined = true;
5975       break;
5976     }
5977     // FS_COMBINED_GLOBALVAR_INIT_REFS: [modid, linkage, n x valueid]
5978     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5979       uint64_t ModuleId = Record[0];
5980       uint64_t RawLinkage = Record[1];
5981       std::unique_ptr<GlobalVarSummary> FS =
5982           llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5983       FS->setModulePath(ModuleIdMap[ModuleId]);
5984       for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5985         unsigned RefValueId = Record[I];
5986         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
5987         FS->addRefEdge(RefGUID);
5988       }
5989       auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5990       assert(!Info->summary() && "Expected a single summary per VST entry");
5991       Info->setSummary(std::move(FS));
5992       Combined = true;
5993       break;
5994     }
5995     }
5996   }
5997   llvm_unreachable("Exit infinite loop");
5998 }
5999 
6000 // Parse the  module string table block into the Index.
6001 // This populates the ModulePathStringTable map in the index.
6002 std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6003   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6004     return error("Invalid record");
6005 
6006   SmallVector<uint64_t, 64> Record;
6007 
6008   SmallString<128> ModulePath;
6009   ModulePathStringTableTy::iterator LastSeenModulePath;
6010   while (1) {
6011     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6012 
6013     switch (Entry.Kind) {
6014     case BitstreamEntry::SubBlock: // Handled for us already.
6015     case BitstreamEntry::Error:
6016       return error("Malformed block");
6017     case BitstreamEntry::EndBlock:
6018       return std::error_code();
6019     case BitstreamEntry::Record:
6020       // The interesting case.
6021       break;
6022     }
6023 
6024     Record.clear();
6025     switch (Stream.readRecord(Entry.ID, Record)) {
6026     default: // Default behavior: ignore.
6027       break;
6028     case bitc::MST_CODE_ENTRY: {
6029       // MST_ENTRY: [modid, namechar x N]
6030       uint64_t ModuleId = Record[0];
6031 
6032       if (convertToString(Record, 1, ModulePath))
6033         return error("Invalid record");
6034 
6035       LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6036       ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6037 
6038       ModulePath.clear();
6039       break;
6040     }
6041     /// MST_CODE_HASH: [5*i32]
6042     case bitc::MST_CODE_HASH: {
6043       if (Record.size() != 5)
6044         return error("Invalid hash length " + Twine(Record.size()).str());
6045       if (LastSeenModulePath == TheIndex->modulePaths().end())
6046         return error("Invalid hash that does not follow a module path");
6047       int Pos = 0;
6048       for (auto &Val : Record) {
6049         assert(!(Val >> 32) && "Unexpected high bits set");
6050         LastSeenModulePath->second.second[Pos++] = Val;
6051       }
6052       // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6053       LastSeenModulePath = TheIndex->modulePaths().end();
6054       break;
6055     }
6056     }
6057   }
6058   llvm_unreachable("Exit infinite loop");
6059 }
6060 
6061 // Parse the function info index from the bitcode streamer into the given index.
6062 std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6063     std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
6064   TheIndex = I;
6065 
6066   if (std::error_code EC = initStream(std::move(Streamer)))
6067     return EC;
6068 
6069   // Sniff for the signature.
6070   if (!hasValidBitcodeHeader(Stream))
6071     return error("Invalid bitcode signature");
6072 
6073   // We expect a number of well-defined blocks, though we don't necessarily
6074   // need to understand them all.
6075   while (1) {
6076     if (Stream.AtEndOfStream()) {
6077       // We didn't really read a proper Module block.
6078       return error("Malformed block");
6079     }
6080 
6081     BitstreamEntry Entry =
6082         Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6083 
6084     if (Entry.Kind != BitstreamEntry::SubBlock)
6085       return error("Malformed block");
6086 
6087     // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6088     // building the function summary index.
6089     if (Entry.ID == bitc::MODULE_BLOCK_ID)
6090       return parseModule();
6091 
6092     if (Stream.SkipBlock())
6093       return error("Invalid record");
6094   }
6095 }
6096 
6097 // Parse the summary information at the given offset in the buffer into
6098 // the index. Used to support lazy parsing of summaries from the
6099 // combined index during importing.
6100 // TODO: This function is not yet complete as it won't have a consumer
6101 // until ThinLTO function importing is added.
6102 std::error_code ModuleSummaryIndexBitcodeReader::parseGlobalValueSummary(
6103     std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I,
6104     size_t SummaryOffset) {
6105   TheIndex = I;
6106 
6107   if (std::error_code EC = initStream(std::move(Streamer)))
6108     return EC;
6109 
6110   // Sniff for the signature.
6111   if (!hasValidBitcodeHeader(Stream))
6112     return error("Invalid bitcode signature");
6113 
6114   Stream.JumpToBit(SummaryOffset);
6115 
6116   BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6117 
6118   switch (Entry.Kind) {
6119   default:
6120     return error("Malformed block");
6121   case BitstreamEntry::Record:
6122     // The expected case.
6123     break;
6124   }
6125 
6126   // TODO: Read a record. This interface will be completed when ThinLTO
6127   // importing is added so that it can be tested.
6128   SmallVector<uint64_t, 64> Record;
6129   switch (Stream.readRecord(Entry.ID, Record)) {
6130   case bitc::FS_COMBINED:
6131   case bitc::FS_COMBINED_PROFILE:
6132   case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS:
6133   default:
6134     return error("Invalid record");
6135   }
6136 
6137   return std::error_code();
6138 }
6139 
6140 std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6141     std::unique_ptr<DataStreamer> Streamer) {
6142   if (Streamer)
6143     return initLazyStream(std::move(Streamer));
6144   return initStreamFromBuffer();
6145 }
6146 
6147 std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
6148   const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6149   const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6150 
6151   if (Buffer->getBufferSize() & 3)
6152     return error("Invalid bitcode signature");
6153 
6154   // If we have a wrapper header, parse it and ignore the non-bc file contents.
6155   // The magic number is 0x0B17C0DE stored in little endian.
6156   if (isBitcodeWrapper(BufPtr, BufEnd))
6157     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6158       return error("Invalid bitcode wrapper header");
6159 
6160   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6161   Stream.init(&*StreamFile);
6162 
6163   return std::error_code();
6164 }
6165 
6166 std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
6167     std::unique_ptr<DataStreamer> Streamer) {
6168   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6169   // see it.
6170   auto OwnedBytes =
6171       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6172   StreamingMemoryObject &Bytes = *OwnedBytes;
6173   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6174   Stream.init(&*StreamFile);
6175 
6176   unsigned char buf[16];
6177   if (Bytes.readBytes(buf, 16, 0) != 16)
6178     return error("Invalid bitcode signature");
6179 
6180   if (!isBitcode(buf, buf + 16))
6181     return error("Invalid bitcode signature");
6182 
6183   if (isBitcodeWrapper(buf, buf + 4)) {
6184     const unsigned char *bitcodeStart = buf;
6185     const unsigned char *bitcodeEnd = buf + 16;
6186     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6187     Bytes.dropLeadingBytes(bitcodeStart - buf);
6188     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6189   }
6190   return std::error_code();
6191 }
6192 
6193 namespace {
6194 class BitcodeErrorCategoryType : public std::error_category {
6195   const char *name() const LLVM_NOEXCEPT override {
6196     return "llvm.bitcode";
6197   }
6198   std::string message(int IE) const override {
6199     BitcodeError E = static_cast<BitcodeError>(IE);
6200     switch (E) {
6201     case BitcodeError::InvalidBitcodeSignature:
6202       return "Invalid bitcode signature";
6203     case BitcodeError::CorruptedBitcode:
6204       return "Corrupted bitcode";
6205     }
6206     llvm_unreachable("Unknown error type!");
6207   }
6208 };
6209 } // end anonymous namespace
6210 
6211 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6212 
6213 const std::error_category &llvm::BitcodeErrorCategory() {
6214   return *ErrorCategory;
6215 }
6216 
6217 //===----------------------------------------------------------------------===//
6218 // External interface
6219 //===----------------------------------------------------------------------===//
6220 
6221 static ErrorOr<std::unique_ptr<Module>>
6222 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6223                      BitcodeReader *R, LLVMContext &Context,
6224                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6225   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6226   M->setMaterializer(R);
6227 
6228   auto cleanupOnError = [&](std::error_code EC) {
6229     R->releaseBuffer(); // Never take ownership on error.
6230     return EC;
6231   };
6232 
6233   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6234   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6235                                                ShouldLazyLoadMetadata))
6236     return cleanupOnError(EC);
6237 
6238   if (MaterializeAll) {
6239     // Read in the entire module, and destroy the BitcodeReader.
6240     if (std::error_code EC = M->materializeAll())
6241       return cleanupOnError(EC);
6242   } else {
6243     // Resolve forward references from blockaddresses.
6244     if (std::error_code EC = R->materializeForwardReferencedFunctions())
6245       return cleanupOnError(EC);
6246   }
6247   return std::move(M);
6248 }
6249 
6250 /// \brief Get a lazy one-at-time loading module from bitcode.
6251 ///
6252 /// This isn't always used in a lazy context.  In particular, it's also used by
6253 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
6254 /// in forward-referenced functions from block address references.
6255 ///
6256 /// \param[in] MaterializeAll Set to \c true if we should materialize
6257 /// everything.
6258 static ErrorOr<std::unique_ptr<Module>>
6259 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
6260                          LLVMContext &Context, bool MaterializeAll,
6261                          bool ShouldLazyLoadMetadata = false) {
6262   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
6263 
6264   ErrorOr<std::unique_ptr<Module>> Ret =
6265       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6266                            MaterializeAll, ShouldLazyLoadMetadata);
6267   if (!Ret)
6268     return Ret;
6269 
6270   Buffer.release(); // The BitcodeReader owns it now.
6271   return Ret;
6272 }
6273 
6274 ErrorOr<std::unique_ptr<Module>>
6275 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6276                            LLVMContext &Context, bool ShouldLazyLoadMetadata) {
6277   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
6278                                   ShouldLazyLoadMetadata);
6279 }
6280 
6281 ErrorOr<std::unique_ptr<Module>>
6282 llvm::getStreamedBitcodeModule(StringRef Name,
6283                                std::unique_ptr<DataStreamer> Streamer,
6284                                LLVMContext &Context) {
6285   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6286   BitcodeReader *R = new BitcodeReader(Context);
6287 
6288   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6289                               false);
6290 }
6291 
6292 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6293                                                         LLVMContext &Context) {
6294   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6295   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
6296   // TODO: Restore the use-lists to the in-memory state when the bitcode was
6297   // written.  We must defer until the Module has been fully materialized.
6298 }
6299 
6300 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6301                                          LLVMContext &Context) {
6302   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6303   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6304   ErrorOr<std::string> Triple = R->parseTriple();
6305   if (Triple.getError())
6306     return "";
6307   return Triple.get();
6308 }
6309 
6310 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6311                                            LLVMContext &Context) {
6312   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6313   BitcodeReader R(Buf.release(), Context);
6314   ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6315   if (ProducerString.getError())
6316     return "";
6317   return ProducerString.get();
6318 }
6319 
6320 // Parse the specified bitcode buffer, returning the function info index.
6321 // If IsLazy is false, parse the entire function summary into
6322 // the index. Otherwise skip the function summary section, and only create
6323 // an index object with a map from function name to function summary offset.
6324 // The index is used to perform lazy function summary reading later.
6325 ErrorOr<std::unique_ptr<ModuleSummaryIndex>>
6326 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer,
6327                             DiagnosticHandlerFunction DiagnosticHandler,
6328                             bool IsLazy) {
6329   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6330   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
6331 
6332   auto Index = llvm::make_unique<ModuleSummaryIndex>();
6333 
6334   auto cleanupOnError = [&](std::error_code EC) {
6335     R.releaseBuffer(); // Never take ownership on error.
6336     return EC;
6337   };
6338 
6339   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6340     return cleanupOnError(EC);
6341 
6342   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6343   return std::move(Index);
6344 }
6345 
6346 // Check if the given bitcode buffer contains a global value summary block.
6347 bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer,
6348                                  DiagnosticHandlerFunction DiagnosticHandler) {
6349   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6350   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
6351 
6352   auto cleanupOnError = [&](std::error_code EC) {
6353     R.releaseBuffer(); // Never take ownership on error.
6354     return false;
6355   };
6356 
6357   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6358     return cleanupOnError(EC);
6359 
6360   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6361   return R.foundGlobalValSummary();
6362 }
6363 
6364 // This method supports lazy reading of summary data from the combined
6365 // index during ThinLTO function importing. When reading the combined index
6366 // file, getModuleSummaryIndex is first invoked with IsLazy=true.
6367 // Then this method is called for each value considered for importing,
6368 // to parse the summary information for the given value name into
6369 // the index.
6370 std::error_code llvm::readGlobalValueSummary(
6371     MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
6372     StringRef ValueName, std::unique_ptr<ModuleSummaryIndex> Index) {
6373   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6374   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
6375 
6376   auto cleanupOnError = [&](std::error_code EC) {
6377     R.releaseBuffer(); // Never take ownership on error.
6378     return EC;
6379   };
6380 
6381   // Lookup the given value name in the GlobalValueMap, which may
6382   // contain a list of global value infos in the case of a COMDAT. Walk through
6383   // and parse each summary info at the summary offset
6384   // recorded when parsing the value symbol table.
6385   for (const auto &FI : Index->getGlobalValueInfoList(ValueName)) {
6386     size_t SummaryOffset = FI->bitcodeIndex();
6387     if (std::error_code EC =
6388             R.parseGlobalValueSummary(nullptr, Index.get(), SummaryOffset))
6389       return cleanupOnError(EC);
6390   }
6391 
6392   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6393   return std::error_code();
6394 }
6395