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