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