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