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