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