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