xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 1804a77b2a70dea81cc21b171febcc9df9cc1274)
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       MetadataList.assignValue(
2418           GET_OR_DISTINCT(
2419               DIDerivedType,
2420               (Context, Record[1], getMDString(Record[2]),
2421                getMDOrNull(Record[3]), Record[4], getDITypeRefOrNull(Record[5]),
2422                getDITypeRefOrNull(Record[6]), Record[7], Record[8], Record[9],
2423                Record[10], getDITypeRefOrNull(Record[11]))),
2424           NextMetadataNo++);
2425       break;
2426     }
2427     case bitc::METADATA_COMPOSITE_TYPE: {
2428       if (Record.size() != 16)
2429         return error("Invalid record");
2430 
2431       // If we have a UUID and this is not a forward declaration, lookup the
2432       // mapping.
2433       IsDistinct = Record[0] & 0x1;
2434       bool IsNotUsedInTypeRef = Record[0] >= 2;
2435       unsigned Tag = Record[1];
2436       MDString *Name = getMDString(Record[2]);
2437       Metadata *File = getMDOrNull(Record[3]);
2438       unsigned Line = Record[4];
2439       Metadata *Scope = getDITypeRefOrNull(Record[5]);
2440       Metadata *BaseType = getDITypeRefOrNull(Record[6]);
2441       uint64_t SizeInBits = Record[7];
2442       uint64_t AlignInBits = Record[8];
2443       uint64_t OffsetInBits = Record[9];
2444       unsigned Flags = Record[10];
2445       Metadata *Elements = getMDOrNull(Record[11]);
2446       unsigned RuntimeLang = Record[12];
2447       Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
2448       Metadata *TemplateParams = getMDOrNull(Record[14]);
2449       auto *Identifier = getMDString(Record[15]);
2450       DICompositeType *CT = nullptr;
2451       if (Identifier)
2452         CT = DICompositeType::buildODRType(
2453             Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2454             SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2455             VTableHolder, TemplateParams);
2456 
2457       // Create a node if we didn't get a lazy ODR type.
2458       if (!CT)
2459         CT = GET_OR_DISTINCT(DICompositeType,
2460                              (Context, Tag, Name, File, Line, Scope, BaseType,
2461                               SizeInBits, AlignInBits, OffsetInBits, Flags,
2462                               Elements, RuntimeLang, VTableHolder,
2463                               TemplateParams, Identifier));
2464       if (!IsNotUsedInTypeRef && Identifier)
2465         MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
2466 
2467       MetadataList.assignValue(CT, NextMetadataNo++);
2468       break;
2469     }
2470     case bitc::METADATA_SUBROUTINE_TYPE: {
2471       if (Record.size() < 3 || Record.size() > 4)
2472         return error("Invalid record");
2473       bool IsOldTypeRefArray = Record[0] < 2;
2474       unsigned CC = (Record.size() > 3) ? Record[3] : 0;
2475 
2476       IsDistinct = Record[0] & 0x1;
2477       Metadata *Types = getMDOrNull(Record[2]);
2478       if (LLVM_UNLIKELY(IsOldTypeRefArray))
2479         Types = MetadataList.upgradeTypeRefArray(Types);
2480 
2481       MetadataList.assignValue(
2482           GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], CC, Types)),
2483           NextMetadataNo++);
2484       break;
2485     }
2486 
2487     case bitc::METADATA_MODULE: {
2488       if (Record.size() != 6)
2489         return error("Invalid record");
2490 
2491       IsDistinct = Record[0];
2492       MetadataList.assignValue(
2493           GET_OR_DISTINCT(DIModule,
2494                           (Context, getMDOrNull(Record[1]),
2495                            getMDString(Record[2]), getMDString(Record[3]),
2496                            getMDString(Record[4]), getMDString(Record[5]))),
2497           NextMetadataNo++);
2498       break;
2499     }
2500 
2501     case bitc::METADATA_FILE: {
2502       if (Record.size() != 3)
2503         return error("Invalid record");
2504 
2505       IsDistinct = Record[0];
2506       MetadataList.assignValue(
2507           GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2508                                    getMDString(Record[2]))),
2509           NextMetadataNo++);
2510       break;
2511     }
2512     case bitc::METADATA_COMPILE_UNIT: {
2513       if (Record.size() < 14 || Record.size() > 17)
2514         return error("Invalid record");
2515 
2516       // Ignore Record[0], which indicates whether this compile unit is
2517       // distinct.  It's always distinct.
2518       IsDistinct = true;
2519       auto *CU = DICompileUnit::getDistinct(
2520           Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2521           Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2522           Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2523           getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2524           Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2525           Record.size() <= 14 ? 0 : Record[14],
2526           Record.size() <= 16 ? true : Record[16]);
2527 
2528       MetadataList.assignValue(CU, NextMetadataNo++);
2529 
2530       // Move the Upgrade the list of subprograms.
2531       if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
2532         CUSubprograms.push_back({CU, SPs});
2533       break;
2534     }
2535     case bitc::METADATA_SUBPROGRAM: {
2536       if (Record.size() < 18 || Record.size() > 20)
2537         return error("Invalid record");
2538 
2539       IsDistinct =
2540           (Record[0] & 1) || Record[8]; // All definitions should be distinct.
2541       // Version 1 has a Function as Record[15].
2542       // Version 2 has removed Record[15].
2543       // Version 3 has the Unit as Record[15].
2544       // Version 4 added thisAdjustment.
2545       bool HasUnit = Record[0] >= 2;
2546       if (HasUnit && Record.size() < 19)
2547         return error("Invalid record");
2548       Metadata *CUorFn = getMDOrNull(Record[15]);
2549       unsigned Offset = Record.size() >= 19 ? 1 : 0;
2550       bool HasFn = Offset && !HasUnit;
2551       bool HasThisAdj = Record.size() >= 20;
2552       DISubprogram *SP = GET_OR_DISTINCT(
2553           DISubprogram, (Context,
2554                          getDITypeRefOrNull(Record[1]),    // scope
2555                          getMDString(Record[2]),           // name
2556                          getMDString(Record[3]),           // linkageName
2557                          getMDOrNull(Record[4]),           // file
2558                          Record[5],                        // line
2559                          getMDOrNull(Record[6]),           // type
2560                          Record[7],                        // isLocal
2561                          Record[8],                        // isDefinition
2562                          Record[9],                        // scopeLine
2563                          getDITypeRefOrNull(Record[10]),   // containingType
2564                          Record[11],                       // virtuality
2565                          Record[12],                       // virtualIndex
2566                          HasThisAdj ? Record[19] : 0,      // thisAdjustment
2567                          Record[13],                       // flags
2568                          Record[14],                       // isOptimized
2569                          HasUnit ? CUorFn : nullptr,       // unit
2570                          getMDOrNull(Record[15 + Offset]), // templateParams
2571                          getMDOrNull(Record[16 + Offset]), // declaration
2572                          getMDOrNull(Record[17 + Offset])  // variables
2573                          ));
2574       MetadataList.assignValue(SP, NextMetadataNo++);
2575 
2576       // Upgrade sp->function mapping to function->sp mapping.
2577       if (HasFn) {
2578         if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2579           if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2580             if (F->isMaterializable())
2581               // Defer until materialized; unmaterialized functions may not have
2582               // metadata.
2583               FunctionsWithSPs[F] = SP;
2584             else if (!F->empty())
2585               F->setSubprogram(SP);
2586           }
2587       }
2588       break;
2589     }
2590     case bitc::METADATA_LEXICAL_BLOCK: {
2591       if (Record.size() != 5)
2592         return error("Invalid record");
2593 
2594       IsDistinct = Record[0];
2595       MetadataList.assignValue(
2596           GET_OR_DISTINCT(DILexicalBlock,
2597                           (Context, getMDOrNull(Record[1]),
2598                            getMDOrNull(Record[2]), Record[3], Record[4])),
2599           NextMetadataNo++);
2600       break;
2601     }
2602     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2603       if (Record.size() != 4)
2604         return error("Invalid record");
2605 
2606       IsDistinct = Record[0];
2607       MetadataList.assignValue(
2608           GET_OR_DISTINCT(DILexicalBlockFile,
2609                           (Context, getMDOrNull(Record[1]),
2610                            getMDOrNull(Record[2]), Record[3])),
2611           NextMetadataNo++);
2612       break;
2613     }
2614     case bitc::METADATA_NAMESPACE: {
2615       if (Record.size() != 5)
2616         return error("Invalid record");
2617 
2618       IsDistinct = Record[0];
2619       MetadataList.assignValue(
2620           GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2621                                         getMDOrNull(Record[2]),
2622                                         getMDString(Record[3]), Record[4])),
2623           NextMetadataNo++);
2624       break;
2625     }
2626     case bitc::METADATA_MACRO: {
2627       if (Record.size() != 5)
2628         return error("Invalid record");
2629 
2630       IsDistinct = Record[0];
2631       MetadataList.assignValue(
2632           GET_OR_DISTINCT(DIMacro,
2633                           (Context, Record[1], Record[2],
2634                            getMDString(Record[3]), getMDString(Record[4]))),
2635           NextMetadataNo++);
2636       break;
2637     }
2638     case bitc::METADATA_MACRO_FILE: {
2639       if (Record.size() != 5)
2640         return error("Invalid record");
2641 
2642       IsDistinct = Record[0];
2643       MetadataList.assignValue(
2644           GET_OR_DISTINCT(DIMacroFile,
2645                           (Context, Record[1], Record[2],
2646                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2647           NextMetadataNo++);
2648       break;
2649     }
2650     case bitc::METADATA_TEMPLATE_TYPE: {
2651       if (Record.size() != 3)
2652         return error("Invalid record");
2653 
2654       IsDistinct = Record[0];
2655       MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2656                                                (Context, getMDString(Record[1]),
2657                                                 getDITypeRefOrNull(Record[2]))),
2658                                NextMetadataNo++);
2659       break;
2660     }
2661     case bitc::METADATA_TEMPLATE_VALUE: {
2662       if (Record.size() != 5)
2663         return error("Invalid record");
2664 
2665       IsDistinct = Record[0];
2666       MetadataList.assignValue(
2667           GET_OR_DISTINCT(DITemplateValueParameter,
2668                           (Context, Record[1], getMDString(Record[2]),
2669                            getDITypeRefOrNull(Record[3]),
2670                            getMDOrNull(Record[4]))),
2671           NextMetadataNo++);
2672       break;
2673     }
2674     case bitc::METADATA_GLOBAL_VAR: {
2675       if (Record.size() != 11)
2676         return error("Invalid record");
2677 
2678       IsDistinct = Record[0];
2679       MetadataList.assignValue(
2680           GET_OR_DISTINCT(DIGlobalVariable,
2681                           (Context, getMDOrNull(Record[1]),
2682                            getMDString(Record[2]), getMDString(Record[3]),
2683                            getMDOrNull(Record[4]), Record[5],
2684                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2685                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2686           NextMetadataNo++);
2687       break;
2688     }
2689     case bitc::METADATA_LOCAL_VAR: {
2690       // 10th field is for the obseleted 'inlinedAt:' field.
2691       if (Record.size() < 8 || Record.size() > 10)
2692         return error("Invalid record");
2693 
2694       // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2695       // DW_TAG_arg_variable.
2696       IsDistinct = Record[0];
2697       bool HasTag = Record.size() > 8;
2698       MetadataList.assignValue(
2699           GET_OR_DISTINCT(DILocalVariable,
2700                           (Context, getMDOrNull(Record[1 + HasTag]),
2701                            getMDString(Record[2 + HasTag]),
2702                            getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2703                            getDITypeRefOrNull(Record[5 + HasTag]),
2704                            Record[6 + HasTag], Record[7 + HasTag])),
2705           NextMetadataNo++);
2706       break;
2707     }
2708     case bitc::METADATA_EXPRESSION: {
2709       if (Record.size() < 1)
2710         return error("Invalid record");
2711 
2712       IsDistinct = Record[0];
2713       MetadataList.assignValue(
2714           GET_OR_DISTINCT(DIExpression,
2715                           (Context, makeArrayRef(Record).slice(1))),
2716           NextMetadataNo++);
2717       break;
2718     }
2719     case bitc::METADATA_OBJC_PROPERTY: {
2720       if (Record.size() != 8)
2721         return error("Invalid record");
2722 
2723       IsDistinct = Record[0];
2724       MetadataList.assignValue(
2725           GET_OR_DISTINCT(DIObjCProperty,
2726                           (Context, getMDString(Record[1]),
2727                            getMDOrNull(Record[2]), Record[3],
2728                            getMDString(Record[4]), getMDString(Record[5]),
2729                            Record[6], getDITypeRefOrNull(Record[7]))),
2730           NextMetadataNo++);
2731       break;
2732     }
2733     case bitc::METADATA_IMPORTED_ENTITY: {
2734       if (Record.size() != 6)
2735         return error("Invalid record");
2736 
2737       IsDistinct = Record[0];
2738       MetadataList.assignValue(
2739           GET_OR_DISTINCT(DIImportedEntity,
2740                           (Context, Record[1], getMDOrNull(Record[2]),
2741                            getDITypeRefOrNull(Record[3]), Record[4],
2742                            getMDString(Record[5]))),
2743           NextMetadataNo++);
2744       break;
2745     }
2746     case bitc::METADATA_STRING_OLD: {
2747       std::string String(Record.begin(), Record.end());
2748 
2749       // Test for upgrading !llvm.loop.
2750       HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2751 
2752       Metadata *MD = MDString::get(Context, String);
2753       MetadataList.assignValue(MD, NextMetadataNo++);
2754       break;
2755     }
2756     case bitc::METADATA_STRINGS:
2757       if (std::error_code EC =
2758               parseMetadataStrings(Record, Blob, NextMetadataNo))
2759         return EC;
2760       break;
2761     case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2762       if (Record.size() % 2 == 0)
2763         return error("Invalid record");
2764       unsigned ValueID = Record[0];
2765       if (ValueID >= ValueList.size())
2766         return error("Invalid record");
2767       if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2768         parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
2769       break;
2770     }
2771     case bitc::METADATA_KIND: {
2772       // Support older bitcode files that had METADATA_KIND records in a
2773       // block with METADATA_BLOCK_ID.
2774       if (std::error_code EC = parseMetadataKindRecord(Record))
2775         return EC;
2776       break;
2777     }
2778     }
2779   }
2780 
2781 #undef GET_OR_DISTINCT
2782 }
2783 
2784 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2785 std::error_code BitcodeReader::parseMetadataKinds() {
2786   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2787     return error("Invalid record");
2788 
2789   SmallVector<uint64_t, 64> Record;
2790 
2791   // Read all the records.
2792   while (true) {
2793     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2794 
2795     switch (Entry.Kind) {
2796     case BitstreamEntry::SubBlock: // Handled for us already.
2797     case BitstreamEntry::Error:
2798       return error("Malformed block");
2799     case BitstreamEntry::EndBlock:
2800       return std::error_code();
2801     case BitstreamEntry::Record:
2802       // The interesting case.
2803       break;
2804     }
2805 
2806     // Read a record.
2807     Record.clear();
2808     unsigned Code = Stream.readRecord(Entry.ID, Record);
2809     switch (Code) {
2810     default: // Default behavior: ignore.
2811       break;
2812     case bitc::METADATA_KIND: {
2813       if (std::error_code EC = parseMetadataKindRecord(Record))
2814         return EC;
2815       break;
2816     }
2817     }
2818   }
2819 }
2820 
2821 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2822 /// encoding.
2823 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2824   if ((V & 1) == 0)
2825     return V >> 1;
2826   if (V != 1)
2827     return -(V >> 1);
2828   // There is no such thing as -0 with integers.  "-0" really means MININT.
2829   return 1ULL << 63;
2830 }
2831 
2832 /// Resolve all of the initializers for global values and aliases that we can.
2833 std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2834   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2835   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2836       IndirectSymbolInitWorklist;
2837   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2838   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2839   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2840 
2841   GlobalInitWorklist.swap(GlobalInits);
2842   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2843   FunctionPrefixWorklist.swap(FunctionPrefixes);
2844   FunctionPrologueWorklist.swap(FunctionPrologues);
2845   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2846 
2847   while (!GlobalInitWorklist.empty()) {
2848     unsigned ValID = GlobalInitWorklist.back().second;
2849     if (ValID >= ValueList.size()) {
2850       // Not ready to resolve this yet, it requires something later in the file.
2851       GlobalInits.push_back(GlobalInitWorklist.back());
2852     } else {
2853       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2854         GlobalInitWorklist.back().first->setInitializer(C);
2855       else
2856         return error("Expected a constant");
2857     }
2858     GlobalInitWorklist.pop_back();
2859   }
2860 
2861   while (!IndirectSymbolInitWorklist.empty()) {
2862     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2863     if (ValID >= ValueList.size()) {
2864       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2865     } else {
2866       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2867       if (!C)
2868         return error("Expected a constant");
2869       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2870       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2871         return error("Alias and aliasee types don't match");
2872       GIS->setIndirectSymbol(C);
2873     }
2874     IndirectSymbolInitWorklist.pop_back();
2875   }
2876 
2877   while (!FunctionPrefixWorklist.empty()) {
2878     unsigned ValID = FunctionPrefixWorklist.back().second;
2879     if (ValID >= ValueList.size()) {
2880       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2881     } else {
2882       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2883         FunctionPrefixWorklist.back().first->setPrefixData(C);
2884       else
2885         return error("Expected a constant");
2886     }
2887     FunctionPrefixWorklist.pop_back();
2888   }
2889 
2890   while (!FunctionPrologueWorklist.empty()) {
2891     unsigned ValID = FunctionPrologueWorklist.back().second;
2892     if (ValID >= ValueList.size()) {
2893       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2894     } else {
2895       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2896         FunctionPrologueWorklist.back().first->setPrologueData(C);
2897       else
2898         return error("Expected a constant");
2899     }
2900     FunctionPrologueWorklist.pop_back();
2901   }
2902 
2903   while (!FunctionPersonalityFnWorklist.empty()) {
2904     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2905     if (ValID >= ValueList.size()) {
2906       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2907     } else {
2908       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2909         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2910       else
2911         return error("Expected a constant");
2912     }
2913     FunctionPersonalityFnWorklist.pop_back();
2914   }
2915 
2916   return std::error_code();
2917 }
2918 
2919 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2920   SmallVector<uint64_t, 8> Words(Vals.size());
2921   transform(Vals, Words.begin(),
2922                  BitcodeReader::decodeSignRotatedValue);
2923 
2924   return APInt(TypeBits, Words);
2925 }
2926 
2927 std::error_code BitcodeReader::parseConstants() {
2928   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2929     return error("Invalid record");
2930 
2931   SmallVector<uint64_t, 64> Record;
2932 
2933   // Read all the records for this value table.
2934   Type *CurTy = Type::getInt32Ty(Context);
2935   unsigned NextCstNo = ValueList.size();
2936 
2937   while (true) {
2938     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2939 
2940     switch (Entry.Kind) {
2941     case BitstreamEntry::SubBlock: // Handled for us already.
2942     case BitstreamEntry::Error:
2943       return error("Malformed block");
2944     case BitstreamEntry::EndBlock:
2945       if (NextCstNo != ValueList.size())
2946         return error("Invalid constant reference");
2947 
2948       // Once all the constants have been read, go through and resolve forward
2949       // references.
2950       ValueList.resolveConstantForwardRefs();
2951       return std::error_code();
2952     case BitstreamEntry::Record:
2953       // The interesting case.
2954       break;
2955     }
2956 
2957     // Read a record.
2958     Record.clear();
2959     Type *VoidType = Type::getVoidTy(Context);
2960     Value *V = nullptr;
2961     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2962     switch (BitCode) {
2963     default:  // Default behavior: unknown constant
2964     case bitc::CST_CODE_UNDEF:     // UNDEF
2965       V = UndefValue::get(CurTy);
2966       break;
2967     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2968       if (Record.empty())
2969         return error("Invalid record");
2970       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2971         return error("Invalid record");
2972       if (TypeList[Record[0]] == VoidType)
2973         return error("Invalid constant type");
2974       CurTy = TypeList[Record[0]];
2975       continue;  // Skip the ValueList manipulation.
2976     case bitc::CST_CODE_NULL:      // NULL
2977       V = Constant::getNullValue(CurTy);
2978       break;
2979     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2980       if (!CurTy->isIntegerTy() || Record.empty())
2981         return error("Invalid record");
2982       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2983       break;
2984     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2985       if (!CurTy->isIntegerTy() || Record.empty())
2986         return error("Invalid record");
2987 
2988       APInt VInt =
2989           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2990       V = ConstantInt::get(Context, VInt);
2991 
2992       break;
2993     }
2994     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2995       if (Record.empty())
2996         return error("Invalid record");
2997       if (CurTy->isHalfTy())
2998         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2999                                              APInt(16, (uint16_t)Record[0])));
3000       else if (CurTy->isFloatTy())
3001         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
3002                                              APInt(32, (uint32_t)Record[0])));
3003       else if (CurTy->isDoubleTy())
3004         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
3005                                              APInt(64, Record[0])));
3006       else if (CurTy->isX86_FP80Ty()) {
3007         // Bits are not stored the same way as a normal i80 APInt, compensate.
3008         uint64_t Rearrange[2];
3009         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3010         Rearrange[1] = Record[0] >> 48;
3011         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
3012                                              APInt(80, Rearrange)));
3013       } else if (CurTy->isFP128Ty())
3014         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
3015                                              APInt(128, Record)));
3016       else if (CurTy->isPPC_FP128Ty())
3017         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
3018                                              APInt(128, Record)));
3019       else
3020         V = UndefValue::get(CurTy);
3021       break;
3022     }
3023 
3024     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3025       if (Record.empty())
3026         return error("Invalid record");
3027 
3028       unsigned Size = Record.size();
3029       SmallVector<Constant*, 16> Elts;
3030 
3031       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3032         for (unsigned i = 0; i != Size; ++i)
3033           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
3034                                                      STy->getElementType(i)));
3035         V = ConstantStruct::get(STy, Elts);
3036       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
3037         Type *EltTy = ATy->getElementType();
3038         for (unsigned i = 0; i != Size; ++i)
3039           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
3040         V = ConstantArray::get(ATy, Elts);
3041       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
3042         Type *EltTy = VTy->getElementType();
3043         for (unsigned i = 0; i != Size; ++i)
3044           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
3045         V = ConstantVector::get(Elts);
3046       } else {
3047         V = UndefValue::get(CurTy);
3048       }
3049       break;
3050     }
3051     case bitc::CST_CODE_STRING:    // STRING: [values]
3052     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3053       if (Record.empty())
3054         return error("Invalid record");
3055 
3056       SmallString<16> Elts(Record.begin(), Record.end());
3057       V = ConstantDataArray::getString(Context, Elts,
3058                                        BitCode == bitc::CST_CODE_CSTRING);
3059       break;
3060     }
3061     case bitc::CST_CODE_DATA: {// DATA: [n x value]
3062       if (Record.empty())
3063         return error("Invalid record");
3064 
3065       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
3066       if (EltTy->isIntegerTy(8)) {
3067         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3068         if (isa<VectorType>(CurTy))
3069           V = ConstantDataVector::get(Context, Elts);
3070         else
3071           V = ConstantDataArray::get(Context, Elts);
3072       } else if (EltTy->isIntegerTy(16)) {
3073         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3074         if (isa<VectorType>(CurTy))
3075           V = ConstantDataVector::get(Context, Elts);
3076         else
3077           V = ConstantDataArray::get(Context, Elts);
3078       } else if (EltTy->isIntegerTy(32)) {
3079         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3080         if (isa<VectorType>(CurTy))
3081           V = ConstantDataVector::get(Context, Elts);
3082         else
3083           V = ConstantDataArray::get(Context, Elts);
3084       } else if (EltTy->isIntegerTy(64)) {
3085         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3086         if (isa<VectorType>(CurTy))
3087           V = ConstantDataVector::get(Context, Elts);
3088         else
3089           V = ConstantDataArray::get(Context, Elts);
3090       } else if (EltTy->isHalfTy()) {
3091         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3092         if (isa<VectorType>(CurTy))
3093           V = ConstantDataVector::getFP(Context, Elts);
3094         else
3095           V = ConstantDataArray::getFP(Context, Elts);
3096       } else if (EltTy->isFloatTy()) {
3097         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3098         if (isa<VectorType>(CurTy))
3099           V = ConstantDataVector::getFP(Context, Elts);
3100         else
3101           V = ConstantDataArray::getFP(Context, Elts);
3102       } else if (EltTy->isDoubleTy()) {
3103         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3104         if (isa<VectorType>(CurTy))
3105           V = ConstantDataVector::getFP(Context, Elts);
3106         else
3107           V = ConstantDataArray::getFP(Context, Elts);
3108       } else {
3109         return error("Invalid type for value");
3110       }
3111       break;
3112     }
3113     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
3114       if (Record.size() < 3)
3115         return error("Invalid record");
3116       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3117       if (Opc < 0) {
3118         V = UndefValue::get(CurTy);  // Unknown binop.
3119       } else {
3120         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3121         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
3122         unsigned Flags = 0;
3123         if (Record.size() >= 4) {
3124           if (Opc == Instruction::Add ||
3125               Opc == Instruction::Sub ||
3126               Opc == Instruction::Mul ||
3127               Opc == Instruction::Shl) {
3128             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3129               Flags |= OverflowingBinaryOperator::NoSignedWrap;
3130             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3131               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3132           } else if (Opc == Instruction::SDiv ||
3133                      Opc == Instruction::UDiv ||
3134                      Opc == Instruction::LShr ||
3135                      Opc == Instruction::AShr) {
3136             if (Record[3] & (1 << bitc::PEO_EXACT))
3137               Flags |= SDivOperator::IsExact;
3138           }
3139         }
3140         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
3141       }
3142       break;
3143     }
3144     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
3145       if (Record.size() < 3)
3146         return error("Invalid record");
3147       int Opc = getDecodedCastOpcode(Record[0]);
3148       if (Opc < 0) {
3149         V = UndefValue::get(CurTy);  // Unknown cast.
3150       } else {
3151         Type *OpTy = getTypeByID(Record[1]);
3152         if (!OpTy)
3153           return error("Invalid record");
3154         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
3155         V = UpgradeBitCastExpr(Opc, Op, CurTy);
3156         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
3157       }
3158       break;
3159     }
3160     case bitc::CST_CODE_CE_INBOUNDS_GEP:
3161     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
3162       unsigned OpNum = 0;
3163       Type *PointeeType = nullptr;
3164       if (Record.size() % 2)
3165         PointeeType = getTypeByID(Record[OpNum++]);
3166       SmallVector<Constant*, 16> Elts;
3167       while (OpNum != Record.size()) {
3168         Type *ElTy = getTypeByID(Record[OpNum++]);
3169         if (!ElTy)
3170           return error("Invalid record");
3171         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
3172       }
3173 
3174       if (PointeeType &&
3175           PointeeType !=
3176               cast<SequentialType>(Elts[0]->getType()->getScalarType())
3177                   ->getElementType())
3178         return error("Explicit gep operator type does not match pointee type "
3179                      "of pointer operand");
3180 
3181       if (Elts.size() < 1)
3182         return error("Invalid gep with no operands");
3183 
3184       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3185       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3186                                          BitCode ==
3187                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
3188       break;
3189     }
3190     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
3191       if (Record.size() < 3)
3192         return error("Invalid record");
3193 
3194       Type *SelectorTy = Type::getInt1Ty(Context);
3195 
3196       // The selector might be an i1 or an <n x i1>
3197       // Get the type from the ValueList before getting a forward ref.
3198       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
3199         if (Value *V = ValueList[Record[0]])
3200           if (SelectorTy != V->getType())
3201             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
3202 
3203       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3204                                                               SelectorTy),
3205                                   ValueList.getConstantFwdRef(Record[1],CurTy),
3206                                   ValueList.getConstantFwdRef(Record[2],CurTy));
3207       break;
3208     }
3209     case bitc::CST_CODE_CE_EXTRACTELT
3210         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3211       if (Record.size() < 3)
3212         return error("Invalid record");
3213       VectorType *OpTy =
3214         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3215       if (!OpTy)
3216         return error("Invalid record");
3217       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3218       Constant *Op1 = nullptr;
3219       if (Record.size() == 4) {
3220         Type *IdxTy = getTypeByID(Record[2]);
3221         if (!IdxTy)
3222           return error("Invalid record");
3223         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3224       } else // TODO: Remove with llvm 4.0
3225         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3226       if (!Op1)
3227         return error("Invalid record");
3228       V = ConstantExpr::getExtractElement(Op0, Op1);
3229       break;
3230     }
3231     case bitc::CST_CODE_CE_INSERTELT
3232         : { // CE_INSERTELT: [opval, opval, opty, opval]
3233       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3234       if (Record.size() < 3 || !OpTy)
3235         return error("Invalid record");
3236       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3237       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3238                                                   OpTy->getElementType());
3239       Constant *Op2 = nullptr;
3240       if (Record.size() == 4) {
3241         Type *IdxTy = getTypeByID(Record[2]);
3242         if (!IdxTy)
3243           return error("Invalid record");
3244         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3245       } else // TODO: Remove with llvm 4.0
3246         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3247       if (!Op2)
3248         return error("Invalid record");
3249       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
3250       break;
3251     }
3252     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3253       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3254       if (Record.size() < 3 || !OpTy)
3255         return error("Invalid record");
3256       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3257       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
3258       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3259                                                  OpTy->getNumElements());
3260       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
3261       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3262       break;
3263     }
3264     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3265       VectorType *RTy = dyn_cast<VectorType>(CurTy);
3266       VectorType *OpTy =
3267         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3268       if (Record.size() < 4 || !RTy || !OpTy)
3269         return error("Invalid record");
3270       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3271       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3272       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3273                                                  RTy->getNumElements());
3274       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
3275       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3276       break;
3277     }
3278     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
3279       if (Record.size() < 4)
3280         return error("Invalid record");
3281       Type *OpTy = getTypeByID(Record[0]);
3282       if (!OpTy)
3283         return error("Invalid record");
3284       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3285       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3286 
3287       if (OpTy->isFPOrFPVectorTy())
3288         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
3289       else
3290         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
3291       break;
3292     }
3293     // This maintains backward compatibility, pre-asm dialect keywords.
3294     // FIXME: Remove with the 4.0 release.
3295     case bitc::CST_CODE_INLINEASM_OLD: {
3296       if (Record.size() < 2)
3297         return error("Invalid record");
3298       std::string AsmStr, ConstrStr;
3299       bool HasSideEffects = Record[0] & 1;
3300       bool IsAlignStack = Record[0] >> 1;
3301       unsigned AsmStrSize = Record[1];
3302       if (2+AsmStrSize >= Record.size())
3303         return error("Invalid record");
3304       unsigned ConstStrSize = Record[2+AsmStrSize];
3305       if (3+AsmStrSize+ConstStrSize > Record.size())
3306         return error("Invalid record");
3307 
3308       for (unsigned i = 0; i != AsmStrSize; ++i)
3309         AsmStr += (char)Record[2+i];
3310       for (unsigned i = 0; i != ConstStrSize; ++i)
3311         ConstrStr += (char)Record[3+AsmStrSize+i];
3312       PointerType *PTy = cast<PointerType>(CurTy);
3313       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3314                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
3315       break;
3316     }
3317     // This version adds support for the asm dialect keywords (e.g.,
3318     // inteldialect).
3319     case bitc::CST_CODE_INLINEASM: {
3320       if (Record.size() < 2)
3321         return error("Invalid record");
3322       std::string AsmStr, ConstrStr;
3323       bool HasSideEffects = Record[0] & 1;
3324       bool IsAlignStack = (Record[0] >> 1) & 1;
3325       unsigned AsmDialect = Record[0] >> 2;
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                          InlineAsm::AsmDialect(AsmDialect));
3341       break;
3342     }
3343     case bitc::CST_CODE_BLOCKADDRESS:{
3344       if (Record.size() < 3)
3345         return error("Invalid record");
3346       Type *FnTy = getTypeByID(Record[0]);
3347       if (!FnTy)
3348         return error("Invalid record");
3349       Function *Fn =
3350         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
3351       if (!Fn)
3352         return error("Invalid record");
3353 
3354       // If the function is already parsed we can insert the block address right
3355       // away.
3356       BasicBlock *BB;
3357       unsigned BBID = Record[2];
3358       if (!BBID)
3359         // Invalid reference to entry block.
3360         return error("Invalid ID");
3361       if (!Fn->empty()) {
3362         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
3363         for (size_t I = 0, E = BBID; I != E; ++I) {
3364           if (BBI == BBE)
3365             return error("Invalid ID");
3366           ++BBI;
3367         }
3368         BB = &*BBI;
3369       } else {
3370         // Otherwise insert a placeholder and remember it so it can be inserted
3371         // when the function is parsed.
3372         auto &FwdBBs = BasicBlockFwdRefs[Fn];
3373         if (FwdBBs.empty())
3374           BasicBlockFwdRefQueue.push_back(Fn);
3375         if (FwdBBs.size() < BBID + 1)
3376           FwdBBs.resize(BBID + 1);
3377         if (!FwdBBs[BBID])
3378           FwdBBs[BBID] = BasicBlock::Create(Context);
3379         BB = FwdBBs[BBID];
3380       }
3381       V = BlockAddress::get(Fn, BB);
3382       break;
3383     }
3384     }
3385 
3386     ValueList.assignValue(V, NextCstNo);
3387     ++NextCstNo;
3388   }
3389 }
3390 
3391 std::error_code BitcodeReader::parseUseLists() {
3392   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3393     return error("Invalid record");
3394 
3395   // Read all the records.
3396   SmallVector<uint64_t, 64> Record;
3397 
3398   while (true) {
3399     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3400 
3401     switch (Entry.Kind) {
3402     case BitstreamEntry::SubBlock: // Handled for us already.
3403     case BitstreamEntry::Error:
3404       return error("Malformed block");
3405     case BitstreamEntry::EndBlock:
3406       return std::error_code();
3407     case BitstreamEntry::Record:
3408       // The interesting case.
3409       break;
3410     }
3411 
3412     // Read a use list record.
3413     Record.clear();
3414     bool IsBB = false;
3415     switch (Stream.readRecord(Entry.ID, Record)) {
3416     default:  // Default behavior: unknown type.
3417       break;
3418     case bitc::USELIST_CODE_BB:
3419       IsBB = true;
3420       LLVM_FALLTHROUGH;
3421     case bitc::USELIST_CODE_DEFAULT: {
3422       unsigned RecordLength = Record.size();
3423       if (RecordLength < 3)
3424         // Records should have at least an ID and two indexes.
3425         return error("Invalid record");
3426       unsigned ID = Record.back();
3427       Record.pop_back();
3428 
3429       Value *V;
3430       if (IsBB) {
3431         assert(ID < FunctionBBs.size() && "Basic block not found");
3432         V = FunctionBBs[ID];
3433       } else
3434         V = ValueList[ID];
3435       unsigned NumUses = 0;
3436       SmallDenseMap<const Use *, unsigned, 16> Order;
3437       for (const Use &U : V->materialized_uses()) {
3438         if (++NumUses > Record.size())
3439           break;
3440         Order[&U] = Record[NumUses - 1];
3441       }
3442       if (Order.size() != Record.size() || NumUses > Record.size())
3443         // Mismatches can happen if the functions are being materialized lazily
3444         // (out-of-order), or a value has been upgraded.
3445         break;
3446 
3447       V->sortUseList([&](const Use &L, const Use &R) {
3448         return Order.lookup(&L) < Order.lookup(&R);
3449       });
3450       break;
3451     }
3452     }
3453   }
3454 }
3455 
3456 /// When we see the block for metadata, remember where it is and then skip it.
3457 /// This lets us lazily deserialize the metadata.
3458 std::error_code BitcodeReader::rememberAndSkipMetadata() {
3459   // Save the current stream state.
3460   uint64_t CurBit = Stream.GetCurrentBitNo();
3461   DeferredMetadataInfo.push_back(CurBit);
3462 
3463   // Skip over the block for now.
3464   if (Stream.SkipBlock())
3465     return error("Invalid record");
3466   return std::error_code();
3467 }
3468 
3469 std::error_code BitcodeReader::materializeMetadata() {
3470   for (uint64_t BitPos : DeferredMetadataInfo) {
3471     // Move the bit stream to the saved position.
3472     Stream.JumpToBit(BitPos);
3473     if (std::error_code EC = parseMetadata(true))
3474       return EC;
3475   }
3476   DeferredMetadataInfo.clear();
3477   return std::error_code();
3478 }
3479 
3480 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3481 
3482 /// When we see the block for a function body, remember where it is and then
3483 /// skip it.  This lets us lazily deserialize the functions.
3484 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3485   // Get the function we are talking about.
3486   if (FunctionsWithBodies.empty())
3487     return error("Insufficient function protos");
3488 
3489   Function *Fn = FunctionsWithBodies.back();
3490   FunctionsWithBodies.pop_back();
3491 
3492   // Save the current stream state.
3493   uint64_t CurBit = Stream.GetCurrentBitNo();
3494   assert(
3495       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3496       "Mismatch between VST and scanned function offsets");
3497   DeferredFunctionInfo[Fn] = CurBit;
3498 
3499   // Skip over the function block for now.
3500   if (Stream.SkipBlock())
3501     return error("Invalid record");
3502   return std::error_code();
3503 }
3504 
3505 std::error_code BitcodeReader::globalCleanup() {
3506   // Patch the initializers for globals and aliases up.
3507   resolveGlobalAndIndirectSymbolInits();
3508   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3509     return error("Malformed global initializer set");
3510 
3511   // Look for intrinsic functions which need to be upgraded at some point
3512   for (Function &F : *TheModule) {
3513     Function *NewFn;
3514     if (UpgradeIntrinsicFunction(&F, NewFn))
3515       UpgradedIntrinsics[&F] = NewFn;
3516     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3517       // Some types could be renamed during loading if several modules are
3518       // loaded in the same LLVMContext (LTO scenario). In this case we should
3519       // remangle intrinsics names as well.
3520       RemangledIntrinsics[&F] = Remangled.getValue();
3521   }
3522 
3523   // Look for global variables which need to be renamed.
3524   for (GlobalVariable &GV : TheModule->globals())
3525     UpgradeGlobalVariable(&GV);
3526 
3527   // Force deallocation of memory for these vectors to favor the client that
3528   // want lazy deserialization.
3529   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3530   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3531       IndirectSymbolInits);
3532   return std::error_code();
3533 }
3534 
3535 /// Support for lazy parsing of function bodies. This is required if we
3536 /// either have an old bitcode file without a VST forward declaration record,
3537 /// or if we have an anonymous function being materialized, since anonymous
3538 /// functions do not have a name and are therefore not in the VST.
3539 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3540   Stream.JumpToBit(NextUnreadBit);
3541 
3542   if (Stream.AtEndOfStream())
3543     return error("Could not find function in stream");
3544 
3545   if (!SeenFirstFunctionBody)
3546     return error("Trying to materialize functions before seeing function blocks");
3547 
3548   // An old bitcode file with the symbol table at the end would have
3549   // finished the parse greedily.
3550   assert(SeenValueSymbolTable);
3551 
3552   SmallVector<uint64_t, 64> Record;
3553 
3554   while (true) {
3555     BitstreamEntry Entry = Stream.advance();
3556     switch (Entry.Kind) {
3557     default:
3558       return error("Expect SubBlock");
3559     case BitstreamEntry::SubBlock:
3560       switch (Entry.ID) {
3561       default:
3562         return error("Expect function block");
3563       case bitc::FUNCTION_BLOCK_ID:
3564         if (std::error_code EC = rememberAndSkipFunctionBody())
3565           return EC;
3566         NextUnreadBit = Stream.GetCurrentBitNo();
3567         return std::error_code();
3568       }
3569     }
3570   }
3571 }
3572 
3573 std::error_code BitcodeReader::parseBitcodeVersion() {
3574   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3575     return error("Invalid record");
3576 
3577   // Read all the records.
3578   SmallVector<uint64_t, 64> Record;
3579 
3580   while (true) {
3581     BitstreamEntry Entry = Stream.advance();
3582 
3583     switch (Entry.Kind) {
3584     default:
3585     case BitstreamEntry::Error:
3586       return error("Malformed block");
3587     case BitstreamEntry::EndBlock:
3588       return std::error_code();
3589     case BitstreamEntry::Record:
3590       // The interesting case.
3591       break;
3592     }
3593 
3594     // Read a record.
3595     Record.clear();
3596     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3597     switch (BitCode) {
3598     default: // Default behavior: reject
3599       return error("Invalid value");
3600     case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION:      [strchr x
3601                                              // N]
3602       convertToString(Record, 0, ProducerIdentification);
3603       break;
3604     }
3605     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH:      [epoch#]
3606       unsigned epoch = (unsigned)Record[0];
3607       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3608         return error(
3609           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3610           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3611       }
3612     }
3613     }
3614   }
3615 }
3616 
3617 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3618                                            bool ShouldLazyLoadMetadata) {
3619   if (ResumeBit)
3620     Stream.JumpToBit(ResumeBit);
3621   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3622     return error("Invalid record");
3623 
3624   SmallVector<uint64_t, 64> Record;
3625   std::vector<std::string> SectionTable;
3626   std::vector<std::string> GCTable;
3627 
3628   // Read all the records for this module.
3629   while (true) {
3630     BitstreamEntry Entry = Stream.advance();
3631 
3632     switch (Entry.Kind) {
3633     case BitstreamEntry::Error:
3634       return error("Malformed block");
3635     case BitstreamEntry::EndBlock:
3636       return globalCleanup();
3637 
3638     case BitstreamEntry::SubBlock:
3639       switch (Entry.ID) {
3640       default:  // Skip unknown content.
3641         if (Stream.SkipBlock())
3642           return error("Invalid record");
3643         break;
3644       case bitc::BLOCKINFO_BLOCK_ID:
3645         if (Stream.ReadBlockInfoBlock())
3646           return error("Malformed block");
3647         break;
3648       case bitc::PARAMATTR_BLOCK_ID:
3649         if (std::error_code EC = parseAttributeBlock())
3650           return EC;
3651         break;
3652       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3653         if (std::error_code EC = parseAttributeGroupBlock())
3654           return EC;
3655         break;
3656       case bitc::TYPE_BLOCK_ID_NEW:
3657         if (std::error_code EC = parseTypeTable())
3658           return EC;
3659         break;
3660       case bitc::VALUE_SYMTAB_BLOCK_ID:
3661         if (!SeenValueSymbolTable) {
3662           // Either this is an old form VST without function index and an
3663           // associated VST forward declaration record (which would have caused
3664           // the VST to be jumped to and parsed before it was encountered
3665           // normally in the stream), or there were no function blocks to
3666           // trigger an earlier parsing of the VST.
3667           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3668           if (std::error_code EC = parseValueSymbolTable())
3669             return EC;
3670           SeenValueSymbolTable = true;
3671         } else {
3672           // We must have had a VST forward declaration record, which caused
3673           // the parser to jump to and parse the VST earlier.
3674           assert(VSTOffset > 0);
3675           if (Stream.SkipBlock())
3676             return error("Invalid record");
3677         }
3678         break;
3679       case bitc::CONSTANTS_BLOCK_ID:
3680         if (std::error_code EC = parseConstants())
3681           return EC;
3682         if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
3683           return EC;
3684         break;
3685       case bitc::METADATA_BLOCK_ID:
3686         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3687           if (std::error_code EC = rememberAndSkipMetadata())
3688             return EC;
3689           break;
3690         }
3691         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3692         if (std::error_code EC = parseMetadata(true))
3693           return EC;
3694         break;
3695       case bitc::METADATA_KIND_BLOCK_ID:
3696         if (std::error_code EC = parseMetadataKinds())
3697           return EC;
3698         break;
3699       case bitc::FUNCTION_BLOCK_ID:
3700         // If this is the first function body we've seen, reverse the
3701         // FunctionsWithBodies list.
3702         if (!SeenFirstFunctionBody) {
3703           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3704           if (std::error_code EC = globalCleanup())
3705             return EC;
3706           SeenFirstFunctionBody = true;
3707         }
3708 
3709         if (VSTOffset > 0) {
3710           // If we have a VST forward declaration record, make sure we
3711           // parse the VST now if we haven't already. It is needed to
3712           // set up the DeferredFunctionInfo vector for lazy reading.
3713           if (!SeenValueSymbolTable) {
3714             if (std::error_code EC =
3715                     BitcodeReader::parseValueSymbolTable(VSTOffset))
3716               return EC;
3717             SeenValueSymbolTable = true;
3718             // Fall through so that we record the NextUnreadBit below.
3719             // This is necessary in case we have an anonymous function that
3720             // is later materialized. Since it will not have a VST entry we
3721             // need to fall back to the lazy parse to find its offset.
3722           } else {
3723             // If we have a VST forward declaration record, but have already
3724             // parsed the VST (just above, when the first function body was
3725             // encountered here), then we are resuming the parse after
3726             // materializing functions. The ResumeBit points to the
3727             // start of the last function block recorded in the
3728             // DeferredFunctionInfo map. Skip it.
3729             if (Stream.SkipBlock())
3730               return error("Invalid record");
3731             continue;
3732           }
3733         }
3734 
3735         // Support older bitcode files that did not have the function
3736         // index in the VST, nor a VST forward declaration record, as
3737         // well as anonymous functions that do not have VST entries.
3738         // Build the DeferredFunctionInfo vector on the fly.
3739         if (std::error_code EC = rememberAndSkipFunctionBody())
3740           return EC;
3741 
3742         // Suspend parsing when we reach the function bodies. Subsequent
3743         // materialization calls will resume it when necessary. If the bitcode
3744         // file is old, the symbol table will be at the end instead and will not
3745         // have been seen yet. In this case, just finish the parse now.
3746         if (SeenValueSymbolTable) {
3747           NextUnreadBit = Stream.GetCurrentBitNo();
3748           // After the VST has been parsed, we need to make sure intrinsic name
3749           // are auto-upgraded.
3750           return globalCleanup();
3751         }
3752         break;
3753       case bitc::USELIST_BLOCK_ID:
3754         if (std::error_code EC = parseUseLists())
3755           return EC;
3756         break;
3757       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3758         if (std::error_code EC = parseOperandBundleTags())
3759           return EC;
3760         break;
3761       }
3762       continue;
3763 
3764     case BitstreamEntry::Record:
3765       // The interesting case.
3766       break;
3767     }
3768 
3769     // Read a record.
3770     auto BitCode = Stream.readRecord(Entry.ID, Record);
3771     switch (BitCode) {
3772     default: break;  // Default behavior, ignore unknown content.
3773     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
3774       if (Record.size() < 1)
3775         return error("Invalid record");
3776       // Only version #0 and #1 are supported so far.
3777       unsigned module_version = Record[0];
3778       switch (module_version) {
3779         default:
3780           return error("Invalid value");
3781         case 0:
3782           UseRelativeIDs = false;
3783           break;
3784         case 1:
3785           UseRelativeIDs = true;
3786           break;
3787       }
3788       break;
3789     }
3790     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3791       std::string S;
3792       if (convertToString(Record, 0, S))
3793         return error("Invalid record");
3794       TheModule->setTargetTriple(S);
3795       break;
3796     }
3797     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3798       std::string S;
3799       if (convertToString(Record, 0, S))
3800         return error("Invalid record");
3801       TheModule->setDataLayout(S);
3802       break;
3803     }
3804     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3805       std::string S;
3806       if (convertToString(Record, 0, S))
3807         return error("Invalid record");
3808       TheModule->setModuleInlineAsm(S);
3809       break;
3810     }
3811     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3812       // FIXME: Remove in 4.0.
3813       std::string S;
3814       if (convertToString(Record, 0, S))
3815         return error("Invalid record");
3816       // Ignore value.
3817       break;
3818     }
3819     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3820       std::string S;
3821       if (convertToString(Record, 0, S))
3822         return error("Invalid record");
3823       SectionTable.push_back(S);
3824       break;
3825     }
3826     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3827       std::string S;
3828       if (convertToString(Record, 0, S))
3829         return error("Invalid record");
3830       GCTable.push_back(S);
3831       break;
3832     }
3833     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3834       if (Record.size() < 2)
3835         return error("Invalid record");
3836       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3837       unsigned ComdatNameSize = Record[1];
3838       std::string ComdatName;
3839       ComdatName.reserve(ComdatNameSize);
3840       for (unsigned i = 0; i != ComdatNameSize; ++i)
3841         ComdatName += (char)Record[2 + i];
3842       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3843       C->setSelectionKind(SK);
3844       ComdatList.push_back(C);
3845       break;
3846     }
3847     // GLOBALVAR: [pointer type, isconst, initid,
3848     //             linkage, alignment, section, visibility, threadlocal,
3849     //             unnamed_addr, externally_initialized, dllstorageclass,
3850     //             comdat]
3851     case bitc::MODULE_CODE_GLOBALVAR: {
3852       if (Record.size() < 6)
3853         return error("Invalid record");
3854       Type *Ty = getTypeByID(Record[0]);
3855       if (!Ty)
3856         return error("Invalid record");
3857       bool isConstant = Record[1] & 1;
3858       bool explicitType = Record[1] & 2;
3859       unsigned AddressSpace;
3860       if (explicitType) {
3861         AddressSpace = Record[1] >> 2;
3862       } else {
3863         if (!Ty->isPointerTy())
3864           return error("Invalid type for value");
3865         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3866         Ty = cast<PointerType>(Ty)->getElementType();
3867       }
3868 
3869       uint64_t RawLinkage = Record[3];
3870       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3871       unsigned Alignment;
3872       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3873         return EC;
3874       std::string Section;
3875       if (Record[5]) {
3876         if (Record[5]-1 >= SectionTable.size())
3877           return error("Invalid ID");
3878         Section = SectionTable[Record[5]-1];
3879       }
3880       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3881       // Local linkage must have default visibility.
3882       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3883         // FIXME: Change to an error if non-default in 4.0.
3884         Visibility = getDecodedVisibility(Record[6]);
3885 
3886       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3887       if (Record.size() > 7)
3888         TLM = getDecodedThreadLocalMode(Record[7]);
3889 
3890       GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3891       if (Record.size() > 8)
3892         UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3893 
3894       bool ExternallyInitialized = false;
3895       if (Record.size() > 9)
3896         ExternallyInitialized = Record[9];
3897 
3898       GlobalVariable *NewGV =
3899         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3900                            TLM, AddressSpace, ExternallyInitialized);
3901       NewGV->setAlignment(Alignment);
3902       if (!Section.empty())
3903         NewGV->setSection(Section);
3904       NewGV->setVisibility(Visibility);
3905       NewGV->setUnnamedAddr(UnnamedAddr);
3906 
3907       if (Record.size() > 10)
3908         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3909       else
3910         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3911 
3912       ValueList.push_back(NewGV);
3913 
3914       // Remember which value to use for the global initializer.
3915       if (unsigned InitID = Record[2])
3916         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3917 
3918       if (Record.size() > 11) {
3919         if (unsigned ComdatID = Record[11]) {
3920           if (ComdatID > ComdatList.size())
3921             return error("Invalid global variable comdat ID");
3922           NewGV->setComdat(ComdatList[ComdatID - 1]);
3923         }
3924       } else if (hasImplicitComdat(RawLinkage)) {
3925         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3926       }
3927 
3928       break;
3929     }
3930     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
3931     //             alignment, section, visibility, gc, unnamed_addr,
3932     //             prologuedata, dllstorageclass, comdat, prefixdata]
3933     case bitc::MODULE_CODE_FUNCTION: {
3934       if (Record.size() < 8)
3935         return error("Invalid record");
3936       Type *Ty = getTypeByID(Record[0]);
3937       if (!Ty)
3938         return error("Invalid record");
3939       if (auto *PTy = dyn_cast<PointerType>(Ty))
3940         Ty = PTy->getElementType();
3941       auto *FTy = dyn_cast<FunctionType>(Ty);
3942       if (!FTy)
3943         return error("Invalid type for value");
3944       auto CC = static_cast<CallingConv::ID>(Record[1]);
3945       if (CC & ~CallingConv::MaxID)
3946         return error("Invalid calling convention ID");
3947 
3948       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3949                                         "", TheModule);
3950 
3951       Func->setCallingConv(CC);
3952       bool isProto = Record[2];
3953       uint64_t RawLinkage = Record[3];
3954       Func->setLinkage(getDecodedLinkage(RawLinkage));
3955       Func->setAttributes(getAttributes(Record[4]));
3956 
3957       unsigned Alignment;
3958       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3959         return EC;
3960       Func->setAlignment(Alignment);
3961       if (Record[6]) {
3962         if (Record[6]-1 >= SectionTable.size())
3963           return error("Invalid ID");
3964         Func->setSection(SectionTable[Record[6]-1]);
3965       }
3966       // Local linkage must have default visibility.
3967       if (!Func->hasLocalLinkage())
3968         // FIXME: Change to an error if non-default in 4.0.
3969         Func->setVisibility(getDecodedVisibility(Record[7]));
3970       if (Record.size() > 8 && Record[8]) {
3971         if (Record[8]-1 >= GCTable.size())
3972           return error("Invalid ID");
3973         Func->setGC(GCTable[Record[8] - 1]);
3974       }
3975       GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3976       if (Record.size() > 9)
3977         UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3978       Func->setUnnamedAddr(UnnamedAddr);
3979       if (Record.size() > 10 && Record[10] != 0)
3980         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3981 
3982       if (Record.size() > 11)
3983         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3984       else
3985         upgradeDLLImportExportLinkage(Func, RawLinkage);
3986 
3987       if (Record.size() > 12) {
3988         if (unsigned ComdatID = Record[12]) {
3989           if (ComdatID > ComdatList.size())
3990             return error("Invalid function comdat ID");
3991           Func->setComdat(ComdatList[ComdatID - 1]);
3992         }
3993       } else if (hasImplicitComdat(RawLinkage)) {
3994         Func->setComdat(reinterpret_cast<Comdat *>(1));
3995       }
3996 
3997       if (Record.size() > 13 && Record[13] != 0)
3998         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3999 
4000       if (Record.size() > 14 && Record[14] != 0)
4001         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
4002 
4003       ValueList.push_back(Func);
4004 
4005       // If this is a function with a body, remember the prototype we are
4006       // creating now, so that we can match up the body with them later.
4007       if (!isProto) {
4008         Func->setIsMaterializable(true);
4009         FunctionsWithBodies.push_back(Func);
4010         DeferredFunctionInfo[Func] = 0;
4011       }
4012       break;
4013     }
4014     // ALIAS: [alias type, addrspace, aliasee val#, linkage]
4015     // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
4016     // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
4017     case bitc::MODULE_CODE_IFUNC:
4018     case bitc::MODULE_CODE_ALIAS:
4019     case bitc::MODULE_CODE_ALIAS_OLD: {
4020       bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4021       if (Record.size() < (3 + (unsigned)NewRecord))
4022         return error("Invalid record");
4023       unsigned OpNum = 0;
4024       Type *Ty = getTypeByID(Record[OpNum++]);
4025       if (!Ty)
4026         return error("Invalid record");
4027 
4028       unsigned AddrSpace;
4029       if (!NewRecord) {
4030         auto *PTy = dyn_cast<PointerType>(Ty);
4031         if (!PTy)
4032           return error("Invalid type for value");
4033         Ty = PTy->getElementType();
4034         AddrSpace = PTy->getAddressSpace();
4035       } else {
4036         AddrSpace = Record[OpNum++];
4037       }
4038 
4039       auto Val = Record[OpNum++];
4040       auto Linkage = Record[OpNum++];
4041       GlobalIndirectSymbol *NewGA;
4042       if (BitCode == bitc::MODULE_CODE_ALIAS ||
4043           BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4044         NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
4045                                     "", TheModule);
4046       else
4047         NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
4048                                     "", nullptr, TheModule);
4049       // Old bitcode files didn't have visibility field.
4050       // Local linkage must have default visibility.
4051       if (OpNum != Record.size()) {
4052         auto VisInd = OpNum++;
4053         if (!NewGA->hasLocalLinkage())
4054           // FIXME: Change to an error if non-default in 4.0.
4055           NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4056       }
4057       if (OpNum != Record.size())
4058         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
4059       else
4060         upgradeDLLImportExportLinkage(NewGA, Linkage);
4061       if (OpNum != Record.size())
4062         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4063       if (OpNum != Record.size())
4064         NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4065       ValueList.push_back(NewGA);
4066       IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4067       break;
4068     }
4069     /// MODULE_CODE_PURGEVALS: [numvals]
4070     case bitc::MODULE_CODE_PURGEVALS:
4071       // Trim down the value list to the specified size.
4072       if (Record.size() < 1 || Record[0] > ValueList.size())
4073         return error("Invalid record");
4074       ValueList.shrinkTo(Record[0]);
4075       break;
4076     /// MODULE_CODE_VSTOFFSET: [offset]
4077     case bitc::MODULE_CODE_VSTOFFSET:
4078       if (Record.size() < 1)
4079         return error("Invalid record");
4080       VSTOffset = Record[0];
4081       break;
4082     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4083     case bitc::MODULE_CODE_SOURCE_FILENAME:
4084       SmallString<128> ValueName;
4085       if (convertToString(Record, 0, ValueName))
4086         return error("Invalid record");
4087       TheModule->setSourceFileName(ValueName);
4088       break;
4089     }
4090     Record.clear();
4091   }
4092 }
4093 
4094 /// Helper to read the header common to all bitcode files.
4095 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4096   // Sniff for the signature.
4097   if (Stream.Read(8) != 'B' ||
4098       Stream.Read(8) != 'C' ||
4099       Stream.Read(4) != 0x0 ||
4100       Stream.Read(4) != 0xC ||
4101       Stream.Read(4) != 0xE ||
4102       Stream.Read(4) != 0xD)
4103     return false;
4104   return true;
4105 }
4106 
4107 std::error_code
4108 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
4109                                 Module *M, bool ShouldLazyLoadMetadata) {
4110   TheModule = M;
4111 
4112   if (std::error_code EC = initStream(std::move(Streamer)))
4113     return EC;
4114 
4115   // Sniff for the signature.
4116   if (!hasValidBitcodeHeader(Stream))
4117     return error("Invalid bitcode signature");
4118 
4119   // We expect a number of well-defined blocks, though we don't necessarily
4120   // need to understand them all.
4121   while (true) {
4122     if (Stream.AtEndOfStream()) {
4123       // We didn't really read a proper Module.
4124       return error("Malformed IR file");
4125     }
4126 
4127     BitstreamEntry Entry =
4128       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
4129 
4130     if (Entry.Kind != BitstreamEntry::SubBlock)
4131       return error("Malformed block");
4132 
4133     if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4134       parseBitcodeVersion();
4135       continue;
4136     }
4137 
4138     if (Entry.ID == bitc::MODULE_BLOCK_ID)
4139       return parseModule(0, ShouldLazyLoadMetadata);
4140 
4141     if (Stream.SkipBlock())
4142       return error("Invalid record");
4143   }
4144 }
4145 
4146 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
4147   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4148     return error("Invalid record");
4149 
4150   SmallVector<uint64_t, 64> Record;
4151 
4152   std::string Triple;
4153 
4154   // Read all the records for this module.
4155   while (true) {
4156     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4157 
4158     switch (Entry.Kind) {
4159     case BitstreamEntry::SubBlock: // Handled for us already.
4160     case BitstreamEntry::Error:
4161       return error("Malformed block");
4162     case BitstreamEntry::EndBlock:
4163       return Triple;
4164     case BitstreamEntry::Record:
4165       // The interesting case.
4166       break;
4167     }
4168 
4169     // Read a record.
4170     switch (Stream.readRecord(Entry.ID, Record)) {
4171     default: break;  // Default behavior, ignore unknown content.
4172     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
4173       std::string S;
4174       if (convertToString(Record, 0, S))
4175         return error("Invalid record");
4176       Triple = S;
4177       break;
4178     }
4179     }
4180     Record.clear();
4181   }
4182   llvm_unreachable("Exit infinite loop");
4183 }
4184 
4185 ErrorOr<std::string> BitcodeReader::parseTriple() {
4186   if (std::error_code EC = initStream(nullptr))
4187     return EC;
4188 
4189   // Sniff for the signature.
4190   if (!hasValidBitcodeHeader(Stream))
4191     return error("Invalid bitcode signature");
4192 
4193   // We expect a number of well-defined blocks, though we don't necessarily
4194   // need to understand them all.
4195   while (true) {
4196     BitstreamEntry Entry = Stream.advance();
4197 
4198     switch (Entry.Kind) {
4199     case BitstreamEntry::Error:
4200       return error("Malformed block");
4201     case BitstreamEntry::EndBlock:
4202       return std::error_code();
4203 
4204     case BitstreamEntry::SubBlock:
4205       if (Entry.ID == bitc::MODULE_BLOCK_ID)
4206         return parseModuleTriple();
4207 
4208       // Ignore other sub-blocks.
4209       if (Stream.SkipBlock())
4210         return error("Malformed block");
4211       continue;
4212 
4213     case BitstreamEntry::Record:
4214       Stream.skipRecord(Entry.ID);
4215       continue;
4216     }
4217   }
4218 }
4219 
4220 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4221   if (std::error_code EC = initStream(nullptr))
4222     return EC;
4223 
4224   // Sniff for the signature.
4225   if (!hasValidBitcodeHeader(Stream))
4226     return error("Invalid bitcode signature");
4227 
4228   // We expect a number of well-defined blocks, though we don't necessarily
4229   // need to understand them all.
4230   while (true) {
4231     BitstreamEntry Entry = Stream.advance();
4232     switch (Entry.Kind) {
4233     case BitstreamEntry::Error:
4234       return error("Malformed block");
4235     case BitstreamEntry::EndBlock:
4236       return std::error_code();
4237 
4238     case BitstreamEntry::SubBlock:
4239       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4240         if (std::error_code EC = parseBitcodeVersion())
4241           return EC;
4242         return ProducerIdentification;
4243       }
4244       // Ignore other sub-blocks.
4245       if (Stream.SkipBlock())
4246         return error("Malformed block");
4247       continue;
4248     case BitstreamEntry::Record:
4249       Stream.skipRecord(Entry.ID);
4250       continue;
4251     }
4252   }
4253 }
4254 
4255 std::error_code BitcodeReader::parseGlobalObjectAttachment(
4256     GlobalObject &GO, ArrayRef<uint64_t> Record) {
4257   assert(Record.size() % 2 == 0);
4258   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4259     auto K = MDKindMap.find(Record[I]);
4260     if (K == MDKindMap.end())
4261       return error("Invalid ID");
4262     MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4263     if (!MD)
4264       return error("Invalid metadata attachment");
4265     GO.addMetadata(K->second, *MD);
4266   }
4267   return std::error_code();
4268 }
4269 
4270 ErrorOr<bool> BitcodeReader::hasObjCCategory() {
4271   if (std::error_code EC = initStream(nullptr))
4272     return EC;
4273 
4274   // Sniff for the signature.
4275   if (!hasValidBitcodeHeader(Stream))
4276     return error("Invalid bitcode signature");
4277 
4278   // We expect a number of well-defined blocks, though we don't necessarily
4279   // need to understand them all.
4280   while (true) {
4281     BitstreamEntry Entry = Stream.advance();
4282 
4283     switch (Entry.Kind) {
4284     case BitstreamEntry::Error:
4285       return error("Malformed block");
4286     case BitstreamEntry::EndBlock:
4287       return std::error_code();
4288 
4289     case BitstreamEntry::SubBlock:
4290       if (Entry.ID == bitc::MODULE_BLOCK_ID)
4291         return hasObjCCategoryInModule();
4292 
4293       // Ignore other sub-blocks.
4294       if (Stream.SkipBlock())
4295         return error("Malformed block");
4296       continue;
4297 
4298     case BitstreamEntry::Record:
4299       Stream.skipRecord(Entry.ID);
4300       continue;
4301     }
4302   }
4303 }
4304 
4305 ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
4306   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4307     return error("Invalid record");
4308 
4309   SmallVector<uint64_t, 64> Record;
4310   // Read all the records for this module.
4311 
4312   while (true) {
4313     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4314 
4315     switch (Entry.Kind) {
4316     case BitstreamEntry::SubBlock: // Handled for us already.
4317     case BitstreamEntry::Error:
4318       return error("Malformed block");
4319     case BitstreamEntry::EndBlock:
4320       return false;
4321     case BitstreamEntry::Record:
4322       // The interesting case.
4323       break;
4324     }
4325 
4326     // Read a record.
4327     switch (Stream.readRecord(Entry.ID, Record)) {
4328     default:
4329       break; // Default behavior, ignore unknown content.
4330     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4331       std::string S;
4332       if (convertToString(Record, 0, S))
4333         return error("Invalid record");
4334       // Check for the i386 and other (x86_64, ARM) conventions
4335       if (S.find("__DATA, __objc_catlist") != std::string::npos ||
4336           S.find("__OBJC,__category") != std::string::npos)
4337         return true;
4338       break;
4339     }
4340     }
4341     Record.clear();
4342   }
4343   llvm_unreachable("Exit infinite loop");
4344 }
4345 
4346 /// Parse metadata attachments.
4347 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
4348   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
4349     return error("Invalid record");
4350 
4351   SmallVector<uint64_t, 64> Record;
4352 
4353   while (true) {
4354     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4355 
4356     switch (Entry.Kind) {
4357     case BitstreamEntry::SubBlock: // Handled for us already.
4358     case BitstreamEntry::Error:
4359       return error("Malformed block");
4360     case BitstreamEntry::EndBlock:
4361       return std::error_code();
4362     case BitstreamEntry::Record:
4363       // The interesting case.
4364       break;
4365     }
4366 
4367     // Read a metadata attachment record.
4368     Record.clear();
4369     switch (Stream.readRecord(Entry.ID, Record)) {
4370     default:  // Default behavior: ignore.
4371       break;
4372     case bitc::METADATA_ATTACHMENT: {
4373       unsigned RecordLength = Record.size();
4374       if (Record.empty())
4375         return error("Invalid record");
4376       if (RecordLength % 2 == 0) {
4377         // A function attachment.
4378         if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4379           return EC;
4380         continue;
4381       }
4382 
4383       // An instruction attachment.
4384       Instruction *Inst = InstructionList[Record[0]];
4385       for (unsigned i = 1; i != RecordLength; i = i+2) {
4386         unsigned Kind = Record[i];
4387         DenseMap<unsigned, unsigned>::iterator I =
4388           MDKindMap.find(Kind);
4389         if (I == MDKindMap.end())
4390           return error("Invalid ID");
4391         Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
4392         if (isa<LocalAsMetadata>(Node))
4393           // Drop the attachment.  This used to be legal, but there's no
4394           // upgrade path.
4395           break;
4396         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4397         if (!MD)
4398           return error("Invalid metadata attachment");
4399 
4400         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4401           MD = upgradeInstructionLoopAttachment(*MD);
4402 
4403         Inst->setMetadata(I->second, MD);
4404         if (I->second == LLVMContext::MD_tbaa) {
4405           InstsWithTBAATag.push_back(Inst);
4406           continue;
4407         }
4408       }
4409       break;
4410     }
4411     }
4412   }
4413 }
4414 
4415 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4416   LLVMContext &Context = PtrType->getContext();
4417   if (!isa<PointerType>(PtrType))
4418     return error(Context, "Load/Store operand is not a pointer type");
4419   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4420 
4421   if (ValType && ValType != ElemType)
4422     return error(Context, "Explicit load/store type does not match pointee "
4423                           "type of pointer operand");
4424   if (!PointerType::isLoadableOrStorableType(ElemType))
4425     return error(Context, "Cannot load/store from pointer");
4426   return std::error_code();
4427 }
4428 
4429 /// Lazily parse the specified function body block.
4430 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
4431   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4432     return error("Invalid record");
4433 
4434   // Unexpected unresolved metadata when parsing function.
4435   if (MetadataList.hasFwdRefs())
4436     return error("Invalid function metadata: incoming forward references");
4437 
4438   InstructionList.clear();
4439   unsigned ModuleValueListSize = ValueList.size();
4440   unsigned ModuleMetadataListSize = MetadataList.size();
4441 
4442   // Add all the function arguments to the value table.
4443   for (Argument &I : F->args())
4444     ValueList.push_back(&I);
4445 
4446   unsigned NextValueNo = ValueList.size();
4447   BasicBlock *CurBB = nullptr;
4448   unsigned CurBBNo = 0;
4449 
4450   DebugLoc LastLoc;
4451   auto getLastInstruction = [&]() -> Instruction * {
4452     if (CurBB && !CurBB->empty())
4453       return &CurBB->back();
4454     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4455              !FunctionBBs[CurBBNo - 1]->empty())
4456       return &FunctionBBs[CurBBNo - 1]->back();
4457     return nullptr;
4458   };
4459 
4460   std::vector<OperandBundleDef> OperandBundles;
4461 
4462   // Read all the records.
4463   SmallVector<uint64_t, 64> Record;
4464 
4465   while (true) {
4466     BitstreamEntry Entry = Stream.advance();
4467 
4468     switch (Entry.Kind) {
4469     case BitstreamEntry::Error:
4470       return error("Malformed block");
4471     case BitstreamEntry::EndBlock:
4472       goto OutOfRecordLoop;
4473 
4474     case BitstreamEntry::SubBlock:
4475       switch (Entry.ID) {
4476       default:  // Skip unknown content.
4477         if (Stream.SkipBlock())
4478           return error("Invalid record");
4479         break;
4480       case bitc::CONSTANTS_BLOCK_ID:
4481         if (std::error_code EC = parseConstants())
4482           return EC;
4483         NextValueNo = ValueList.size();
4484         break;
4485       case bitc::VALUE_SYMTAB_BLOCK_ID:
4486         if (std::error_code EC = parseValueSymbolTable())
4487           return EC;
4488         break;
4489       case bitc::METADATA_ATTACHMENT_ID:
4490         if (std::error_code EC = parseMetadataAttachment(*F))
4491           return EC;
4492         break;
4493       case bitc::METADATA_BLOCK_ID:
4494         if (std::error_code EC = parseMetadata())
4495           return EC;
4496         break;
4497       case bitc::USELIST_BLOCK_ID:
4498         if (std::error_code EC = parseUseLists())
4499           return EC;
4500         break;
4501       }
4502       continue;
4503 
4504     case BitstreamEntry::Record:
4505       // The interesting case.
4506       break;
4507     }
4508 
4509     // Read a record.
4510     Record.clear();
4511     Instruction *I = nullptr;
4512     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4513     switch (BitCode) {
4514     default: // Default behavior: reject
4515       return error("Invalid value");
4516     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4517       if (Record.size() < 1 || Record[0] == 0)
4518         return error("Invalid record");
4519       // Create all the basic blocks for the function.
4520       FunctionBBs.resize(Record[0]);
4521 
4522       // See if anything took the address of blocks in this function.
4523       auto BBFRI = BasicBlockFwdRefs.find(F);
4524       if (BBFRI == BasicBlockFwdRefs.end()) {
4525         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4526           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4527       } else {
4528         auto &BBRefs = BBFRI->second;
4529         // Check for invalid basic block references.
4530         if (BBRefs.size() > FunctionBBs.size())
4531           return error("Invalid ID");
4532         assert(!BBRefs.empty() && "Unexpected empty array");
4533         assert(!BBRefs.front() && "Invalid reference to entry block");
4534         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4535              ++I)
4536           if (I < RE && BBRefs[I]) {
4537             BBRefs[I]->insertInto(F);
4538             FunctionBBs[I] = BBRefs[I];
4539           } else {
4540             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4541           }
4542 
4543         // Erase from the table.
4544         BasicBlockFwdRefs.erase(BBFRI);
4545       }
4546 
4547       CurBB = FunctionBBs[0];
4548       continue;
4549     }
4550 
4551     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4552       // This record indicates that the last instruction is at the same
4553       // location as the previous instruction with a location.
4554       I = getLastInstruction();
4555 
4556       if (!I)
4557         return error("Invalid record");
4558       I->setDebugLoc(LastLoc);
4559       I = nullptr;
4560       continue;
4561 
4562     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4563       I = getLastInstruction();
4564       if (!I || Record.size() < 4)
4565         return error("Invalid record");
4566 
4567       unsigned Line = Record[0], Col = Record[1];
4568       unsigned ScopeID = Record[2], IAID = Record[3];
4569 
4570       MDNode *Scope = nullptr, *IA = nullptr;
4571       if (ScopeID) {
4572         Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4573         if (!Scope)
4574           return error("Invalid record");
4575       }
4576       if (IAID) {
4577         IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4578         if (!IA)
4579           return error("Invalid record");
4580       }
4581       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4582       I->setDebugLoc(LastLoc);
4583       I = nullptr;
4584       continue;
4585     }
4586 
4587     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4588       unsigned OpNum = 0;
4589       Value *LHS, *RHS;
4590       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4591           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4592           OpNum+1 > Record.size())
4593         return error("Invalid record");
4594 
4595       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4596       if (Opc == -1)
4597         return error("Invalid record");
4598       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4599       InstructionList.push_back(I);
4600       if (OpNum < Record.size()) {
4601         if (Opc == Instruction::Add ||
4602             Opc == Instruction::Sub ||
4603             Opc == Instruction::Mul ||
4604             Opc == Instruction::Shl) {
4605           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4606             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4607           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4608             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4609         } else if (Opc == Instruction::SDiv ||
4610                    Opc == Instruction::UDiv ||
4611                    Opc == Instruction::LShr ||
4612                    Opc == Instruction::AShr) {
4613           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4614             cast<BinaryOperator>(I)->setIsExact(true);
4615         } else if (isa<FPMathOperator>(I)) {
4616           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4617           if (FMF.any())
4618             I->setFastMathFlags(FMF);
4619         }
4620 
4621       }
4622       break;
4623     }
4624     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4625       unsigned OpNum = 0;
4626       Value *Op;
4627       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4628           OpNum+2 != Record.size())
4629         return error("Invalid record");
4630 
4631       Type *ResTy = getTypeByID(Record[OpNum]);
4632       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4633       if (Opc == -1 || !ResTy)
4634         return error("Invalid record");
4635       Instruction *Temp = nullptr;
4636       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4637         if (Temp) {
4638           InstructionList.push_back(Temp);
4639           CurBB->getInstList().push_back(Temp);
4640         }
4641       } else {
4642         auto CastOp = (Instruction::CastOps)Opc;
4643         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4644           return error("Invalid cast");
4645         I = CastInst::Create(CastOp, Op, ResTy);
4646       }
4647       InstructionList.push_back(I);
4648       break;
4649     }
4650     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4651     case bitc::FUNC_CODE_INST_GEP_OLD:
4652     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4653       unsigned OpNum = 0;
4654 
4655       Type *Ty;
4656       bool InBounds;
4657 
4658       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4659         InBounds = Record[OpNum++];
4660         Ty = getTypeByID(Record[OpNum++]);
4661       } else {
4662         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4663         Ty = nullptr;
4664       }
4665 
4666       Value *BasePtr;
4667       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4668         return error("Invalid record");
4669 
4670       if (!Ty)
4671         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4672                  ->getElementType();
4673       else if (Ty !=
4674                cast<SequentialType>(BasePtr->getType()->getScalarType())
4675                    ->getElementType())
4676         return error(
4677             "Explicit gep type does not match pointee type of pointer operand");
4678 
4679       SmallVector<Value*, 16> GEPIdx;
4680       while (OpNum != Record.size()) {
4681         Value *Op;
4682         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4683           return error("Invalid record");
4684         GEPIdx.push_back(Op);
4685       }
4686 
4687       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4688 
4689       InstructionList.push_back(I);
4690       if (InBounds)
4691         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4692       break;
4693     }
4694 
4695     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4696                                        // EXTRACTVAL: [opty, opval, n x indices]
4697       unsigned OpNum = 0;
4698       Value *Agg;
4699       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4700         return error("Invalid record");
4701 
4702       unsigned RecSize = Record.size();
4703       if (OpNum == RecSize)
4704         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4705 
4706       SmallVector<unsigned, 4> EXTRACTVALIdx;
4707       Type *CurTy = Agg->getType();
4708       for (; OpNum != RecSize; ++OpNum) {
4709         bool IsArray = CurTy->isArrayTy();
4710         bool IsStruct = CurTy->isStructTy();
4711         uint64_t Index = Record[OpNum];
4712 
4713         if (!IsStruct && !IsArray)
4714           return error("EXTRACTVAL: Invalid type");
4715         if ((unsigned)Index != Index)
4716           return error("Invalid value");
4717         if (IsStruct && Index >= CurTy->subtypes().size())
4718           return error("EXTRACTVAL: Invalid struct index");
4719         if (IsArray && Index >= CurTy->getArrayNumElements())
4720           return error("EXTRACTVAL: Invalid array index");
4721         EXTRACTVALIdx.push_back((unsigned)Index);
4722 
4723         if (IsStruct)
4724           CurTy = CurTy->subtypes()[Index];
4725         else
4726           CurTy = CurTy->subtypes()[0];
4727       }
4728 
4729       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4730       InstructionList.push_back(I);
4731       break;
4732     }
4733 
4734     case bitc::FUNC_CODE_INST_INSERTVAL: {
4735                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4736       unsigned OpNum = 0;
4737       Value *Agg;
4738       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4739         return error("Invalid record");
4740       Value *Val;
4741       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4742         return error("Invalid record");
4743 
4744       unsigned RecSize = Record.size();
4745       if (OpNum == RecSize)
4746         return error("INSERTVAL: Invalid instruction with 0 indices");
4747 
4748       SmallVector<unsigned, 4> INSERTVALIdx;
4749       Type *CurTy = Agg->getType();
4750       for (; OpNum != RecSize; ++OpNum) {
4751         bool IsArray = CurTy->isArrayTy();
4752         bool IsStruct = CurTy->isStructTy();
4753         uint64_t Index = Record[OpNum];
4754 
4755         if (!IsStruct && !IsArray)
4756           return error("INSERTVAL: Invalid type");
4757         if ((unsigned)Index != Index)
4758           return error("Invalid value");
4759         if (IsStruct && Index >= CurTy->subtypes().size())
4760           return error("INSERTVAL: Invalid struct index");
4761         if (IsArray && Index >= CurTy->getArrayNumElements())
4762           return error("INSERTVAL: Invalid array index");
4763 
4764         INSERTVALIdx.push_back((unsigned)Index);
4765         if (IsStruct)
4766           CurTy = CurTy->subtypes()[Index];
4767         else
4768           CurTy = CurTy->subtypes()[0];
4769       }
4770 
4771       if (CurTy != Val->getType())
4772         return error("Inserted value type doesn't match aggregate type");
4773 
4774       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4775       InstructionList.push_back(I);
4776       break;
4777     }
4778 
4779     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4780       // obsolete form of select
4781       // handles select i1 ... in old bitcode
4782       unsigned OpNum = 0;
4783       Value *TrueVal, *FalseVal, *Cond;
4784       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4785           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4786           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4787         return error("Invalid record");
4788 
4789       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4790       InstructionList.push_back(I);
4791       break;
4792     }
4793 
4794     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4795       // new form of select
4796       // handles select i1 or select [N x i1]
4797       unsigned OpNum = 0;
4798       Value *TrueVal, *FalseVal, *Cond;
4799       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4800           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4801           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4802         return error("Invalid record");
4803 
4804       // select condition can be either i1 or [N x i1]
4805       if (VectorType* vector_type =
4806           dyn_cast<VectorType>(Cond->getType())) {
4807         // expect <n x i1>
4808         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4809           return error("Invalid type for value");
4810       } else {
4811         // expect i1
4812         if (Cond->getType() != Type::getInt1Ty(Context))
4813           return error("Invalid type for value");
4814       }
4815 
4816       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4817       InstructionList.push_back(I);
4818       break;
4819     }
4820 
4821     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4822       unsigned OpNum = 0;
4823       Value *Vec, *Idx;
4824       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4825           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4826         return error("Invalid record");
4827       if (!Vec->getType()->isVectorTy())
4828         return error("Invalid type for value");
4829       I = ExtractElementInst::Create(Vec, Idx);
4830       InstructionList.push_back(I);
4831       break;
4832     }
4833 
4834     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4835       unsigned OpNum = 0;
4836       Value *Vec, *Elt, *Idx;
4837       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4838         return error("Invalid record");
4839       if (!Vec->getType()->isVectorTy())
4840         return error("Invalid type for value");
4841       if (popValue(Record, OpNum, NextValueNo,
4842                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4843           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4844         return error("Invalid record");
4845       I = InsertElementInst::Create(Vec, Elt, Idx);
4846       InstructionList.push_back(I);
4847       break;
4848     }
4849 
4850     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4851       unsigned OpNum = 0;
4852       Value *Vec1, *Vec2, *Mask;
4853       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4854           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4855         return error("Invalid record");
4856 
4857       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4858         return error("Invalid record");
4859       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4860         return error("Invalid type for value");
4861       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4862       InstructionList.push_back(I);
4863       break;
4864     }
4865 
4866     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4867       // Old form of ICmp/FCmp returning bool
4868       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4869       // both legal on vectors but had different behaviour.
4870     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4871       // FCmp/ICmp returning bool or vector of bool
4872 
4873       unsigned OpNum = 0;
4874       Value *LHS, *RHS;
4875       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4876           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4877         return error("Invalid record");
4878 
4879       unsigned PredVal = Record[OpNum];
4880       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4881       FastMathFlags FMF;
4882       if (IsFP && Record.size() > OpNum+1)
4883         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4884 
4885       if (OpNum+1 != Record.size())
4886         return error("Invalid record");
4887 
4888       if (LHS->getType()->isFPOrFPVectorTy())
4889         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4890       else
4891         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4892 
4893       if (FMF.any())
4894         I->setFastMathFlags(FMF);
4895       InstructionList.push_back(I);
4896       break;
4897     }
4898 
4899     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4900       {
4901         unsigned Size = Record.size();
4902         if (Size == 0) {
4903           I = ReturnInst::Create(Context);
4904           InstructionList.push_back(I);
4905           break;
4906         }
4907 
4908         unsigned OpNum = 0;
4909         Value *Op = nullptr;
4910         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4911           return error("Invalid record");
4912         if (OpNum != Record.size())
4913           return error("Invalid record");
4914 
4915         I = ReturnInst::Create(Context, Op);
4916         InstructionList.push_back(I);
4917         break;
4918       }
4919     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4920       if (Record.size() != 1 && Record.size() != 3)
4921         return error("Invalid record");
4922       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4923       if (!TrueDest)
4924         return error("Invalid record");
4925 
4926       if (Record.size() == 1) {
4927         I = BranchInst::Create(TrueDest);
4928         InstructionList.push_back(I);
4929       }
4930       else {
4931         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4932         Value *Cond = getValue(Record, 2, NextValueNo,
4933                                Type::getInt1Ty(Context));
4934         if (!FalseDest || !Cond)
4935           return error("Invalid record");
4936         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4937         InstructionList.push_back(I);
4938       }
4939       break;
4940     }
4941     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4942       if (Record.size() != 1 && Record.size() != 2)
4943         return error("Invalid record");
4944       unsigned Idx = 0;
4945       Value *CleanupPad =
4946           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4947       if (!CleanupPad)
4948         return error("Invalid record");
4949       BasicBlock *UnwindDest = nullptr;
4950       if (Record.size() == 2) {
4951         UnwindDest = getBasicBlock(Record[Idx++]);
4952         if (!UnwindDest)
4953           return error("Invalid record");
4954       }
4955 
4956       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4957       InstructionList.push_back(I);
4958       break;
4959     }
4960     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4961       if (Record.size() != 2)
4962         return error("Invalid record");
4963       unsigned Idx = 0;
4964       Value *CatchPad =
4965           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4966       if (!CatchPad)
4967         return error("Invalid record");
4968       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4969       if (!BB)
4970         return error("Invalid record");
4971 
4972       I = CatchReturnInst::Create(CatchPad, BB);
4973       InstructionList.push_back(I);
4974       break;
4975     }
4976     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4977       // We must have, at minimum, the outer scope and the number of arguments.
4978       if (Record.size() < 2)
4979         return error("Invalid record");
4980 
4981       unsigned Idx = 0;
4982 
4983       Value *ParentPad =
4984           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4985 
4986       unsigned NumHandlers = Record[Idx++];
4987 
4988       SmallVector<BasicBlock *, 2> Handlers;
4989       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4990         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4991         if (!BB)
4992           return error("Invalid record");
4993         Handlers.push_back(BB);
4994       }
4995 
4996       BasicBlock *UnwindDest = nullptr;
4997       if (Idx + 1 == Record.size()) {
4998         UnwindDest = getBasicBlock(Record[Idx++]);
4999         if (!UnwindDest)
5000           return error("Invalid record");
5001       }
5002 
5003       if (Record.size() != Idx)
5004         return error("Invalid record");
5005 
5006       auto *CatchSwitch =
5007           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5008       for (BasicBlock *Handler : Handlers)
5009         CatchSwitch->addHandler(Handler);
5010       I = CatchSwitch;
5011       InstructionList.push_back(I);
5012       break;
5013     }
5014     case bitc::FUNC_CODE_INST_CATCHPAD:
5015     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5016       // We must have, at minimum, the outer scope and the number of arguments.
5017       if (Record.size() < 2)
5018         return error("Invalid record");
5019 
5020       unsigned Idx = 0;
5021 
5022       Value *ParentPad =
5023           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
5024 
5025       unsigned NumArgOperands = Record[Idx++];
5026 
5027       SmallVector<Value *, 2> Args;
5028       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5029         Value *Val;
5030         if (getValueTypePair(Record, Idx, NextValueNo, Val))
5031           return error("Invalid record");
5032         Args.push_back(Val);
5033       }
5034 
5035       if (Record.size() != Idx)
5036         return error("Invalid record");
5037 
5038       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5039         I = CleanupPadInst::Create(ParentPad, Args);
5040       else
5041         I = CatchPadInst::Create(ParentPad, Args);
5042       InstructionList.push_back(I);
5043       break;
5044     }
5045     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5046       // Check magic
5047       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5048         // "New" SwitchInst format with case ranges. The changes to write this
5049         // format were reverted but we still recognize bitcode that uses it.
5050         // Hopefully someday we will have support for case ranges and can use
5051         // this format again.
5052 
5053         Type *OpTy = getTypeByID(Record[1]);
5054         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5055 
5056         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
5057         BasicBlock *Default = getBasicBlock(Record[3]);
5058         if (!OpTy || !Cond || !Default)
5059           return error("Invalid record");
5060 
5061         unsigned NumCases = Record[4];
5062 
5063         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5064         InstructionList.push_back(SI);
5065 
5066         unsigned CurIdx = 5;
5067         for (unsigned i = 0; i != NumCases; ++i) {
5068           SmallVector<ConstantInt*, 1> CaseVals;
5069           unsigned NumItems = Record[CurIdx++];
5070           for (unsigned ci = 0; ci != NumItems; ++ci) {
5071             bool isSingleNumber = Record[CurIdx++];
5072 
5073             APInt Low;
5074             unsigned ActiveWords = 1;
5075             if (ValueBitWidth > 64)
5076               ActiveWords = Record[CurIdx++];
5077             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
5078                                 ValueBitWidth);
5079             CurIdx += ActiveWords;
5080 
5081             if (!isSingleNumber) {
5082               ActiveWords = 1;
5083               if (ValueBitWidth > 64)
5084                 ActiveWords = Record[CurIdx++];
5085               APInt High = readWideAPInt(
5086                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
5087               CurIdx += ActiveWords;
5088 
5089               // FIXME: It is not clear whether values in the range should be
5090               // compared as signed or unsigned values. The partially
5091               // implemented changes that used this format in the past used
5092               // unsigned comparisons.
5093               for ( ; Low.ule(High); ++Low)
5094                 CaseVals.push_back(ConstantInt::get(Context, Low));
5095             } else
5096               CaseVals.push_back(ConstantInt::get(Context, Low));
5097           }
5098           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5099           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
5100                  cve = CaseVals.end(); cvi != cve; ++cvi)
5101             SI->addCase(*cvi, DestBB);
5102         }
5103         I = SI;
5104         break;
5105       }
5106 
5107       // Old SwitchInst format without case ranges.
5108 
5109       if (Record.size() < 3 || (Record.size() & 1) == 0)
5110         return error("Invalid record");
5111       Type *OpTy = getTypeByID(Record[0]);
5112       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
5113       BasicBlock *Default = getBasicBlock(Record[2]);
5114       if (!OpTy || !Cond || !Default)
5115         return error("Invalid record");
5116       unsigned NumCases = (Record.size()-3)/2;
5117       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5118       InstructionList.push_back(SI);
5119       for (unsigned i = 0, e = NumCases; i != e; ++i) {
5120         ConstantInt *CaseVal =
5121           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
5122         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5123         if (!CaseVal || !DestBB) {
5124           delete SI;
5125           return error("Invalid record");
5126         }
5127         SI->addCase(CaseVal, DestBB);
5128       }
5129       I = SI;
5130       break;
5131     }
5132     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5133       if (Record.size() < 2)
5134         return error("Invalid record");
5135       Type *OpTy = getTypeByID(Record[0]);
5136       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
5137       if (!OpTy || !Address)
5138         return error("Invalid record");
5139       unsigned NumDests = Record.size()-2;
5140       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5141       InstructionList.push_back(IBI);
5142       for (unsigned i = 0, e = NumDests; i != e; ++i) {
5143         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5144           IBI->addDestination(DestBB);
5145         } else {
5146           delete IBI;
5147           return error("Invalid record");
5148         }
5149       }
5150       I = IBI;
5151       break;
5152     }
5153 
5154     case bitc::FUNC_CODE_INST_INVOKE: {
5155       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5156       if (Record.size() < 4)
5157         return error("Invalid record");
5158       unsigned OpNum = 0;
5159       AttributeSet PAL = getAttributes(Record[OpNum++]);
5160       unsigned CCInfo = Record[OpNum++];
5161       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5162       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5163 
5164       FunctionType *FTy = nullptr;
5165       if (CCInfo >> 13 & 1 &&
5166           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5167         return error("Explicit invoke type is not a function type");
5168 
5169       Value *Callee;
5170       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5171         return error("Invalid record");
5172 
5173       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5174       if (!CalleeTy)
5175         return error("Callee is not a pointer");
5176       if (!FTy) {
5177         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5178         if (!FTy)
5179           return error("Callee is not of pointer to function type");
5180       } else if (CalleeTy->getElementType() != FTy)
5181         return error("Explicit invoke type does not match pointee type of "
5182                      "callee operand");
5183       if (Record.size() < FTy->getNumParams() + OpNum)
5184         return error("Insufficient operands to call");
5185 
5186       SmallVector<Value*, 16> Ops;
5187       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5188         Ops.push_back(getValue(Record, OpNum, NextValueNo,
5189                                FTy->getParamType(i)));
5190         if (!Ops.back())
5191           return error("Invalid record");
5192       }
5193 
5194       if (!FTy->isVarArg()) {
5195         if (Record.size() != OpNum)
5196           return error("Invalid record");
5197       } else {
5198         // Read type/value pairs for varargs params.
5199         while (OpNum != Record.size()) {
5200           Value *Op;
5201           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5202             return error("Invalid record");
5203           Ops.push_back(Op);
5204         }
5205       }
5206 
5207       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5208       OperandBundles.clear();
5209       InstructionList.push_back(I);
5210       cast<InvokeInst>(I)->setCallingConv(
5211           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5212       cast<InvokeInst>(I)->setAttributes(PAL);
5213       break;
5214     }
5215     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5216       unsigned Idx = 0;
5217       Value *Val = nullptr;
5218       if (getValueTypePair(Record, Idx, NextValueNo, Val))
5219         return error("Invalid record");
5220       I = ResumeInst::Create(Val);
5221       InstructionList.push_back(I);
5222       break;
5223     }
5224     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5225       I = new UnreachableInst(Context);
5226       InstructionList.push_back(I);
5227       break;
5228     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5229       if (Record.size() < 1 || ((Record.size()-1)&1))
5230         return error("Invalid record");
5231       Type *Ty = getTypeByID(Record[0]);
5232       if (!Ty)
5233         return error("Invalid record");
5234 
5235       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
5236       InstructionList.push_back(PN);
5237 
5238       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
5239         Value *V;
5240         // With the new function encoding, it is possible that operands have
5241         // negative IDs (for forward references).  Use a signed VBR
5242         // representation to keep the encoding small.
5243         if (UseRelativeIDs)
5244           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5245         else
5246           V = getValue(Record, 1+i, NextValueNo, Ty);
5247         BasicBlock *BB = getBasicBlock(Record[2+i]);
5248         if (!V || !BB)
5249           return error("Invalid record");
5250         PN->addIncoming(V, BB);
5251       }
5252       I = PN;
5253       break;
5254     }
5255 
5256     case bitc::FUNC_CODE_INST_LANDINGPAD:
5257     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5258       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5259       unsigned Idx = 0;
5260       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5261         if (Record.size() < 3)
5262           return error("Invalid record");
5263       } else {
5264         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5265         if (Record.size() < 4)
5266           return error("Invalid record");
5267       }
5268       Type *Ty = getTypeByID(Record[Idx++]);
5269       if (!Ty)
5270         return error("Invalid record");
5271       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5272         Value *PersFn = nullptr;
5273         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5274           return error("Invalid record");
5275 
5276         if (!F->hasPersonalityFn())
5277           F->setPersonalityFn(cast<Constant>(PersFn));
5278         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5279           return error("Personality function mismatch");
5280       }
5281 
5282       bool IsCleanup = !!Record[Idx++];
5283       unsigned NumClauses = Record[Idx++];
5284       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5285       LP->setCleanup(IsCleanup);
5286       for (unsigned J = 0; J != NumClauses; ++J) {
5287         LandingPadInst::ClauseType CT =
5288           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5289         Value *Val;
5290 
5291         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5292           delete LP;
5293           return error("Invalid record");
5294         }
5295 
5296         assert((CT != LandingPadInst::Catch ||
5297                 !isa<ArrayType>(Val->getType())) &&
5298                "Catch clause has a invalid type!");
5299         assert((CT != LandingPadInst::Filter ||
5300                 isa<ArrayType>(Val->getType())) &&
5301                "Filter clause has invalid type!");
5302         LP->addClause(cast<Constant>(Val));
5303       }
5304 
5305       I = LP;
5306       InstructionList.push_back(I);
5307       break;
5308     }
5309 
5310     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5311       if (Record.size() != 4)
5312         return error("Invalid record");
5313       uint64_t AlignRecord = Record[3];
5314       const uint64_t InAllocaMask = uint64_t(1) << 5;
5315       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
5316       const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5317       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5318                                 SwiftErrorMask;
5319       bool InAlloca = AlignRecord & InAllocaMask;
5320       bool SwiftError = AlignRecord & SwiftErrorMask;
5321       Type *Ty = getTypeByID(Record[0]);
5322       if ((AlignRecord & ExplicitTypeMask) == 0) {
5323         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5324         if (!PTy)
5325           return error("Old-style alloca with a non-pointer type");
5326         Ty = PTy->getElementType();
5327       }
5328       Type *OpTy = getTypeByID(Record[1]);
5329       Value *Size = getFnValueByID(Record[2], OpTy);
5330       unsigned Align;
5331       if (std::error_code EC =
5332               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
5333         return EC;
5334       }
5335       if (!Ty || !Size)
5336         return error("Invalid record");
5337       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
5338       AI->setUsedWithInAlloca(InAlloca);
5339       AI->setSwiftError(SwiftError);
5340       I = AI;
5341       InstructionList.push_back(I);
5342       break;
5343     }
5344     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5345       unsigned OpNum = 0;
5346       Value *Op;
5347       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5348           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5349         return error("Invalid record");
5350 
5351       Type *Ty = nullptr;
5352       if (OpNum + 3 == Record.size())
5353         Ty = getTypeByID(Record[OpNum++]);
5354       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5355         return EC;
5356       if (!Ty)
5357         Ty = cast<PointerType>(Op->getType())->getElementType();
5358 
5359       unsigned Align;
5360       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5361         return EC;
5362       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
5363 
5364       InstructionList.push_back(I);
5365       break;
5366     }
5367     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5368        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5369       unsigned OpNum = 0;
5370       Value *Op;
5371       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5372           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5373         return error("Invalid record");
5374 
5375       Type *Ty = nullptr;
5376       if (OpNum + 5 == Record.size())
5377         Ty = getTypeByID(Record[OpNum++]);
5378       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5379         return EC;
5380       if (!Ty)
5381         Ty = cast<PointerType>(Op->getType())->getElementType();
5382 
5383       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5384       if (Ordering == AtomicOrdering::NotAtomic ||
5385           Ordering == AtomicOrdering::Release ||
5386           Ordering == AtomicOrdering::AcquireRelease)
5387         return error("Invalid record");
5388       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5389         return error("Invalid record");
5390       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5391 
5392       unsigned Align;
5393       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5394         return EC;
5395       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
5396 
5397       InstructionList.push_back(I);
5398       break;
5399     }
5400     case bitc::FUNC_CODE_INST_STORE:
5401     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5402       unsigned OpNum = 0;
5403       Value *Val, *Ptr;
5404       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5405           (BitCode == bitc::FUNC_CODE_INST_STORE
5406                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5407                : popValue(Record, OpNum, NextValueNo,
5408                           cast<PointerType>(Ptr->getType())->getElementType(),
5409                           Val)) ||
5410           OpNum + 2 != Record.size())
5411         return error("Invalid record");
5412 
5413       if (std::error_code EC =
5414               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5415         return EC;
5416       unsigned Align;
5417       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5418         return EC;
5419       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
5420       InstructionList.push_back(I);
5421       break;
5422     }
5423     case bitc::FUNC_CODE_INST_STOREATOMIC:
5424     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5425       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5426       unsigned OpNum = 0;
5427       Value *Val, *Ptr;
5428       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5429           !isa<PointerType>(Ptr->getType()) ||
5430           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5431                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5432                : popValue(Record, OpNum, NextValueNo,
5433                           cast<PointerType>(Ptr->getType())->getElementType(),
5434                           Val)) ||
5435           OpNum + 4 != Record.size())
5436         return error("Invalid record");
5437 
5438       if (std::error_code EC =
5439               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5440         return EC;
5441       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5442       if (Ordering == AtomicOrdering::NotAtomic ||
5443           Ordering == AtomicOrdering::Acquire ||
5444           Ordering == AtomicOrdering::AcquireRelease)
5445         return error("Invalid record");
5446       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5447       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5448         return error("Invalid record");
5449 
5450       unsigned Align;
5451       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5452         return EC;
5453       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
5454       InstructionList.push_back(I);
5455       break;
5456     }
5457     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
5458     case bitc::FUNC_CODE_INST_CMPXCHG: {
5459       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
5460       //          failureordering?, isweak?]
5461       unsigned OpNum = 0;
5462       Value *Ptr, *Cmp, *New;
5463       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5464           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5465                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5466                : popValue(Record, OpNum, NextValueNo,
5467                           cast<PointerType>(Ptr->getType())->getElementType(),
5468                           Cmp)) ||
5469           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5470           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
5471         return error("Invalid record");
5472       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
5473       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5474           SuccessOrdering == AtomicOrdering::Unordered)
5475         return error("Invalid record");
5476       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
5477 
5478       if (std::error_code EC =
5479               typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5480         return EC;
5481       AtomicOrdering FailureOrdering;
5482       if (Record.size() < 7)
5483         FailureOrdering =
5484             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5485       else
5486         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
5487 
5488       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5489                                 SynchScope);
5490       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5491 
5492       if (Record.size() < 8) {
5493         // Before weak cmpxchgs existed, the instruction simply returned the
5494         // value loaded from memory, so bitcode files from that era will be
5495         // expecting the first component of a modern cmpxchg.
5496         CurBB->getInstList().push_back(I);
5497         I = ExtractValueInst::Create(I, 0);
5498       } else {
5499         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5500       }
5501 
5502       InstructionList.push_back(I);
5503       break;
5504     }
5505     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5506       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5507       unsigned OpNum = 0;
5508       Value *Ptr, *Val;
5509       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5510           !isa<PointerType>(Ptr->getType()) ||
5511           popValue(Record, OpNum, NextValueNo,
5512                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5513           OpNum+4 != Record.size())
5514         return error("Invalid record");
5515       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5516       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5517           Operation > AtomicRMWInst::LAST_BINOP)
5518         return error("Invalid record");
5519       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5520       if (Ordering == AtomicOrdering::NotAtomic ||
5521           Ordering == AtomicOrdering::Unordered)
5522         return error("Invalid record");
5523       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5524       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5525       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5526       InstructionList.push_back(I);
5527       break;
5528     }
5529     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5530       if (2 != Record.size())
5531         return error("Invalid record");
5532       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5533       if (Ordering == AtomicOrdering::NotAtomic ||
5534           Ordering == AtomicOrdering::Unordered ||
5535           Ordering == AtomicOrdering::Monotonic)
5536         return error("Invalid record");
5537       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5538       I = new FenceInst(Context, Ordering, SynchScope);
5539       InstructionList.push_back(I);
5540       break;
5541     }
5542     case bitc::FUNC_CODE_INST_CALL: {
5543       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5544       if (Record.size() < 3)
5545         return error("Invalid record");
5546 
5547       unsigned OpNum = 0;
5548       AttributeSet PAL = getAttributes(Record[OpNum++]);
5549       unsigned CCInfo = Record[OpNum++];
5550 
5551       FastMathFlags FMF;
5552       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5553         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5554         if (!FMF.any())
5555           return error("Fast math flags indicator set for call with no FMF");
5556       }
5557 
5558       FunctionType *FTy = nullptr;
5559       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5560           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5561         return error("Explicit call type is not a function type");
5562 
5563       Value *Callee;
5564       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5565         return error("Invalid record");
5566 
5567       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5568       if (!OpTy)
5569         return error("Callee is not a pointer type");
5570       if (!FTy) {
5571         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5572         if (!FTy)
5573           return error("Callee is not of pointer to function type");
5574       } else if (OpTy->getElementType() != FTy)
5575         return error("Explicit call type does not match pointee type of "
5576                      "callee operand");
5577       if (Record.size() < FTy->getNumParams() + OpNum)
5578         return error("Insufficient operands to call");
5579 
5580       SmallVector<Value*, 16> Args;
5581       // Read the fixed params.
5582       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5583         if (FTy->getParamType(i)->isLabelTy())
5584           Args.push_back(getBasicBlock(Record[OpNum]));
5585         else
5586           Args.push_back(getValue(Record, OpNum, NextValueNo,
5587                                   FTy->getParamType(i)));
5588         if (!Args.back())
5589           return error("Invalid record");
5590       }
5591 
5592       // Read type/value pairs for varargs params.
5593       if (!FTy->isVarArg()) {
5594         if (OpNum != Record.size())
5595           return error("Invalid record");
5596       } else {
5597         while (OpNum != Record.size()) {
5598           Value *Op;
5599           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5600             return error("Invalid record");
5601           Args.push_back(Op);
5602         }
5603       }
5604 
5605       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5606       OperandBundles.clear();
5607       InstructionList.push_back(I);
5608       cast<CallInst>(I)->setCallingConv(
5609           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5610       CallInst::TailCallKind TCK = CallInst::TCK_None;
5611       if (CCInfo & 1 << bitc::CALL_TAIL)
5612         TCK = CallInst::TCK_Tail;
5613       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5614         TCK = CallInst::TCK_MustTail;
5615       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5616         TCK = CallInst::TCK_NoTail;
5617       cast<CallInst>(I)->setTailCallKind(TCK);
5618       cast<CallInst>(I)->setAttributes(PAL);
5619       if (FMF.any()) {
5620         if (!isa<FPMathOperator>(I))
5621           return error("Fast-math-flags specified for call without "
5622                        "floating-point scalar or vector return type");
5623         I->setFastMathFlags(FMF);
5624       }
5625       break;
5626     }
5627     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5628       if (Record.size() < 3)
5629         return error("Invalid record");
5630       Type *OpTy = getTypeByID(Record[0]);
5631       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5632       Type *ResTy = getTypeByID(Record[2]);
5633       if (!OpTy || !Op || !ResTy)
5634         return error("Invalid record");
5635       I = new VAArgInst(Op, ResTy);
5636       InstructionList.push_back(I);
5637       break;
5638     }
5639 
5640     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5641       // A call or an invoke can be optionally prefixed with some variable
5642       // number of operand bundle blocks.  These blocks are read into
5643       // OperandBundles and consumed at the next call or invoke instruction.
5644 
5645       if (Record.size() < 1 || Record[0] >= BundleTags.size())
5646         return error("Invalid record");
5647 
5648       std::vector<Value *> Inputs;
5649 
5650       unsigned OpNum = 1;
5651       while (OpNum != Record.size()) {
5652         Value *Op;
5653         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5654           return error("Invalid record");
5655         Inputs.push_back(Op);
5656       }
5657 
5658       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5659       continue;
5660     }
5661     }
5662 
5663     // Add instruction to end of current BB.  If there is no current BB, reject
5664     // this file.
5665     if (!CurBB) {
5666       delete I;
5667       return error("Invalid instruction with no BB");
5668     }
5669     if (!OperandBundles.empty()) {
5670       delete I;
5671       return error("Operand bundles found with no consumer");
5672     }
5673     CurBB->getInstList().push_back(I);
5674 
5675     // If this was a terminator instruction, move to the next block.
5676     if (isa<TerminatorInst>(I)) {
5677       ++CurBBNo;
5678       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5679     }
5680 
5681     // Non-void values get registered in the value table for future use.
5682     if (I && !I->getType()->isVoidTy())
5683       ValueList.assignValue(I, NextValueNo++);
5684   }
5685 
5686 OutOfRecordLoop:
5687 
5688   if (!OperandBundles.empty())
5689     return error("Operand bundles found with no consumer");
5690 
5691   // Check the function list for unresolved values.
5692   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5693     if (!A->getParent()) {
5694       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5695       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5696         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5697           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5698           delete A;
5699         }
5700       }
5701       return error("Never resolved value found in function");
5702     }
5703   }
5704 
5705   // Unexpected unresolved metadata about to be dropped.
5706   if (MetadataList.hasFwdRefs())
5707     return error("Invalid function metadata: outgoing forward refs");
5708 
5709   // Trim the value list down to the size it was before we parsed this function.
5710   ValueList.shrinkTo(ModuleValueListSize);
5711   MetadataList.shrinkTo(ModuleMetadataListSize);
5712   std::vector<BasicBlock*>().swap(FunctionBBs);
5713   return std::error_code();
5714 }
5715 
5716 /// Find the function body in the bitcode stream
5717 std::error_code BitcodeReader::findFunctionInStream(
5718     Function *F,
5719     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5720   while (DeferredFunctionInfoIterator->second == 0) {
5721     // This is the fallback handling for the old format bitcode that
5722     // didn't contain the function index in the VST, or when we have
5723     // an anonymous function which would not have a VST entry.
5724     // Assert that we have one of those two cases.
5725     assert(VSTOffset == 0 || !F->hasName());
5726     // Parse the next body in the stream and set its position in the
5727     // DeferredFunctionInfo map.
5728     if (std::error_code EC = rememberAndSkipFunctionBodies())
5729       return EC;
5730   }
5731   return std::error_code();
5732 }
5733 
5734 //===----------------------------------------------------------------------===//
5735 // GVMaterializer implementation
5736 //===----------------------------------------------------------------------===//
5737 
5738 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5739 
5740 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5741   Function *F = dyn_cast<Function>(GV);
5742   // If it's not a function or is already material, ignore the request.
5743   if (!F || !F->isMaterializable())
5744     return std::error_code();
5745 
5746   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5747   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5748   // If its position is recorded as 0, its body is somewhere in the stream
5749   // but we haven't seen it yet.
5750   if (DFII->second == 0)
5751     if (std::error_code EC = findFunctionInStream(F, DFII))
5752       return EC;
5753 
5754   // Materialize metadata before parsing any function bodies.
5755   if (std::error_code EC = materializeMetadata())
5756     return EC;
5757 
5758   // Move the bit stream to the saved position of the deferred function body.
5759   Stream.JumpToBit(DFII->second);
5760 
5761   if (std::error_code EC = parseFunctionBody(F))
5762     return EC;
5763   F->setIsMaterializable(false);
5764 
5765   if (StripDebugInfo)
5766     stripDebugInfo(*F);
5767 
5768   // Upgrade any old intrinsic calls in the function.
5769   for (auto &I : UpgradedIntrinsics) {
5770     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5771          UI != UE;) {
5772       User *U = *UI;
5773       ++UI;
5774       if (CallInst *CI = dyn_cast<CallInst>(U))
5775         UpgradeIntrinsicCall(CI, I.second);
5776     }
5777   }
5778 
5779   // Update calls to the remangled intrinsics
5780   for (auto &I : RemangledIntrinsics)
5781     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5782          UI != UE;)
5783       // Don't expect any other users than call sites
5784       CallSite(*UI++).setCalledFunction(I.second);
5785 
5786   // Finish fn->subprogram upgrade for materialized functions.
5787   if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5788     F->setSubprogram(SP);
5789 
5790   // Bring in any functions that this function forward-referenced via
5791   // blockaddresses.
5792   return materializeForwardReferencedFunctions();
5793 }
5794 
5795 std::error_code BitcodeReader::materializeModule() {
5796   if (std::error_code EC = materializeMetadata())
5797     return EC;
5798 
5799   // Promise to materialize all forward references.
5800   WillMaterializeAllForwardRefs = true;
5801 
5802   // Iterate over the module, deserializing any functions that are still on
5803   // disk.
5804   for (Function &F : *TheModule) {
5805     if (std::error_code EC = materialize(&F))
5806       return EC;
5807   }
5808   // At this point, if there are any function bodies, parse the rest of
5809   // the bits in the module past the last function block we have recorded
5810   // through either lazy scanning or the VST.
5811   if (LastFunctionBlockBit || NextUnreadBit)
5812     parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5813                                                      : NextUnreadBit);
5814 
5815   // Check that all block address forward references got resolved (as we
5816   // promised above).
5817   if (!BasicBlockFwdRefs.empty())
5818     return error("Never resolved function from blockaddress");
5819 
5820   // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5821   // to prevent this instructions with TBAA tags should be upgraded first.
5822   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5823     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5824 
5825   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5826   // delete the old functions to clean up. We can't do this unless the entire
5827   // module is materialized because there could always be another function body
5828   // with calls to the old function.
5829   for (auto &I : UpgradedIntrinsics) {
5830     for (auto *U : I.first->users()) {
5831       if (CallInst *CI = dyn_cast<CallInst>(U))
5832         UpgradeIntrinsicCall(CI, I.second);
5833     }
5834     if (!I.first->use_empty())
5835       I.first->replaceAllUsesWith(I.second);
5836     I.first->eraseFromParent();
5837   }
5838   UpgradedIntrinsics.clear();
5839   // Do the same for remangled intrinsics
5840   for (auto &I : RemangledIntrinsics) {
5841     I.first->replaceAllUsesWith(I.second);
5842     I.first->eraseFromParent();
5843   }
5844   RemangledIntrinsics.clear();
5845 
5846   UpgradeDebugInfo(*TheModule);
5847 
5848   UpgradeModuleFlags(*TheModule);
5849   return std::error_code();
5850 }
5851 
5852 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5853   return IdentifiedStructTypes;
5854 }
5855 
5856 std::error_code
5857 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5858   if (Streamer)
5859     return initLazyStream(std::move(Streamer));
5860   return initStreamFromBuffer();
5861 }
5862 
5863 std::error_code BitcodeReader::initStreamFromBuffer() {
5864   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5865   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5866 
5867   if (Buffer->getBufferSize() & 3)
5868     return error("Invalid bitcode signature");
5869 
5870   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5871   // The magic number is 0x0B17C0DE stored in little endian.
5872   if (isBitcodeWrapper(BufPtr, BufEnd))
5873     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5874       return error("Invalid bitcode wrapper header");
5875 
5876   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5877   Stream.init(&*StreamFile);
5878 
5879   return std::error_code();
5880 }
5881 
5882 std::error_code
5883 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5884   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5885   // see it.
5886   auto OwnedBytes =
5887       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5888   StreamingMemoryObject &Bytes = *OwnedBytes;
5889   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5890   Stream.init(&*StreamFile);
5891 
5892   unsigned char buf[16];
5893   if (Bytes.readBytes(buf, 16, 0) != 16)
5894     return error("Invalid bitcode signature");
5895 
5896   if (!isBitcode(buf, buf + 16))
5897     return error("Invalid bitcode signature");
5898 
5899   if (isBitcodeWrapper(buf, buf + 4)) {
5900     const unsigned char *bitcodeStart = buf;
5901     const unsigned char *bitcodeEnd = buf + 16;
5902     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5903     Bytes.dropLeadingBytes(bitcodeStart - buf);
5904     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5905   }
5906   return std::error_code();
5907 }
5908 
5909 std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
5910   return ::error(DiagnosticHandler,
5911                  make_error_code(BitcodeError::CorruptedBitcode), Message);
5912 }
5913 
5914 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5915     MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5916     bool CheckGlobalValSummaryPresenceOnly)
5917     : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(Buffer),
5918       CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
5919 
5920 void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
5921 
5922 void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5923 
5924 std::pair<GlobalValue::GUID, GlobalValue::GUID>
5925 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
5926   auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5927   assert(VGI != ValueIdToCallGraphGUIDMap.end());
5928   return VGI->second;
5929 }
5930 
5931 // Specialized value symbol table parser used when reading module index
5932 // blocks where we don't actually create global values. The parsed information
5933 // is saved in the bitcode reader for use when later parsing summaries.
5934 std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5935     uint64_t Offset,
5936     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5937   assert(Offset > 0 && "Expected non-zero VST offset");
5938   uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5939 
5940   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5941     return error("Invalid record");
5942 
5943   SmallVector<uint64_t, 64> Record;
5944 
5945   // Read all the records for this value table.
5946   SmallString<128> ValueName;
5947 
5948   while (true) {
5949     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5950 
5951     switch (Entry.Kind) {
5952     case BitstreamEntry::SubBlock: // Handled for us already.
5953     case BitstreamEntry::Error:
5954       return error("Malformed block");
5955     case BitstreamEntry::EndBlock:
5956       // Done parsing VST, jump back to wherever we came from.
5957       Stream.JumpToBit(CurrentBit);
5958       return std::error_code();
5959     case BitstreamEntry::Record:
5960       // The interesting case.
5961       break;
5962     }
5963 
5964     // Read a record.
5965     Record.clear();
5966     switch (Stream.readRecord(Entry.ID, Record)) {
5967     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5968       break;
5969     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5970       if (convertToString(Record, 1, ValueName))
5971         return error("Invalid record");
5972       unsigned ValueID = Record[0];
5973       assert(!SourceFileName.empty());
5974       auto VLI = ValueIdToLinkageMap.find(ValueID);
5975       assert(VLI != ValueIdToLinkageMap.end() &&
5976              "No linkage found for VST entry?");
5977       auto Linkage = VLI->second;
5978       std::string GlobalId =
5979           GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5980       auto ValueGUID = GlobalValue::getGUID(GlobalId);
5981       auto OriginalNameID = ValueGUID;
5982       if (GlobalValue::isLocalLinkage(Linkage))
5983         OriginalNameID = GlobalValue::getGUID(ValueName);
5984       if (PrintSummaryGUIDs)
5985         dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5986                << ValueName << "\n";
5987       ValueIdToCallGraphGUIDMap[ValueID] =
5988           std::make_pair(ValueGUID, OriginalNameID);
5989       ValueName.clear();
5990       break;
5991     }
5992     case bitc::VST_CODE_FNENTRY: {
5993       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5994       if (convertToString(Record, 2, ValueName))
5995         return error("Invalid record");
5996       unsigned ValueID = Record[0];
5997       assert(!SourceFileName.empty());
5998       auto VLI = ValueIdToLinkageMap.find(ValueID);
5999       assert(VLI != ValueIdToLinkageMap.end() &&
6000              "No linkage found for VST entry?");
6001       auto Linkage = VLI->second;
6002       std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
6003           ValueName, VLI->second, SourceFileName);
6004       auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
6005       auto OriginalNameID = FunctionGUID;
6006       if (GlobalValue::isLocalLinkage(Linkage))
6007         OriginalNameID = GlobalValue::getGUID(ValueName);
6008       if (PrintSummaryGUIDs)
6009         dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
6010                << ValueName << "\n";
6011       ValueIdToCallGraphGUIDMap[ValueID] =
6012           std::make_pair(FunctionGUID, OriginalNameID);
6013 
6014       ValueName.clear();
6015       break;
6016     }
6017     case bitc::VST_CODE_COMBINED_ENTRY: {
6018       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6019       unsigned ValueID = Record[0];
6020       GlobalValue::GUID RefGUID = Record[1];
6021       // The "original name", which is the second value of the pair will be
6022       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6023       ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
6024       break;
6025     }
6026     }
6027   }
6028 }
6029 
6030 // Parse just the blocks needed for building the index out of the module.
6031 // At the end of this routine the module Index is populated with a map
6032 // from global value id to GlobalValueSummary objects.
6033 std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
6034   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6035     return error("Invalid record");
6036 
6037   SmallVector<uint64_t, 64> Record;
6038   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6039   unsigned ValueId = 0;
6040 
6041   // Read the index for this module.
6042   while (true) {
6043     BitstreamEntry Entry = Stream.advance();
6044 
6045     switch (Entry.Kind) {
6046     case BitstreamEntry::Error:
6047       return error("Malformed block");
6048     case BitstreamEntry::EndBlock:
6049       return std::error_code();
6050 
6051     case BitstreamEntry::SubBlock:
6052       if (CheckGlobalValSummaryPresenceOnly) {
6053         if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6054           SeenGlobalValSummary = true;
6055           // No need to parse the rest since we found the summary.
6056           return std::error_code();
6057         }
6058         if (Stream.SkipBlock())
6059           return error("Invalid record");
6060         continue;
6061       }
6062       switch (Entry.ID) {
6063       default: // Skip unknown content.
6064         if (Stream.SkipBlock())
6065           return error("Invalid record");
6066         break;
6067       case bitc::BLOCKINFO_BLOCK_ID:
6068         // Need to parse these to get abbrev ids (e.g. for VST)
6069         if (Stream.ReadBlockInfoBlock())
6070           return error("Malformed block");
6071         break;
6072       case bitc::VALUE_SYMTAB_BLOCK_ID:
6073         // Should have been parsed earlier via VSTOffset, unless there
6074         // is no summary section.
6075         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6076                 !SeenGlobalValSummary) &&
6077                "Expected early VST parse via VSTOffset record");
6078         if (Stream.SkipBlock())
6079           return error("Invalid record");
6080         break;
6081       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6082         assert(VSTOffset > 0 && "Expected non-zero VST offset");
6083         assert(!SeenValueSymbolTable &&
6084                "Already read VST when parsing summary block?");
6085         if (std::error_code EC =
6086                 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6087           return EC;
6088         SeenValueSymbolTable = true;
6089         SeenGlobalValSummary = true;
6090         if (std::error_code EC = parseEntireSummary())
6091           return EC;
6092         break;
6093       case bitc::MODULE_STRTAB_BLOCK_ID:
6094         if (std::error_code EC = parseModuleStringTable())
6095           return EC;
6096         break;
6097       }
6098       continue;
6099 
6100     case BitstreamEntry::Record: {
6101         Record.clear();
6102         auto BitCode = Stream.readRecord(Entry.ID, Record);
6103         switch (BitCode) {
6104         default:
6105           break; // Default behavior, ignore unknown content.
6106         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6107         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6108           SmallString<128> ValueName;
6109           if (convertToString(Record, 0, ValueName))
6110             return error("Invalid record");
6111           SourceFileName = ValueName.c_str();
6112           break;
6113         }
6114         /// MODULE_CODE_HASH: [5*i32]
6115         case bitc::MODULE_CODE_HASH: {
6116           if (Record.size() != 5)
6117             return error("Invalid hash length " + Twine(Record.size()).str());
6118           if (!TheIndex)
6119             break;
6120           if (TheIndex->modulePaths().empty())
6121             // Does not have any summary emitted.
6122             break;
6123           if (TheIndex->modulePaths().size() != 1)
6124             return error("Don't expect multiple modules defined?");
6125           auto &Hash = TheIndex->modulePaths().begin()->second.second;
6126           int Pos = 0;
6127           for (auto &Val : Record) {
6128             assert(!(Val >> 32) && "Unexpected high bits set");
6129             Hash[Pos++] = Val;
6130           }
6131           break;
6132         }
6133         /// MODULE_CODE_VSTOFFSET: [offset]
6134         case bitc::MODULE_CODE_VSTOFFSET:
6135           if (Record.size() < 1)
6136             return error("Invalid record");
6137           VSTOffset = Record[0];
6138           break;
6139         // GLOBALVAR: [pointer type, isconst, initid,
6140         //             linkage, alignment, section, visibility, threadlocal,
6141         //             unnamed_addr, externally_initialized, dllstorageclass,
6142         //             comdat]
6143         case bitc::MODULE_CODE_GLOBALVAR: {
6144           if (Record.size() < 6)
6145             return error("Invalid record");
6146           uint64_t RawLinkage = Record[3];
6147           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6148           ValueIdToLinkageMap[ValueId++] = Linkage;
6149           break;
6150         }
6151         // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
6152         //             alignment, section, visibility, gc, unnamed_addr,
6153         //             prologuedata, dllstorageclass, comdat, prefixdata]
6154         case bitc::MODULE_CODE_FUNCTION: {
6155           if (Record.size() < 8)
6156             return error("Invalid record");
6157           uint64_t RawLinkage = Record[3];
6158           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6159           ValueIdToLinkageMap[ValueId++] = Linkage;
6160           break;
6161         }
6162         // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6163         // dllstorageclass]
6164         case bitc::MODULE_CODE_ALIAS: {
6165           if (Record.size() < 6)
6166             return error("Invalid record");
6167           uint64_t RawLinkage = Record[3];
6168           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6169           ValueIdToLinkageMap[ValueId++] = Linkage;
6170           break;
6171         }
6172         }
6173       }
6174       continue;
6175     }
6176   }
6177 }
6178 
6179 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6180 // objects in the index.
6181 std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
6182   if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
6183     return error("Invalid record");
6184   SmallVector<uint64_t, 64> Record;
6185 
6186   // Parse version
6187   {
6188     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6189     if (Entry.Kind != BitstreamEntry::Record)
6190       return error("Invalid Summary Block: record for version expected");
6191     if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6192       return error("Invalid Summary Block: version expected");
6193   }
6194   const uint64_t Version = Record[0];
6195   if (Version != 1)
6196     return error("Invalid summary version " + Twine(Version) + ", 1 expected");
6197   Record.clear();
6198 
6199   // Keep around the last seen summary to be used when we see an optional
6200   // "OriginalName" attachement.
6201   GlobalValueSummary *LastSeenSummary = nullptr;
6202   bool Combined = false;
6203 
6204   while (true) {
6205     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6206 
6207     switch (Entry.Kind) {
6208     case BitstreamEntry::SubBlock: // Handled for us already.
6209     case BitstreamEntry::Error:
6210       return error("Malformed block");
6211     case BitstreamEntry::EndBlock:
6212       // For a per-module index, remove any entries that still have empty
6213       // summaries. The VST parsing creates entries eagerly for all symbols,
6214       // but not all have associated summaries (e.g. it doesn't know how to
6215       // distinguish between VST_CODE_ENTRY for function declarations vs global
6216       // variables with initializers that end up with a summary). Remove those
6217       // entries now so that we don't need to rely on the combined index merger
6218       // to clean them up (especially since that may not run for the first
6219       // module's index if we merge into that).
6220       if (!Combined)
6221         TheIndex->removeEmptySummaryEntries();
6222       return std::error_code();
6223     case BitstreamEntry::Record:
6224       // The interesting case.
6225       break;
6226     }
6227 
6228     // Read a record. The record format depends on whether this
6229     // is a per-module index or a combined index file. In the per-module
6230     // case the records contain the associated value's ID for correlation
6231     // with VST entries. In the combined index the correlation is done
6232     // via the bitcode offset of the summary records (which were saved
6233     // in the combined index VST entries). The records also contain
6234     // information used for ThinLTO renaming and importing.
6235     Record.clear();
6236     auto BitCode = Stream.readRecord(Entry.ID, Record);
6237     switch (BitCode) {
6238     default: // Default behavior: ignore.
6239       break;
6240     // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
6241     //                n x (valueid, callsitecount)]
6242     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
6243     //                        numrefs x valueid,
6244     //                        n x (valueid, callsitecount, profilecount)]
6245     case bitc::FS_PERMODULE:
6246     case bitc::FS_PERMODULE_PROFILE: {
6247       unsigned ValueID = Record[0];
6248       uint64_t RawFlags = Record[1];
6249       unsigned InstCount = Record[2];
6250       unsigned NumRefs = Record[3];
6251       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6252       std::unique_ptr<FunctionSummary> FS =
6253           llvm::make_unique<FunctionSummary>(Flags, InstCount);
6254       // The module path string ref set in the summary must be owned by the
6255       // index's module string table. Since we don't have a module path
6256       // string table section in the per-module index, we create a single
6257       // module path string table entry with an empty (0) ID to take
6258       // ownership.
6259       FS->setModulePath(
6260           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6261       static int RefListStartIndex = 4;
6262       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6263       assert(Record.size() >= RefListStartIndex + NumRefs &&
6264              "Record size inconsistent with number of references");
6265       for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6266         unsigned RefValueId = Record[I];
6267         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6268         FS->addRefEdge(RefGUID);
6269       }
6270       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6271       for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6272            ++I) {
6273         unsigned CalleeValueId = Record[I];
6274         unsigned CallsiteCount = Record[++I];
6275         uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
6276         GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
6277         FS->addCallGraphEdge(CalleeGUID,
6278                              CalleeInfo(CallsiteCount, ProfileCount));
6279       }
6280       auto GUID = getGUIDFromValueId(ValueID);
6281       FS->setOriginalName(GUID.second);
6282       TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
6283       break;
6284     }
6285     // FS_ALIAS: [valueid, flags, valueid]
6286     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6287     // they expect all aliasee summaries to be available.
6288     case bitc::FS_ALIAS: {
6289       unsigned ValueID = Record[0];
6290       uint64_t RawFlags = Record[1];
6291       unsigned AliaseeID = Record[2];
6292       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6293       std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
6294       // The module path string ref set in the summary must be owned by the
6295       // index's module string table. Since we don't have a module path
6296       // string table section in the per-module index, we create a single
6297       // module path string table entry with an empty (0) ID to take
6298       // ownership.
6299       AS->setModulePath(
6300           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6301 
6302       GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
6303       auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6304       if (!AliaseeSummary)
6305         return error("Alias expects aliasee summary to be parsed");
6306       AS->setAliasee(AliaseeSummary);
6307 
6308       auto GUID = getGUIDFromValueId(ValueID);
6309       AS->setOriginalName(GUID.second);
6310       TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
6311       break;
6312     }
6313     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
6314     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6315       unsigned ValueID = Record[0];
6316       uint64_t RawFlags = Record[1];
6317       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6318       std::unique_ptr<GlobalVarSummary> FS =
6319           llvm::make_unique<GlobalVarSummary>(Flags);
6320       FS->setModulePath(
6321           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6322       for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6323         unsigned RefValueId = Record[I];
6324         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6325         FS->addRefEdge(RefGUID);
6326       }
6327       auto GUID = getGUIDFromValueId(ValueID);
6328       FS->setOriginalName(GUID.second);
6329       TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
6330       break;
6331     }
6332     // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
6333     //               numrefs x valueid, n x (valueid, callsitecount)]
6334     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
6335     //                       numrefs x valueid,
6336     //                       n x (valueid, callsitecount, profilecount)]
6337     case bitc::FS_COMBINED:
6338     case bitc::FS_COMBINED_PROFILE: {
6339       unsigned ValueID = Record[0];
6340       uint64_t ModuleId = Record[1];
6341       uint64_t RawFlags = Record[2];
6342       unsigned InstCount = Record[3];
6343       unsigned NumRefs = Record[4];
6344       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6345       std::unique_ptr<FunctionSummary> FS =
6346           llvm::make_unique<FunctionSummary>(Flags, InstCount);
6347       LastSeenSummary = FS.get();
6348       FS->setModulePath(ModuleIdMap[ModuleId]);
6349       static int RefListStartIndex = 5;
6350       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6351       assert(Record.size() >= RefListStartIndex + NumRefs &&
6352              "Record size inconsistent with number of references");
6353       for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6354            ++I) {
6355         unsigned RefValueId = Record[I];
6356         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6357         FS->addRefEdge(RefGUID);
6358       }
6359       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6360       for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6361            ++I) {
6362         unsigned CalleeValueId = Record[I];
6363         unsigned CallsiteCount = Record[++I];
6364         uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
6365         GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
6366         FS->addCallGraphEdge(CalleeGUID,
6367                              CalleeInfo(CallsiteCount, ProfileCount));
6368       }
6369       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6370       TheIndex->addGlobalValueSummary(GUID, std::move(FS));
6371       Combined = true;
6372       break;
6373     }
6374     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6375     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6376     // they expect all aliasee summaries to be available.
6377     case bitc::FS_COMBINED_ALIAS: {
6378       unsigned ValueID = Record[0];
6379       uint64_t ModuleId = Record[1];
6380       uint64_t RawFlags = Record[2];
6381       unsigned AliaseeValueId = Record[3];
6382       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6383       std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
6384       LastSeenSummary = AS.get();
6385       AS->setModulePath(ModuleIdMap[ModuleId]);
6386 
6387       auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6388       auto AliaseeInModule =
6389           TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6390       if (!AliaseeInModule)
6391         return error("Alias expects aliasee summary to be parsed");
6392       AS->setAliasee(AliaseeInModule);
6393 
6394       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6395       TheIndex->addGlobalValueSummary(GUID, std::move(AS));
6396       Combined = true;
6397       break;
6398     }
6399     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6400     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6401       unsigned ValueID = Record[0];
6402       uint64_t ModuleId = Record[1];
6403       uint64_t RawFlags = Record[2];
6404       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6405       std::unique_ptr<GlobalVarSummary> FS =
6406           llvm::make_unique<GlobalVarSummary>(Flags);
6407       LastSeenSummary = FS.get();
6408       FS->setModulePath(ModuleIdMap[ModuleId]);
6409       for (unsigned I = 3, E = Record.size(); I != E; ++I) {
6410         unsigned RefValueId = Record[I];
6411         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
6412         FS->addRefEdge(RefGUID);
6413       }
6414       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
6415       TheIndex->addGlobalValueSummary(GUID, std::move(FS));
6416       Combined = true;
6417       break;
6418     }
6419     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6420     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6421       uint64_t OriginalName = Record[0];
6422       if (!LastSeenSummary)
6423         return error("Name attachment that does not follow a combined record");
6424       LastSeenSummary->setOriginalName(OriginalName);
6425       // Reset the LastSeenSummary
6426       LastSeenSummary = nullptr;
6427     }
6428     }
6429   }
6430   llvm_unreachable("Exit infinite loop");
6431 }
6432 
6433 // Parse the  module string table block into the Index.
6434 // This populates the ModulePathStringTable map in the index.
6435 std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6436   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6437     return error("Invalid record");
6438 
6439   SmallVector<uint64_t, 64> Record;
6440 
6441   SmallString<128> ModulePath;
6442   ModulePathStringTableTy::iterator LastSeenModulePath;
6443 
6444   while (true) {
6445     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6446 
6447     switch (Entry.Kind) {
6448     case BitstreamEntry::SubBlock: // Handled for us already.
6449     case BitstreamEntry::Error:
6450       return error("Malformed block");
6451     case BitstreamEntry::EndBlock:
6452       return std::error_code();
6453     case BitstreamEntry::Record:
6454       // The interesting case.
6455       break;
6456     }
6457 
6458     Record.clear();
6459     switch (Stream.readRecord(Entry.ID, Record)) {
6460     default: // Default behavior: ignore.
6461       break;
6462     case bitc::MST_CODE_ENTRY: {
6463       // MST_ENTRY: [modid, namechar x N]
6464       uint64_t ModuleId = Record[0];
6465 
6466       if (convertToString(Record, 1, ModulePath))
6467         return error("Invalid record");
6468 
6469       LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6470       ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6471 
6472       ModulePath.clear();
6473       break;
6474     }
6475     /// MST_CODE_HASH: [5*i32]
6476     case bitc::MST_CODE_HASH: {
6477       if (Record.size() != 5)
6478         return error("Invalid hash length " + Twine(Record.size()).str());
6479       if (LastSeenModulePath == TheIndex->modulePaths().end())
6480         return error("Invalid hash that does not follow a module path");
6481       int Pos = 0;
6482       for (auto &Val : Record) {
6483         assert(!(Val >> 32) && "Unexpected high bits set");
6484         LastSeenModulePath->second.second[Pos++] = Val;
6485       }
6486       // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6487       LastSeenModulePath = TheIndex->modulePaths().end();
6488       break;
6489     }
6490     }
6491   }
6492   llvm_unreachable("Exit infinite loop");
6493 }
6494 
6495 // Parse the function info index from the bitcode streamer into the given index.
6496 std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6497     std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
6498   TheIndex = I;
6499 
6500   if (std::error_code EC = initStream(std::move(Streamer)))
6501     return EC;
6502 
6503   // Sniff for the signature.
6504   if (!hasValidBitcodeHeader(Stream))
6505     return error("Invalid bitcode signature");
6506 
6507   // We expect a number of well-defined blocks, though we don't necessarily
6508   // need to understand them all.
6509   while (true) {
6510     if (Stream.AtEndOfStream()) {
6511       // We didn't really read a proper Module block.
6512       return error("Malformed block");
6513     }
6514 
6515     BitstreamEntry Entry =
6516         Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6517 
6518     if (Entry.Kind != BitstreamEntry::SubBlock)
6519       return error("Malformed block");
6520 
6521     // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6522     // building the function summary index.
6523     if (Entry.ID == bitc::MODULE_BLOCK_ID)
6524       return parseModule();
6525 
6526     if (Stream.SkipBlock())
6527       return error("Invalid record");
6528   }
6529 }
6530 
6531 std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6532     std::unique_ptr<DataStreamer> Streamer) {
6533   if (Streamer)
6534     return initLazyStream(std::move(Streamer));
6535   return initStreamFromBuffer();
6536 }
6537 
6538 std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
6539   const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6540   const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6541 
6542   if (Buffer->getBufferSize() & 3)
6543     return error("Invalid bitcode signature");
6544 
6545   // If we have a wrapper header, parse it and ignore the non-bc file contents.
6546   // The magic number is 0x0B17C0DE stored in little endian.
6547   if (isBitcodeWrapper(BufPtr, BufEnd))
6548     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6549       return error("Invalid bitcode wrapper header");
6550 
6551   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6552   Stream.init(&*StreamFile);
6553 
6554   return std::error_code();
6555 }
6556 
6557 std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
6558     std::unique_ptr<DataStreamer> Streamer) {
6559   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6560   // see it.
6561   auto OwnedBytes =
6562       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6563   StreamingMemoryObject &Bytes = *OwnedBytes;
6564   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6565   Stream.init(&*StreamFile);
6566 
6567   unsigned char buf[16];
6568   if (Bytes.readBytes(buf, 16, 0) != 16)
6569     return error("Invalid bitcode signature");
6570 
6571   if (!isBitcode(buf, buf + 16))
6572     return error("Invalid bitcode signature");
6573 
6574   if (isBitcodeWrapper(buf, buf + 4)) {
6575     const unsigned char *bitcodeStart = buf;
6576     const unsigned char *bitcodeEnd = buf + 16;
6577     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6578     Bytes.dropLeadingBytes(bitcodeStart - buf);
6579     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6580   }
6581   return std::error_code();
6582 }
6583 
6584 namespace {
6585 
6586 // FIXME: This class is only here to support the transition to llvm::Error. It
6587 // will be removed once this transition is complete. Clients should prefer to
6588 // deal with the Error value directly, rather than converting to error_code.
6589 class BitcodeErrorCategoryType : public std::error_category {
6590   const char *name() const LLVM_NOEXCEPT override {
6591     return "llvm.bitcode";
6592   }
6593   std::string message(int IE) const override {
6594     BitcodeError E = static_cast<BitcodeError>(IE);
6595     switch (E) {
6596     case BitcodeError::InvalidBitcodeSignature:
6597       return "Invalid bitcode signature";
6598     case BitcodeError::CorruptedBitcode:
6599       return "Corrupted bitcode";
6600     }
6601     llvm_unreachable("Unknown error type!");
6602   }
6603 };
6604 
6605 } // end anonymous namespace
6606 
6607 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6608 
6609 const std::error_category &llvm::BitcodeErrorCategory() {
6610   return *ErrorCategory;
6611 }
6612 
6613 //===----------------------------------------------------------------------===//
6614 // External interface
6615 //===----------------------------------------------------------------------===//
6616 
6617 static ErrorOr<std::unique_ptr<Module>>
6618 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6619                      BitcodeReader *R, LLVMContext &Context,
6620                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6621   std::unique_ptr<Module> M = llvm::make_unique<Module>(Name, Context);
6622   M->setMaterializer(R);
6623 
6624   auto cleanupOnError = [&](std::error_code EC) {
6625     R->releaseBuffer(); // Never take ownership on error.
6626     return EC;
6627   };
6628 
6629   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6630   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6631                                                ShouldLazyLoadMetadata))
6632     return cleanupOnError(EC);
6633 
6634   if (MaterializeAll) {
6635     // Read in the entire module, and destroy the BitcodeReader.
6636     if (std::error_code EC = M->materializeAll())
6637       return cleanupOnError(EC);
6638   } else {
6639     // Resolve forward references from blockaddresses.
6640     if (std::error_code EC = R->materializeForwardReferencedFunctions())
6641       return cleanupOnError(EC);
6642   }
6643   return std::move(M);
6644 }
6645 
6646 /// \brief Get a lazy one-at-time loading module from bitcode.
6647 ///
6648 /// This isn't always used in a lazy context.  In particular, it's also used by
6649 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
6650 /// in forward-referenced functions from block address references.
6651 ///
6652 /// \param[in] MaterializeAll Set to \c true if we should materialize
6653 /// everything.
6654 static ErrorOr<std::unique_ptr<Module>>
6655 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
6656                          LLVMContext &Context, bool MaterializeAll,
6657                          bool ShouldLazyLoadMetadata = false) {
6658   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
6659 
6660   ErrorOr<std::unique_ptr<Module>> Ret =
6661       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6662                            MaterializeAll, ShouldLazyLoadMetadata);
6663   if (!Ret)
6664     return Ret;
6665 
6666   Buffer.release(); // The BitcodeReader owns it now.
6667   return Ret;
6668 }
6669 
6670 ErrorOr<std::unique_ptr<Module>>
6671 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6672                            LLVMContext &Context, bool ShouldLazyLoadMetadata) {
6673   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
6674                                   ShouldLazyLoadMetadata);
6675 }
6676 
6677 ErrorOr<std::unique_ptr<Module>>
6678 llvm::getStreamedBitcodeModule(StringRef Name,
6679                                std::unique_ptr<DataStreamer> Streamer,
6680                                LLVMContext &Context) {
6681   std::unique_ptr<Module> M = llvm::make_unique<Module>(Name, Context);
6682   BitcodeReader *R = new BitcodeReader(Context);
6683 
6684   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6685                               false);
6686 }
6687 
6688 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6689                                                         LLVMContext &Context) {
6690   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6691   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
6692   // TODO: Restore the use-lists to the in-memory state when the bitcode was
6693   // written.  We must defer until the Module has been fully materialized.
6694 }
6695 
6696 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6697                                          LLVMContext &Context) {
6698   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6699   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6700   ErrorOr<std::string> Triple = R->parseTriple();
6701   if (Triple.getError())
6702     return "";
6703   return Triple.get();
6704 }
6705 
6706 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
6707                                            LLVMContext &Context) {
6708   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6709   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
6710   ErrorOr<bool> hasObjCCategory = R->hasObjCCategory();
6711   if (hasObjCCategory.getError())
6712     return false;
6713   return hasObjCCategory.get();
6714 }
6715 
6716 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6717                                            LLVMContext &Context) {
6718   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6719   BitcodeReader R(Buf.release(), Context);
6720   ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6721   if (ProducerString.getError())
6722     return "";
6723   return ProducerString.get();
6724 }
6725 
6726 // Parse the specified bitcode buffer, returning the function info index.
6727 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
6728     MemoryBufferRef Buffer,
6729     const DiagnosticHandlerFunction &DiagnosticHandler) {
6730   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6731   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
6732 
6733   auto Index = llvm::make_unique<ModuleSummaryIndex>();
6734 
6735   auto cleanupOnError = [&](std::error_code EC) {
6736     R.releaseBuffer(); // Never take ownership on error.
6737     return EC;
6738   };
6739 
6740   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6741     return cleanupOnError(EC);
6742 
6743   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6744   return std::move(Index);
6745 }
6746 
6747 // Check if the given bitcode buffer contains a global value summary block.
6748 bool llvm::hasGlobalValueSummary(
6749     MemoryBufferRef Buffer,
6750     const DiagnosticHandlerFunction &DiagnosticHandler) {
6751   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
6752   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
6753 
6754   auto cleanupOnError = [&](std::error_code EC) {
6755     R.releaseBuffer(); // Never take ownership on error.
6756     return false;
6757   };
6758 
6759   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6760     return cleanupOnError(EC);
6761 
6762   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
6763   return R.foundGlobalValSummary();
6764 }
6765