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