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