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