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