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