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