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