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