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