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