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