522f2aa4707b6e873db86a8e5b4afaed82e37821
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/GVMaterializer.h"
24 #include "llvm/IR/InlineAsm.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/OperandTraits.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/FunctionInfo.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/DataStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <deque>
38 using namespace llvm;
39
40 namespace {
41 enum {
42   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
43 };
44
45 /// Indicates which operator an operand allows (for the few operands that may
46 /// only reference a certain operator).
47 enum OperatorConstraint {
48   OC_None = 0,  // No constraint
49   OC_CatchPad,  // Must be CatchPadInst
50   OC_CleanupPad // Must be CleanupPadInst
51 };
52
53 class BitcodeReaderValueList {
54   std::vector<WeakVH> ValuePtrs;
55
56   /// As we resolve forward-referenced constants, we add information about them
57   /// to this vector.  This allows us to resolve them in bulk instead of
58   /// resolving each reference at a time.  See the code in
59   /// ResolveConstantForwardRefs for more information about this.
60   ///
61   /// The key of this vector is the placeholder constant, the value is the slot
62   /// number that holds the resolved value.
63   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64   ResolveConstantsTy ResolveConstants;
65   LLVMContext &Context;
66 public:
67   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68   ~BitcodeReaderValueList() {
69     assert(ResolveConstants.empty() && "Constants not resolved?");
70   }
71
72   // vector compatibility methods
73   unsigned size() const { return ValuePtrs.size(); }
74   void resize(unsigned N) { ValuePtrs.resize(N); }
75   void push_back(Value *V) { ValuePtrs.emplace_back(V); }
76
77   void clear() {
78     assert(ResolveConstants.empty() && "Constants not resolved?");
79     ValuePtrs.clear();
80   }
81
82   Value *operator[](unsigned i) const {
83     assert(i < ValuePtrs.size());
84     return ValuePtrs[i];
85   }
86
87   Value *back() const { return ValuePtrs.back(); }
88     void pop_back() { ValuePtrs.pop_back(); }
89   bool empty() const { return ValuePtrs.empty(); }
90   void shrinkTo(unsigned N) {
91     assert(N <= size() && "Invalid shrinkTo request!");
92     ValuePtrs.resize(N);
93   }
94
95   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
96   Value *getValueFwdRef(unsigned Idx, Type *Ty,
97                         OperatorConstraint OC = OC_None);
98
99   bool assignValue(Value *V, unsigned Idx);
100
101   /// Once all constants are read, this method bulk resolves any forward
102   /// references.
103   void resolveConstantForwardRefs();
104 };
105
106 class BitcodeReaderMDValueList {
107   unsigned NumFwdRefs;
108   bool AnyFwdRefs;
109   unsigned MinFwdRef;
110   unsigned MaxFwdRef;
111   std::vector<TrackingMDRef> MDValuePtrs;
112
113   LLVMContext &Context;
114 public:
115   BitcodeReaderMDValueList(LLVMContext &C)
116       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
117
118   // vector compatibility methods
119   unsigned size() const       { return MDValuePtrs.size(); }
120   void resize(unsigned N)     { MDValuePtrs.resize(N); }
121   void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122   void clear()                { MDValuePtrs.clear();  }
123   Metadata *back() const      { return MDValuePtrs.back(); }
124   void pop_back()             { MDValuePtrs.pop_back(); }
125   bool empty() const          { return MDValuePtrs.empty(); }
126
127   Metadata *operator[](unsigned i) const {
128     assert(i < MDValuePtrs.size());
129     return MDValuePtrs[i];
130   }
131
132   void shrinkTo(unsigned N) {
133     assert(N <= size() && "Invalid shrinkTo request!");
134     MDValuePtrs.resize(N);
135   }
136
137   Metadata *getValueFwdRef(unsigned Idx);
138   void assignValue(Metadata *MD, unsigned Idx);
139   void tryToResolveCycles();
140 };
141
142 class BitcodeReader : public GVMaterializer {
143   LLVMContext &Context;
144   DiagnosticHandlerFunction DiagnosticHandler;
145   Module *TheModule = nullptr;
146   std::unique_ptr<MemoryBuffer> Buffer;
147   std::unique_ptr<BitstreamReader> StreamFile;
148   BitstreamCursor Stream;
149   // Next offset to start scanning for lazy parsing of function bodies.
150   uint64_t NextUnreadBit = 0;
151   // Last function offset found in the VST.
152   uint64_t LastFunctionBlockBit = 0;
153   bool SeenValueSymbolTable = false;
154   uint64_t VSTOffset = 0;
155   // Contains an arbitrary and optional string identifying the bitcode producer
156   std::string ProducerIdentification;
157
158   std::vector<Type*> TypeList;
159   BitcodeReaderValueList ValueList;
160   BitcodeReaderMDValueList MDValueList;
161   std::vector<Comdat *> ComdatList;
162   SmallVector<Instruction *, 64> InstructionList;
163
164   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
165   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
166   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
167   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
168   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
169
170   SmallVector<Instruction*, 64> InstsWithTBAATag;
171
172   /// The set of attributes by index.  Index zero in the file is for null, and
173   /// is thus not represented here.  As such all indices are off by one.
174   std::vector<AttributeSet> MAttributes;
175
176   /// The set of attribute groups.
177   std::map<unsigned, AttributeSet> MAttributeGroups;
178
179   /// While parsing a function body, this is a list of the basic blocks for the
180   /// function.
181   std::vector<BasicBlock*> FunctionBBs;
182
183   // When reading the module header, this list is populated with functions that
184   // have bodies later in the file.
185   std::vector<Function*> FunctionsWithBodies;
186
187   // When intrinsic functions are encountered which require upgrading they are
188   // stored here with their replacement function.
189   typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
190   UpgradedIntrinsicMap UpgradedIntrinsics;
191
192   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
193   DenseMap<unsigned, unsigned> MDKindMap;
194
195   // Several operations happen after the module header has been read, but
196   // before function bodies are processed. This keeps track of whether
197   // we've done this yet.
198   bool SeenFirstFunctionBody = false;
199
200   /// When function bodies are initially scanned, this map contains info about
201   /// where to find deferred function body in the stream.
202   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
203
204   /// When Metadata block is initially scanned when parsing the module, we may
205   /// choose to defer parsing of the metadata. This vector contains info about
206   /// which Metadata blocks are deferred.
207   std::vector<uint64_t> DeferredMetadataInfo;
208
209   /// These are basic blocks forward-referenced by block addresses.  They are
210   /// inserted lazily into functions when they're loaded.  The basic block ID is
211   /// its index into the vector.
212   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
213   std::deque<Function *> BasicBlockFwdRefQueue;
214
215   /// Indicates that we are using a new encoding for instruction operands where
216   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
217   /// instruction number, for a more compact encoding.  Some instruction
218   /// operands are not relative to the instruction ID: basic block numbers, and
219   /// types. Once the old style function blocks have been phased out, we would
220   /// not need this flag.
221   bool UseRelativeIDs = false;
222
223   /// True if all functions will be materialized, negating the need to process
224   /// (e.g.) blockaddress forward references.
225   bool WillMaterializeAllForwardRefs = false;
226
227   /// Functions that have block addresses taken.  This is usually empty.
228   SmallPtrSet<const Function *, 4> BlockAddressesTaken;
229
230   /// True if any Metadata block has been materialized.
231   bool IsMetadataMaterialized = false;
232
233   bool StripDebugInfo = false;
234
235   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(uint64_t Offset = 0);
392   std::error_code parseConstants();
393   std::error_code rememberAndSkipFunctionBodies();
394   std::error_code rememberAndSkipFunctionBody();
395   /// Save the positions of the Metadata blocks and skip parsing the blocks.
396   std::error_code rememberAndSkipMetadata();
397   std::error_code parseFunctionBody(Function *F);
398   std::error_code globalCleanup();
399   std::error_code resolveGlobalAndAliasInits();
400   std::error_code parseMetadata();
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     return ::error(DiagnosticHandler, make_error_code(E),
530                    Message + " (Producer: '" + ProducerIdentification +
531                        "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
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     return ::error(DiagnosticHandler,
539                    make_error_code(BitcodeError::CorruptedBitcode),
540                    Message + " (Producer: '" + ProducerIdentification +
541                        "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
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   StringRef NameStr(ValueName.data(), ValueName.size());
1753   if (NameStr.find_first_of(0) != StringRef::npos)
1754     return error("Invalid value name");
1755   V->setName(NameStr);
1756   auto *GO = dyn_cast<GlobalObject>(V);
1757   if (GO) {
1758     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1759       if (TT.isOSBinFormatMachO())
1760         GO->setComdat(nullptr);
1761       else
1762         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1763     }
1764   }
1765   return V;
1766 }
1767
1768 /// Parse the value symbol table at either the current parsing location or
1769 /// at the given bit offset if provided.
1770 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1771   uint64_t CurrentBit;
1772   // Pass in the Offset to distinguish between calling for the module-level
1773   // VST (where we want to jump to the VST offset) and the function-level
1774   // VST (where we don't).
1775   if (Offset > 0) {
1776     // Save the current parsing location so we can jump back at the end
1777     // of the VST read.
1778     CurrentBit = Stream.GetCurrentBitNo();
1779     Stream.JumpToBit(Offset * 32);
1780 #ifndef NDEBUG
1781     // Do some checking if we are in debug mode.
1782     BitstreamEntry Entry = Stream.advance();
1783     assert(Entry.Kind == BitstreamEntry::SubBlock);
1784     assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1785 #else
1786     // In NDEBUG mode ignore the output so we don't get an unused variable
1787     // warning.
1788     Stream.advance();
1789 #endif
1790   }
1791
1792   // Compute the delta between the bitcode indices in the VST (the word offset
1793   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1794   // expected by the lazy reader. The reader's EnterSubBlock expects to have
1795   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1796   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1797   // just before entering the VST subblock because: 1) the EnterSubBlock
1798   // changes the AbbrevID width; 2) the VST block is nested within the same
1799   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1800   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1801   // jump to the FUNCTION_BLOCK using this offset later, we don't want
1802   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1803   unsigned FuncBitcodeOffsetDelta =
1804       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1805
1806   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1807     return error("Invalid record");
1808
1809   SmallVector<uint64_t, 64> Record;
1810
1811   Triple TT(TheModule->getTargetTriple());
1812
1813   // Read all the records for this value table.
1814   SmallString<128> ValueName;
1815   while (1) {
1816     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1817
1818     switch (Entry.Kind) {
1819     case BitstreamEntry::SubBlock: // Handled for us already.
1820     case BitstreamEntry::Error:
1821       return error("Malformed block");
1822     case BitstreamEntry::EndBlock:
1823       if (Offset > 0)
1824         Stream.JumpToBit(CurrentBit);
1825       return std::error_code();
1826     case BitstreamEntry::Record:
1827       // The interesting case.
1828       break;
1829     }
1830
1831     // Read a record.
1832     Record.clear();
1833     switch (Stream.readRecord(Entry.ID, Record)) {
1834     default:  // Default behavior: unknown type.
1835       break;
1836     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1837       ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1838       if (std::error_code EC = ValOrErr.getError())
1839         return EC;
1840       ValOrErr.get();
1841       break;
1842     }
1843     case bitc::VST_CODE_FNENTRY: {
1844       // VST_FNENTRY: [valueid, offset, namechar x N]
1845       ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1846       if (std::error_code EC = ValOrErr.getError())
1847         return EC;
1848       Value *V = ValOrErr.get();
1849
1850       auto *GO = dyn_cast<GlobalObject>(V);
1851       if (!GO) {
1852         // If this is an alias, need to get the actual Function object
1853         // it aliases, in order to set up the DeferredFunctionInfo entry below.
1854         auto *GA = dyn_cast<GlobalAlias>(V);
1855         if (GA)
1856           GO = GA->getBaseObject();
1857         assert(GO);
1858       }
1859
1860       uint64_t FuncWordOffset = Record[1];
1861       Function *F = dyn_cast<Function>(GO);
1862       assert(F);
1863       uint64_t FuncBitOffset = FuncWordOffset * 32;
1864       DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1865       // Set the LastFunctionBlockBit to point to the last function block.
1866       // Later when parsing is resumed after function materialization,
1867       // we can simply skip that last function block.
1868       if (FuncBitOffset > LastFunctionBlockBit)
1869         LastFunctionBlockBit = FuncBitOffset;
1870       break;
1871     }
1872     case bitc::VST_CODE_BBENTRY: {
1873       if (convertToString(Record, 1, ValueName))
1874         return error("Invalid record");
1875       BasicBlock *BB = getBasicBlock(Record[0]);
1876       if (!BB)
1877         return error("Invalid record");
1878
1879       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1880       ValueName.clear();
1881       break;
1882     }
1883     }
1884   }
1885 }
1886
1887 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1888
1889 std::error_code BitcodeReader::parseMetadata() {
1890   IsMetadataMaterialized = true;
1891   unsigned NextMDValueNo = MDValueList.size();
1892
1893   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1894     return error("Invalid record");
1895
1896   SmallVector<uint64_t, 64> Record;
1897
1898   auto getMD =
1899       [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1900   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1901     if (ID)
1902       return getMD(ID - 1);
1903     return nullptr;
1904   };
1905   auto getMDString = [&](unsigned ID) -> MDString *{
1906     // This requires that the ID is not really a forward reference.  In
1907     // particular, the MDString must already have been resolved.
1908     return cast_or_null<MDString>(getMDOrNull(ID));
1909   };
1910
1911 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
1912   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1913
1914   // Read all the records.
1915   while (1) {
1916     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1917
1918     switch (Entry.Kind) {
1919     case BitstreamEntry::SubBlock: // Handled for us already.
1920     case BitstreamEntry::Error:
1921       return error("Malformed block");
1922     case BitstreamEntry::EndBlock:
1923       MDValueList.tryToResolveCycles();
1924       return std::error_code();
1925     case BitstreamEntry::Record:
1926       // The interesting case.
1927       break;
1928     }
1929
1930     // Read a record.
1931     Record.clear();
1932     unsigned Code = Stream.readRecord(Entry.ID, Record);
1933     bool IsDistinct = false;
1934     switch (Code) {
1935     default:  // Default behavior: ignore.
1936       break;
1937     case bitc::METADATA_NAME: {
1938       // Read name of the named metadata.
1939       SmallString<8> Name(Record.begin(), Record.end());
1940       Record.clear();
1941       Code = Stream.ReadCode();
1942
1943       unsigned NextBitCode = Stream.readRecord(Code, Record);
1944       if (NextBitCode != bitc::METADATA_NAMED_NODE)
1945         return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1946
1947       // Read named metadata elements.
1948       unsigned Size = Record.size();
1949       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1950       for (unsigned i = 0; i != Size; ++i) {
1951         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1952         if (!MD)
1953           return error("Invalid record");
1954         NMD->addOperand(MD);
1955       }
1956       break;
1957     }
1958     case bitc::METADATA_OLD_FN_NODE: {
1959       // FIXME: Remove in 4.0.
1960       // This is a LocalAsMetadata record, the only type of function-local
1961       // metadata.
1962       if (Record.size() % 2 == 1)
1963         return error("Invalid record");
1964
1965       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
1966       // to be legal, but there's no upgrade path.
1967       auto dropRecord = [&] {
1968         MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1969       };
1970       if (Record.size() != 2) {
1971         dropRecord();
1972         break;
1973       }
1974
1975       Type *Ty = getTypeByID(Record[0]);
1976       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1977         dropRecord();
1978         break;
1979       }
1980
1981       MDValueList.assignValue(
1982           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1983           NextMDValueNo++);
1984       break;
1985     }
1986     case bitc::METADATA_OLD_NODE: {
1987       // FIXME: Remove in 4.0.
1988       if (Record.size() % 2 == 1)
1989         return error("Invalid record");
1990
1991       unsigned Size = Record.size();
1992       SmallVector<Metadata *, 8> Elts;
1993       for (unsigned i = 0; i != Size; i += 2) {
1994         Type *Ty = getTypeByID(Record[i]);
1995         if (!Ty)
1996           return error("Invalid record");
1997         if (Ty->isMetadataTy())
1998           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1999         else if (!Ty->isVoidTy()) {
2000           auto *MD =
2001               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2002           assert(isa<ConstantAsMetadata>(MD) &&
2003                  "Expected non-function-local metadata");
2004           Elts.push_back(MD);
2005         } else
2006           Elts.push_back(nullptr);
2007       }
2008       MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
2009       break;
2010     }
2011     case bitc::METADATA_VALUE: {
2012       if (Record.size() != 2)
2013         return error("Invalid record");
2014
2015       Type *Ty = getTypeByID(Record[0]);
2016       if (Ty->isMetadataTy() || Ty->isVoidTy())
2017         return error("Invalid record");
2018
2019       MDValueList.assignValue(
2020           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2021           NextMDValueNo++);
2022       break;
2023     }
2024     case bitc::METADATA_DISTINCT_NODE:
2025       IsDistinct = true;
2026       // fallthrough...
2027     case bitc::METADATA_NODE: {
2028       SmallVector<Metadata *, 8> Elts;
2029       Elts.reserve(Record.size());
2030       for (unsigned ID : Record)
2031         Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
2032       MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2033                                          : MDNode::get(Context, Elts),
2034                               NextMDValueNo++);
2035       break;
2036     }
2037     case bitc::METADATA_LOCATION: {
2038       if (Record.size() != 5)
2039         return error("Invalid record");
2040
2041       unsigned Line = Record[1];
2042       unsigned Column = Record[2];
2043       MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2044       Metadata *InlinedAt =
2045           Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
2046       MDValueList.assignValue(
2047           GET_OR_DISTINCT(DILocation, Record[0],
2048                           (Context, Line, Column, Scope, InlinedAt)),
2049           NextMDValueNo++);
2050       break;
2051     }
2052     case bitc::METADATA_GENERIC_DEBUG: {
2053       if (Record.size() < 4)
2054         return error("Invalid record");
2055
2056       unsigned Tag = Record[1];
2057       unsigned Version = Record[2];
2058
2059       if (Tag >= 1u << 16 || Version != 0)
2060         return error("Invalid record");
2061
2062       auto *Header = getMDString(Record[3]);
2063       SmallVector<Metadata *, 8> DwarfOps;
2064       for (unsigned I = 4, E = Record.size(); I != E; ++I)
2065         DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2066                                      : nullptr);
2067       MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
2068                                               (Context, Tag, Header, DwarfOps)),
2069                               NextMDValueNo++);
2070       break;
2071     }
2072     case bitc::METADATA_SUBRANGE: {
2073       if (Record.size() != 3)
2074         return error("Invalid record");
2075
2076       MDValueList.assignValue(
2077           GET_OR_DISTINCT(DISubrange, Record[0],
2078                           (Context, Record[1], unrotateSign(Record[2]))),
2079           NextMDValueNo++);
2080       break;
2081     }
2082     case bitc::METADATA_ENUMERATOR: {
2083       if (Record.size() != 3)
2084         return error("Invalid record");
2085
2086       MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
2087                                               (Context, unrotateSign(Record[1]),
2088                                                getMDString(Record[2]))),
2089                               NextMDValueNo++);
2090       break;
2091     }
2092     case bitc::METADATA_BASIC_TYPE: {
2093       if (Record.size() != 6)
2094         return error("Invalid record");
2095
2096       MDValueList.assignValue(
2097           GET_OR_DISTINCT(DIBasicType, Record[0],
2098                           (Context, Record[1], getMDString(Record[2]),
2099                            Record[3], Record[4], Record[5])),
2100           NextMDValueNo++);
2101       break;
2102     }
2103     case bitc::METADATA_DERIVED_TYPE: {
2104       if (Record.size() != 12)
2105         return error("Invalid record");
2106
2107       MDValueList.assignValue(
2108           GET_OR_DISTINCT(DIDerivedType, Record[0],
2109                           (Context, Record[1], getMDString(Record[2]),
2110                            getMDOrNull(Record[3]), Record[4],
2111                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2112                            Record[7], Record[8], Record[9], Record[10],
2113                            getMDOrNull(Record[11]))),
2114           NextMDValueNo++);
2115       break;
2116     }
2117     case bitc::METADATA_COMPOSITE_TYPE: {
2118       if (Record.size() != 16)
2119         return error("Invalid record");
2120
2121       MDValueList.assignValue(
2122           GET_OR_DISTINCT(DICompositeType, Record[0],
2123                           (Context, Record[1], getMDString(Record[2]),
2124                            getMDOrNull(Record[3]), Record[4],
2125                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2126                            Record[7], Record[8], Record[9], Record[10],
2127                            getMDOrNull(Record[11]), Record[12],
2128                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2129                            getMDString(Record[15]))),
2130           NextMDValueNo++);
2131       break;
2132     }
2133     case bitc::METADATA_SUBROUTINE_TYPE: {
2134       if (Record.size() != 3)
2135         return error("Invalid record");
2136
2137       MDValueList.assignValue(
2138           GET_OR_DISTINCT(DISubroutineType, Record[0],
2139                           (Context, Record[1], getMDOrNull(Record[2]))),
2140           NextMDValueNo++);
2141       break;
2142     }
2143
2144     case bitc::METADATA_MODULE: {
2145       if (Record.size() != 6)
2146         return error("Invalid record");
2147
2148       MDValueList.assignValue(
2149           GET_OR_DISTINCT(DIModule, Record[0],
2150                           (Context, getMDOrNull(Record[1]),
2151                           getMDString(Record[2]), getMDString(Record[3]),
2152                           getMDString(Record[4]), getMDString(Record[5]))),
2153           NextMDValueNo++);
2154       break;
2155     }
2156
2157     case bitc::METADATA_FILE: {
2158       if (Record.size() != 3)
2159         return error("Invalid record");
2160
2161       MDValueList.assignValue(
2162           GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
2163                                               getMDString(Record[2]))),
2164           NextMDValueNo++);
2165       break;
2166     }
2167     case bitc::METADATA_COMPILE_UNIT: {
2168       if (Record.size() < 14 || Record.size() > 15)
2169         return error("Invalid record");
2170
2171       // Ignore Record[1], which indicates whether this compile unit is
2172       // distinct.  It's always distinct.
2173       MDValueList.assignValue(
2174           DICompileUnit::getDistinct(
2175               Context, Record[1], getMDOrNull(Record[2]),
2176               getMDString(Record[3]), Record[4], getMDString(Record[5]),
2177               Record[6], getMDString(Record[7]), Record[8],
2178               getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2179               getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2180               getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
2181           NextMDValueNo++);
2182       break;
2183     }
2184     case bitc::METADATA_SUBPROGRAM: {
2185       if (Record.size() != 19)
2186         return error("Invalid record");
2187
2188       MDValueList.assignValue(
2189           GET_OR_DISTINCT(
2190               DISubprogram,
2191               Record[0] || Record[8], // All definitions should be distinct.
2192               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2193                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2194                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2195                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2196                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
2197                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
2198           NextMDValueNo++);
2199       break;
2200     }
2201     case bitc::METADATA_LEXICAL_BLOCK: {
2202       if (Record.size() != 5)
2203         return error("Invalid record");
2204
2205       MDValueList.assignValue(
2206           GET_OR_DISTINCT(DILexicalBlock, Record[0],
2207                           (Context, getMDOrNull(Record[1]),
2208                            getMDOrNull(Record[2]), Record[3], Record[4])),
2209           NextMDValueNo++);
2210       break;
2211     }
2212     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2213       if (Record.size() != 4)
2214         return error("Invalid record");
2215
2216       MDValueList.assignValue(
2217           GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
2218                           (Context, getMDOrNull(Record[1]),
2219                            getMDOrNull(Record[2]), Record[3])),
2220           NextMDValueNo++);
2221       break;
2222     }
2223     case bitc::METADATA_NAMESPACE: {
2224       if (Record.size() != 5)
2225         return error("Invalid record");
2226
2227       MDValueList.assignValue(
2228           GET_OR_DISTINCT(DINamespace, Record[0],
2229                           (Context, getMDOrNull(Record[1]),
2230                            getMDOrNull(Record[2]), getMDString(Record[3]),
2231                            Record[4])),
2232           NextMDValueNo++);
2233       break;
2234     }
2235     case bitc::METADATA_TEMPLATE_TYPE: {
2236       if (Record.size() != 3)
2237         return error("Invalid record");
2238
2239       MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2240                                               Record[0],
2241                                               (Context, getMDString(Record[1]),
2242                                                getMDOrNull(Record[2]))),
2243                               NextMDValueNo++);
2244       break;
2245     }
2246     case bitc::METADATA_TEMPLATE_VALUE: {
2247       if (Record.size() != 5)
2248         return error("Invalid record");
2249
2250       MDValueList.assignValue(
2251           GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
2252                           (Context, Record[1], getMDString(Record[2]),
2253                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
2254           NextMDValueNo++);
2255       break;
2256     }
2257     case bitc::METADATA_GLOBAL_VAR: {
2258       if (Record.size() != 11)
2259         return error("Invalid record");
2260
2261       MDValueList.assignValue(
2262           GET_OR_DISTINCT(DIGlobalVariable, Record[0],
2263                           (Context, getMDOrNull(Record[1]),
2264                            getMDString(Record[2]), getMDString(Record[3]),
2265                            getMDOrNull(Record[4]), Record[5],
2266                            getMDOrNull(Record[6]), Record[7], Record[8],
2267                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2268           NextMDValueNo++);
2269       break;
2270     }
2271     case bitc::METADATA_LOCAL_VAR: {
2272       // 10th field is for the obseleted 'inlinedAt:' field.
2273       if (Record.size() < 8 || Record.size() > 10)
2274         return error("Invalid record");
2275
2276       // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2277       // DW_TAG_arg_variable.
2278       bool HasTag = Record.size() > 8;
2279       MDValueList.assignValue(
2280           GET_OR_DISTINCT(DILocalVariable, Record[0],
2281                           (Context, getMDOrNull(Record[1 + HasTag]),
2282                            getMDString(Record[2 + HasTag]),
2283                            getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2284                            getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2285                            Record[7 + HasTag])),
2286           NextMDValueNo++);
2287       break;
2288     }
2289     case bitc::METADATA_EXPRESSION: {
2290       if (Record.size() < 1)
2291         return error("Invalid record");
2292
2293       MDValueList.assignValue(
2294           GET_OR_DISTINCT(DIExpression, Record[0],
2295                           (Context, makeArrayRef(Record).slice(1))),
2296           NextMDValueNo++);
2297       break;
2298     }
2299     case bitc::METADATA_OBJC_PROPERTY: {
2300       if (Record.size() != 8)
2301         return error("Invalid record");
2302
2303       MDValueList.assignValue(
2304           GET_OR_DISTINCT(DIObjCProperty, Record[0],
2305                           (Context, getMDString(Record[1]),
2306                            getMDOrNull(Record[2]), Record[3],
2307                            getMDString(Record[4]), getMDString(Record[5]),
2308                            Record[6], getMDOrNull(Record[7]))),
2309           NextMDValueNo++);
2310       break;
2311     }
2312     case bitc::METADATA_IMPORTED_ENTITY: {
2313       if (Record.size() != 6)
2314         return error("Invalid record");
2315
2316       MDValueList.assignValue(
2317           GET_OR_DISTINCT(DIImportedEntity, Record[0],
2318                           (Context, Record[1], getMDOrNull(Record[2]),
2319                            getMDOrNull(Record[3]), Record[4],
2320                            getMDString(Record[5]))),
2321           NextMDValueNo++);
2322       break;
2323     }
2324     case bitc::METADATA_STRING: {
2325       std::string String(Record.begin(), Record.end());
2326       llvm::UpgradeMDStringConstant(String);
2327       Metadata *MD = MDString::get(Context, String);
2328       MDValueList.assignValue(MD, NextMDValueNo++);
2329       break;
2330     }
2331     case bitc::METADATA_KIND: {
2332       if (Record.size() < 2)
2333         return error("Invalid record");
2334
2335       unsigned Kind = Record[0];
2336       SmallString<8> Name(Record.begin()+1, Record.end());
2337
2338       unsigned NewKind = TheModule->getMDKindID(Name.str());
2339       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2340         return error("Conflicting METADATA_KIND records");
2341       break;
2342     }
2343     }
2344   }
2345 #undef GET_OR_DISTINCT
2346 }
2347
2348 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2349 /// encoding.
2350 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2351   if ((V & 1) == 0)
2352     return V >> 1;
2353   if (V != 1)
2354     return -(V >> 1);
2355   // There is no such thing as -0 with integers.  "-0" really means MININT.
2356   return 1ULL << 63;
2357 }
2358
2359 /// Resolve all of the initializers for global values and aliases that we can.
2360 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2361   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2362   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2363   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2364   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2365   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2366
2367   GlobalInitWorklist.swap(GlobalInits);
2368   AliasInitWorklist.swap(AliasInits);
2369   FunctionPrefixWorklist.swap(FunctionPrefixes);
2370   FunctionPrologueWorklist.swap(FunctionPrologues);
2371   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2372
2373   while (!GlobalInitWorklist.empty()) {
2374     unsigned ValID = GlobalInitWorklist.back().second;
2375     if (ValID >= ValueList.size()) {
2376       // Not ready to resolve this yet, it requires something later in the file.
2377       GlobalInits.push_back(GlobalInitWorklist.back());
2378     } else {
2379       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2380         GlobalInitWorklist.back().first->setInitializer(C);
2381       else
2382         return error("Expected a constant");
2383     }
2384     GlobalInitWorklist.pop_back();
2385   }
2386
2387   while (!AliasInitWorklist.empty()) {
2388     unsigned ValID = AliasInitWorklist.back().second;
2389     if (ValID >= ValueList.size()) {
2390       AliasInits.push_back(AliasInitWorklist.back());
2391     } else {
2392       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2393       if (!C)
2394         return error("Expected a constant");
2395       GlobalAlias *Alias = AliasInitWorklist.back().first;
2396       if (C->getType() != Alias->getType())
2397         return error("Alias and aliasee types don't match");
2398       Alias->setAliasee(C);
2399     }
2400     AliasInitWorklist.pop_back();
2401   }
2402
2403   while (!FunctionPrefixWorklist.empty()) {
2404     unsigned ValID = FunctionPrefixWorklist.back().second;
2405     if (ValID >= ValueList.size()) {
2406       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2407     } else {
2408       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2409         FunctionPrefixWorklist.back().first->setPrefixData(C);
2410       else
2411         return error("Expected a constant");
2412     }
2413     FunctionPrefixWorklist.pop_back();
2414   }
2415
2416   while (!FunctionPrologueWorklist.empty()) {
2417     unsigned ValID = FunctionPrologueWorklist.back().second;
2418     if (ValID >= ValueList.size()) {
2419       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2420     } else {
2421       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2422         FunctionPrologueWorklist.back().first->setPrologueData(C);
2423       else
2424         return error("Expected a constant");
2425     }
2426     FunctionPrologueWorklist.pop_back();
2427   }
2428
2429   while (!FunctionPersonalityFnWorklist.empty()) {
2430     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2431     if (ValID >= ValueList.size()) {
2432       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2433     } else {
2434       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2435         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2436       else
2437         return error("Expected a constant");
2438     }
2439     FunctionPersonalityFnWorklist.pop_back();
2440   }
2441
2442   return std::error_code();
2443 }
2444
2445 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2446   SmallVector<uint64_t, 8> Words(Vals.size());
2447   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2448                  BitcodeReader::decodeSignRotatedValue);
2449
2450   return APInt(TypeBits, Words);
2451 }
2452
2453 std::error_code BitcodeReader::parseConstants() {
2454   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2455     return error("Invalid record");
2456
2457   SmallVector<uint64_t, 64> Record;
2458
2459   // Read all the records for this value table.
2460   Type *CurTy = Type::getInt32Ty(Context);
2461   unsigned NextCstNo = ValueList.size();
2462   while (1) {
2463     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2464
2465     switch (Entry.Kind) {
2466     case BitstreamEntry::SubBlock: // Handled for us already.
2467     case BitstreamEntry::Error:
2468       return error("Malformed block");
2469     case BitstreamEntry::EndBlock:
2470       if (NextCstNo != ValueList.size())
2471         return error("Invalid ronstant reference");
2472
2473       // Once all the constants have been read, go through and resolve forward
2474       // references.
2475       ValueList.resolveConstantForwardRefs();
2476       return std::error_code();
2477     case BitstreamEntry::Record:
2478       // The interesting case.
2479       break;
2480     }
2481
2482     // Read a record.
2483     Record.clear();
2484     Value *V = nullptr;
2485     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2486     switch (BitCode) {
2487     default:  // Default behavior: unknown constant
2488     case bitc::CST_CODE_UNDEF:     // UNDEF
2489       V = UndefValue::get(CurTy);
2490       break;
2491     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2492       if (Record.empty())
2493         return error("Invalid record");
2494       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2495         return error("Invalid record");
2496       CurTy = TypeList[Record[0]];
2497       continue;  // Skip the ValueList manipulation.
2498     case bitc::CST_CODE_NULL:      // NULL
2499       V = Constant::getNullValue(CurTy);
2500       break;
2501     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2502       if (!CurTy->isIntegerTy() || Record.empty())
2503         return error("Invalid record");
2504       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2505       break;
2506     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2507       if (!CurTy->isIntegerTy() || Record.empty())
2508         return error("Invalid record");
2509
2510       APInt VInt =
2511           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2512       V = ConstantInt::get(Context, VInt);
2513
2514       break;
2515     }
2516     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2517       if (Record.empty())
2518         return error("Invalid record");
2519       if (CurTy->isHalfTy())
2520         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2521                                              APInt(16, (uint16_t)Record[0])));
2522       else if (CurTy->isFloatTy())
2523         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2524                                              APInt(32, (uint32_t)Record[0])));
2525       else if (CurTy->isDoubleTy())
2526         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2527                                              APInt(64, Record[0])));
2528       else if (CurTy->isX86_FP80Ty()) {
2529         // Bits are not stored the same way as a normal i80 APInt, compensate.
2530         uint64_t Rearrange[2];
2531         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2532         Rearrange[1] = Record[0] >> 48;
2533         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2534                                              APInt(80, Rearrange)));
2535       } else if (CurTy->isFP128Ty())
2536         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2537                                              APInt(128, Record)));
2538       else if (CurTy->isPPC_FP128Ty())
2539         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2540                                              APInt(128, Record)));
2541       else
2542         V = UndefValue::get(CurTy);
2543       break;
2544     }
2545
2546     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2547       if (Record.empty())
2548         return error("Invalid record");
2549
2550       unsigned Size = Record.size();
2551       SmallVector<Constant*, 16> Elts;
2552
2553       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2554         for (unsigned i = 0; i != Size; ++i)
2555           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2556                                                      STy->getElementType(i)));
2557         V = ConstantStruct::get(STy, Elts);
2558       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2559         Type *EltTy = ATy->getElementType();
2560         for (unsigned i = 0; i != Size; ++i)
2561           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2562         V = ConstantArray::get(ATy, Elts);
2563       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2564         Type *EltTy = VTy->getElementType();
2565         for (unsigned i = 0; i != Size; ++i)
2566           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2567         V = ConstantVector::get(Elts);
2568       } else {
2569         V = UndefValue::get(CurTy);
2570       }
2571       break;
2572     }
2573     case bitc::CST_CODE_STRING:    // STRING: [values]
2574     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2575       if (Record.empty())
2576         return error("Invalid record");
2577
2578       SmallString<16> Elts(Record.begin(), Record.end());
2579       V = ConstantDataArray::getString(Context, Elts,
2580                                        BitCode == bitc::CST_CODE_CSTRING);
2581       break;
2582     }
2583     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2584       if (Record.empty())
2585         return error("Invalid record");
2586
2587       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2588       unsigned Size = Record.size();
2589
2590       if (EltTy->isIntegerTy(8)) {
2591         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2592         if (isa<VectorType>(CurTy))
2593           V = ConstantDataVector::get(Context, Elts);
2594         else
2595           V = ConstantDataArray::get(Context, Elts);
2596       } else if (EltTy->isIntegerTy(16)) {
2597         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2598         if (isa<VectorType>(CurTy))
2599           V = ConstantDataVector::get(Context, Elts);
2600         else
2601           V = ConstantDataArray::get(Context, Elts);
2602       } else if (EltTy->isIntegerTy(32)) {
2603         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2604         if (isa<VectorType>(CurTy))
2605           V = ConstantDataVector::get(Context, Elts);
2606         else
2607           V = ConstantDataArray::get(Context, Elts);
2608       } else if (EltTy->isIntegerTy(64)) {
2609         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2610         if (isa<VectorType>(CurTy))
2611           V = ConstantDataVector::get(Context, Elts);
2612         else
2613           V = ConstantDataArray::get(Context, Elts);
2614       } else if (EltTy->isFloatTy()) {
2615         SmallVector<float, 16> Elts(Size);
2616         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2617         if (isa<VectorType>(CurTy))
2618           V = ConstantDataVector::get(Context, Elts);
2619         else
2620           V = ConstantDataArray::get(Context, Elts);
2621       } else if (EltTy->isDoubleTy()) {
2622         SmallVector<double, 16> Elts(Size);
2623         std::transform(Record.begin(), Record.end(), Elts.begin(),
2624                        BitsToDouble);
2625         if (isa<VectorType>(CurTy))
2626           V = ConstantDataVector::get(Context, Elts);
2627         else
2628           V = ConstantDataArray::get(Context, Elts);
2629       } else {
2630         return error("Invalid type for value");
2631       }
2632       break;
2633     }
2634
2635     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2636       if (Record.size() < 3)
2637         return error("Invalid record");
2638       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2639       if (Opc < 0) {
2640         V = UndefValue::get(CurTy);  // Unknown binop.
2641       } else {
2642         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2643         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2644         unsigned Flags = 0;
2645         if (Record.size() >= 4) {
2646           if (Opc == Instruction::Add ||
2647               Opc == Instruction::Sub ||
2648               Opc == Instruction::Mul ||
2649               Opc == Instruction::Shl) {
2650             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2651               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2652             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2653               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2654           } else if (Opc == Instruction::SDiv ||
2655                      Opc == Instruction::UDiv ||
2656                      Opc == Instruction::LShr ||
2657                      Opc == Instruction::AShr) {
2658             if (Record[3] & (1 << bitc::PEO_EXACT))
2659               Flags |= SDivOperator::IsExact;
2660           }
2661         }
2662         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2663       }
2664       break;
2665     }
2666     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2667       if (Record.size() < 3)
2668         return error("Invalid record");
2669       int Opc = getDecodedCastOpcode(Record[0]);
2670       if (Opc < 0) {
2671         V = UndefValue::get(CurTy);  // Unknown cast.
2672       } else {
2673         Type *OpTy = getTypeByID(Record[1]);
2674         if (!OpTy)
2675           return error("Invalid record");
2676         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2677         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2678         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2679       }
2680       break;
2681     }
2682     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2683     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2684       unsigned OpNum = 0;
2685       Type *PointeeType = nullptr;
2686       if (Record.size() % 2)
2687         PointeeType = getTypeByID(Record[OpNum++]);
2688       SmallVector<Constant*, 16> Elts;
2689       while (OpNum != Record.size()) {
2690         Type *ElTy = getTypeByID(Record[OpNum++]);
2691         if (!ElTy)
2692           return error("Invalid record");
2693         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2694       }
2695
2696       if (PointeeType &&
2697           PointeeType !=
2698               cast<SequentialType>(Elts[0]->getType()->getScalarType())
2699                   ->getElementType())
2700         return error("Explicit gep operator type does not match pointee type "
2701                      "of pointer operand");
2702
2703       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2704       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2705                                          BitCode ==
2706                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
2707       break;
2708     }
2709     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2710       if (Record.size() < 3)
2711         return error("Invalid record");
2712
2713       Type *SelectorTy = Type::getInt1Ty(Context);
2714
2715       // The selector might be an i1 or an <n x i1>
2716       // Get the type from the ValueList before getting a forward ref.
2717       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2718         if (Value *V = ValueList[Record[0]])
2719           if (SelectorTy != V->getType())
2720             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2721
2722       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2723                                                               SelectorTy),
2724                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2725                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2726       break;
2727     }
2728     case bitc::CST_CODE_CE_EXTRACTELT
2729         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2730       if (Record.size() < 3)
2731         return error("Invalid record");
2732       VectorType *OpTy =
2733         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2734       if (!OpTy)
2735         return error("Invalid record");
2736       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2737       Constant *Op1 = nullptr;
2738       if (Record.size() == 4) {
2739         Type *IdxTy = getTypeByID(Record[2]);
2740         if (!IdxTy)
2741           return error("Invalid record");
2742         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2743       } else // TODO: Remove with llvm 4.0
2744         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2745       if (!Op1)
2746         return error("Invalid record");
2747       V = ConstantExpr::getExtractElement(Op0, Op1);
2748       break;
2749     }
2750     case bitc::CST_CODE_CE_INSERTELT
2751         : { // CE_INSERTELT: [opval, opval, opty, opval]
2752       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2753       if (Record.size() < 3 || !OpTy)
2754         return error("Invalid record");
2755       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2756       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2757                                                   OpTy->getElementType());
2758       Constant *Op2 = nullptr;
2759       if (Record.size() == 4) {
2760         Type *IdxTy = getTypeByID(Record[2]);
2761         if (!IdxTy)
2762           return error("Invalid record");
2763         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2764       } else // TODO: Remove with llvm 4.0
2765         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2766       if (!Op2)
2767         return error("Invalid record");
2768       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2769       break;
2770     }
2771     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2772       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2773       if (Record.size() < 3 || !OpTy)
2774         return error("Invalid record");
2775       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2776       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2777       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2778                                                  OpTy->getNumElements());
2779       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2780       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2781       break;
2782     }
2783     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2784       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2785       VectorType *OpTy =
2786         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2787       if (Record.size() < 4 || !RTy || !OpTy)
2788         return error("Invalid record");
2789       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2790       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2791       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2792                                                  RTy->getNumElements());
2793       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2794       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2795       break;
2796     }
2797     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2798       if (Record.size() < 4)
2799         return error("Invalid record");
2800       Type *OpTy = getTypeByID(Record[0]);
2801       if (!OpTy)
2802         return error("Invalid record");
2803       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2804       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2805
2806       if (OpTy->isFPOrFPVectorTy())
2807         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2808       else
2809         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2810       break;
2811     }
2812     // This maintains backward compatibility, pre-asm dialect keywords.
2813     // FIXME: Remove with the 4.0 release.
2814     case bitc::CST_CODE_INLINEASM_OLD: {
2815       if (Record.size() < 2)
2816         return error("Invalid record");
2817       std::string AsmStr, ConstrStr;
2818       bool HasSideEffects = Record[0] & 1;
2819       bool IsAlignStack = Record[0] >> 1;
2820       unsigned AsmStrSize = Record[1];
2821       if (2+AsmStrSize >= Record.size())
2822         return error("Invalid record");
2823       unsigned ConstStrSize = Record[2+AsmStrSize];
2824       if (3+AsmStrSize+ConstStrSize > Record.size())
2825         return error("Invalid record");
2826
2827       for (unsigned i = 0; i != AsmStrSize; ++i)
2828         AsmStr += (char)Record[2+i];
2829       for (unsigned i = 0; i != ConstStrSize; ++i)
2830         ConstrStr += (char)Record[3+AsmStrSize+i];
2831       PointerType *PTy = cast<PointerType>(CurTy);
2832       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2833                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2834       break;
2835     }
2836     // This version adds support for the asm dialect keywords (e.g.,
2837     // inteldialect).
2838     case bitc::CST_CODE_INLINEASM: {
2839       if (Record.size() < 2)
2840         return error("Invalid record");
2841       std::string AsmStr, ConstrStr;
2842       bool HasSideEffects = Record[0] & 1;
2843       bool IsAlignStack = (Record[0] >> 1) & 1;
2844       unsigned AsmDialect = Record[0] >> 2;
2845       unsigned AsmStrSize = Record[1];
2846       if (2+AsmStrSize >= Record.size())
2847         return error("Invalid record");
2848       unsigned ConstStrSize = Record[2+AsmStrSize];
2849       if (3+AsmStrSize+ConstStrSize > Record.size())
2850         return error("Invalid record");
2851
2852       for (unsigned i = 0; i != AsmStrSize; ++i)
2853         AsmStr += (char)Record[2+i];
2854       for (unsigned i = 0; i != ConstStrSize; ++i)
2855         ConstrStr += (char)Record[3+AsmStrSize+i];
2856       PointerType *PTy = cast<PointerType>(CurTy);
2857       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2858                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2859                          InlineAsm::AsmDialect(AsmDialect));
2860       break;
2861     }
2862     case bitc::CST_CODE_BLOCKADDRESS:{
2863       if (Record.size() < 3)
2864         return error("Invalid record");
2865       Type *FnTy = getTypeByID(Record[0]);
2866       if (!FnTy)
2867         return error("Invalid record");
2868       Function *Fn =
2869         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2870       if (!Fn)
2871         return error("Invalid record");
2872
2873       // Don't let Fn get dematerialized.
2874       BlockAddressesTaken.insert(Fn);
2875
2876       // If the function is already parsed we can insert the block address right
2877       // away.
2878       BasicBlock *BB;
2879       unsigned BBID = Record[2];
2880       if (!BBID)
2881         // Invalid reference to entry block.
2882         return error("Invalid ID");
2883       if (!Fn->empty()) {
2884         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2885         for (size_t I = 0, E = BBID; I != E; ++I) {
2886           if (BBI == BBE)
2887             return error("Invalid ID");
2888           ++BBI;
2889         }
2890         BB = &*BBI;
2891       } else {
2892         // Otherwise insert a placeholder and remember it so it can be inserted
2893         // when the function is parsed.
2894         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2895         if (FwdBBs.empty())
2896           BasicBlockFwdRefQueue.push_back(Fn);
2897         if (FwdBBs.size() < BBID + 1)
2898           FwdBBs.resize(BBID + 1);
2899         if (!FwdBBs[BBID])
2900           FwdBBs[BBID] = BasicBlock::Create(Context);
2901         BB = FwdBBs[BBID];
2902       }
2903       V = BlockAddress::get(Fn, BB);
2904       break;
2905     }
2906     }
2907
2908     if (ValueList.assignValue(V, NextCstNo))
2909       return error("Invalid forward reference");
2910     ++NextCstNo;
2911   }
2912 }
2913
2914 std::error_code BitcodeReader::parseUseLists() {
2915   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2916     return error("Invalid record");
2917
2918   // Read all the records.
2919   SmallVector<uint64_t, 64> Record;
2920   while (1) {
2921     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2922
2923     switch (Entry.Kind) {
2924     case BitstreamEntry::SubBlock: // Handled for us already.
2925     case BitstreamEntry::Error:
2926       return error("Malformed block");
2927     case BitstreamEntry::EndBlock:
2928       return std::error_code();
2929     case BitstreamEntry::Record:
2930       // The interesting case.
2931       break;
2932     }
2933
2934     // Read a use list record.
2935     Record.clear();
2936     bool IsBB = false;
2937     switch (Stream.readRecord(Entry.ID, Record)) {
2938     default:  // Default behavior: unknown type.
2939       break;
2940     case bitc::USELIST_CODE_BB:
2941       IsBB = true;
2942       // fallthrough
2943     case bitc::USELIST_CODE_DEFAULT: {
2944       unsigned RecordLength = Record.size();
2945       if (RecordLength < 3)
2946         // Records should have at least an ID and two indexes.
2947         return error("Invalid record");
2948       unsigned ID = Record.back();
2949       Record.pop_back();
2950
2951       Value *V;
2952       if (IsBB) {
2953         assert(ID < FunctionBBs.size() && "Basic block not found");
2954         V = FunctionBBs[ID];
2955       } else
2956         V = ValueList[ID];
2957       unsigned NumUses = 0;
2958       SmallDenseMap<const Use *, unsigned, 16> Order;
2959       for (const Use &U : V->uses()) {
2960         if (++NumUses > Record.size())
2961           break;
2962         Order[&U] = Record[NumUses - 1];
2963       }
2964       if (Order.size() != Record.size() || NumUses > Record.size())
2965         // Mismatches can happen if the functions are being materialized lazily
2966         // (out-of-order), or a value has been upgraded.
2967         break;
2968
2969       V->sortUseList([&](const Use &L, const Use &R) {
2970         return Order.lookup(&L) < Order.lookup(&R);
2971       });
2972       break;
2973     }
2974     }
2975   }
2976 }
2977
2978 /// When we see the block for metadata, remember where it is and then skip it.
2979 /// This lets us lazily deserialize the metadata.
2980 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2981   // Save the current stream state.
2982   uint64_t CurBit = Stream.GetCurrentBitNo();
2983   DeferredMetadataInfo.push_back(CurBit);
2984
2985   // Skip over the block for now.
2986   if (Stream.SkipBlock())
2987     return error("Invalid record");
2988   return std::error_code();
2989 }
2990
2991 std::error_code BitcodeReader::materializeMetadata() {
2992   for (uint64_t BitPos : DeferredMetadataInfo) {
2993     // Move the bit stream to the saved position.
2994     Stream.JumpToBit(BitPos);
2995     if (std::error_code EC = parseMetadata())
2996       return EC;
2997   }
2998   DeferredMetadataInfo.clear();
2999   return std::error_code();
3000 }
3001
3002 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3003
3004 /// When we see the block for a function body, remember where it is and then
3005 /// skip it.  This lets us lazily deserialize the functions.
3006 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3007   // Get the function we are talking about.
3008   if (FunctionsWithBodies.empty())
3009     return error("Insufficient function protos");
3010
3011   Function *Fn = FunctionsWithBodies.back();
3012   FunctionsWithBodies.pop_back();
3013
3014   // Save the current stream state.
3015   uint64_t CurBit = Stream.GetCurrentBitNo();
3016   assert(
3017       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3018       "Mismatch between VST and scanned function offsets");
3019   DeferredFunctionInfo[Fn] = CurBit;
3020
3021   // Skip over the function block for now.
3022   if (Stream.SkipBlock())
3023     return error("Invalid record");
3024   return std::error_code();
3025 }
3026
3027 std::error_code BitcodeReader::globalCleanup() {
3028   // Patch the initializers for globals and aliases up.
3029   resolveGlobalAndAliasInits();
3030   if (!GlobalInits.empty() || !AliasInits.empty())
3031     return error("Malformed global initializer set");
3032
3033   // Look for intrinsic functions which need to be upgraded at some point
3034   for (Function &F : *TheModule) {
3035     Function *NewFn;
3036     if (UpgradeIntrinsicFunction(&F, NewFn))
3037       UpgradedIntrinsics[&F] = NewFn;
3038   }
3039
3040   // Look for global variables which need to be renamed.
3041   for (GlobalVariable &GV : TheModule->globals())
3042     UpgradeGlobalVariable(&GV);
3043
3044   // Force deallocation of memory for these vectors to favor the client that
3045   // want lazy deserialization.
3046   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3047   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3048   return std::error_code();
3049 }
3050
3051 /// Support for lazy parsing of function bodies. This is required if we
3052 /// either have an old bitcode file without a VST forward declaration record,
3053 /// or if we have an anonymous function being materialized, since anonymous
3054 /// functions do not have a name and are therefore not in the VST.
3055 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3056   Stream.JumpToBit(NextUnreadBit);
3057
3058   if (Stream.AtEndOfStream())
3059     return error("Could not find function in stream");
3060
3061   if (!SeenFirstFunctionBody)
3062     return error("Trying to materialize functions before seeing function blocks");
3063
3064   // An old bitcode file with the symbol table at the end would have
3065   // finished the parse greedily.
3066   assert(SeenValueSymbolTable);
3067
3068   SmallVector<uint64_t, 64> Record;
3069
3070   while (1) {
3071     BitstreamEntry Entry = Stream.advance();
3072     switch (Entry.Kind) {
3073     default:
3074       return error("Expect SubBlock");
3075     case BitstreamEntry::SubBlock:
3076       switch (Entry.ID) {
3077       default:
3078         return error("Expect function block");
3079       case bitc::FUNCTION_BLOCK_ID:
3080         if (std::error_code EC = rememberAndSkipFunctionBody())
3081           return EC;
3082         NextUnreadBit = Stream.GetCurrentBitNo();
3083         return std::error_code();
3084       }
3085     }
3086   }
3087 }
3088
3089 std::error_code BitcodeReader::parseBitcodeVersion() {
3090   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3091     return error("Invalid record");
3092
3093   // Read all the records.
3094   SmallVector<uint64_t, 64> Record;
3095   while (1) {
3096     BitstreamEntry Entry = Stream.advance();
3097
3098     switch (Entry.Kind) {
3099     default:
3100     case BitstreamEntry::Error:
3101       return error("Malformed block");
3102     case BitstreamEntry::EndBlock:
3103       return std::error_code();
3104     case BitstreamEntry::Record:
3105       // The interesting case.
3106       break;
3107     }
3108
3109     // Read a record.
3110     Record.clear();
3111     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3112     switch (BitCode) {
3113     default: // Default behavior: reject
3114       return error("Invalid value");
3115     case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION:      [strchr x
3116                                              // N]
3117       convertToString(Record, 0, ProducerIdentification);
3118       break;
3119     }
3120     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH:      [epoch#]
3121       unsigned epoch = (unsigned)Record[0];
3122       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3123         return error(
3124           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3125           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3126       }
3127     }
3128     }
3129   }
3130 }
3131
3132 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3133                                            bool ShouldLazyLoadMetadata) {
3134   if (ResumeBit)
3135     Stream.JumpToBit(ResumeBit);
3136   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3137     return error("Invalid record");
3138
3139   SmallVector<uint64_t, 64> Record;
3140   std::vector<std::string> SectionTable;
3141   std::vector<std::string> GCTable;
3142
3143   // Read all the records for this module.
3144   while (1) {
3145     BitstreamEntry Entry = Stream.advance();
3146
3147     switch (Entry.Kind) {
3148     case BitstreamEntry::Error:
3149       return error("Malformed block");
3150     case BitstreamEntry::EndBlock:
3151       return globalCleanup();
3152
3153     case BitstreamEntry::SubBlock:
3154       switch (Entry.ID) {
3155       default:  // Skip unknown content.
3156         if (Stream.SkipBlock())
3157           return error("Invalid record");
3158         break;
3159       case bitc::BLOCKINFO_BLOCK_ID:
3160         if (Stream.ReadBlockInfoBlock())
3161           return error("Malformed block");
3162         break;
3163       case bitc::PARAMATTR_BLOCK_ID:
3164         if (std::error_code EC = parseAttributeBlock())
3165           return EC;
3166         break;
3167       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3168         if (std::error_code EC = parseAttributeGroupBlock())
3169           return EC;
3170         break;
3171       case bitc::TYPE_BLOCK_ID_NEW:
3172         if (std::error_code EC = parseTypeTable())
3173           return EC;
3174         break;
3175       case bitc::VALUE_SYMTAB_BLOCK_ID:
3176         if (!SeenValueSymbolTable) {
3177           // Either this is an old form VST without function index and an
3178           // associated VST forward declaration record (which would have caused
3179           // the VST to be jumped to and parsed before it was encountered
3180           // normally in the stream), or there were no function blocks to
3181           // trigger an earlier parsing of the VST.
3182           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3183           if (std::error_code EC = parseValueSymbolTable())
3184             return EC;
3185           SeenValueSymbolTable = true;
3186         } else {
3187           // We must have had a VST forward declaration record, which caused
3188           // the parser to jump to and parse the VST earlier.
3189           assert(VSTOffset > 0);
3190           if (Stream.SkipBlock())
3191             return error("Invalid record");
3192         }
3193         break;
3194       case bitc::CONSTANTS_BLOCK_ID:
3195         if (std::error_code EC = parseConstants())
3196           return EC;
3197         if (std::error_code EC = resolveGlobalAndAliasInits())
3198           return EC;
3199         break;
3200       case bitc::METADATA_BLOCK_ID:
3201         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3202           if (std::error_code EC = rememberAndSkipMetadata())
3203             return EC;
3204           break;
3205         }
3206         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3207         if (std::error_code EC = parseMetadata())
3208           return EC;
3209         break;
3210       case bitc::FUNCTION_BLOCK_ID:
3211         // If this is the first function body we've seen, reverse the
3212         // FunctionsWithBodies list.
3213         if (!SeenFirstFunctionBody) {
3214           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3215           if (std::error_code EC = globalCleanup())
3216             return EC;
3217           SeenFirstFunctionBody = true;
3218         }
3219
3220         if (VSTOffset > 0) {
3221           // If we have a VST forward declaration record, make sure we
3222           // parse the VST now if we haven't already. It is needed to
3223           // set up the DeferredFunctionInfo vector for lazy reading.
3224           if (!SeenValueSymbolTable) {
3225             if (std::error_code EC =
3226                     BitcodeReader::parseValueSymbolTable(VSTOffset))
3227               return EC;
3228             SeenValueSymbolTable = true;
3229             // Fall through so that we record the NextUnreadBit below.
3230             // This is necessary in case we have an anonymous function that
3231             // is later materialized. Since it will not have a VST entry we
3232             // need to fall back to the lazy parse to find its offset.
3233           } else {
3234             // If we have a VST forward declaration record, but have already
3235             // parsed the VST (just above, when the first function body was
3236             // encountered here), then we are resuming the parse after
3237             // materializing functions. The ResumeBit points to the
3238             // start of the last function block recorded in the
3239             // DeferredFunctionInfo map. Skip it.
3240             if (Stream.SkipBlock())
3241               return error("Invalid record");
3242             continue;
3243           }
3244         }
3245
3246         // Support older bitcode files that did not have the function
3247         // index in the VST, nor a VST forward declaration record, as
3248         // well as anonymous functions that do not have VST entries.
3249         // Build the DeferredFunctionInfo vector on the fly.
3250         if (std::error_code EC = rememberAndSkipFunctionBody())
3251           return EC;
3252
3253         // Suspend parsing when we reach the function bodies. Subsequent
3254         // materialization calls will resume it when necessary. If the bitcode
3255         // file is old, the symbol table will be at the end instead and will not
3256         // have been seen yet. In this case, just finish the parse now.
3257         if (SeenValueSymbolTable) {
3258           NextUnreadBit = Stream.GetCurrentBitNo();
3259           return std::error_code();
3260         }
3261         break;
3262       case bitc::USELIST_BLOCK_ID:
3263         if (std::error_code EC = parseUseLists())
3264           return EC;
3265         break;
3266       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3267         if (std::error_code EC = parseOperandBundleTags())
3268           return EC;
3269         break;
3270       }
3271       continue;
3272
3273     case BitstreamEntry::Record:
3274       // The interesting case.
3275       break;
3276     }
3277
3278
3279     // Read a record.
3280     auto BitCode = Stream.readRecord(Entry.ID, Record);
3281     switch (BitCode) {
3282     default: break;  // Default behavior, ignore unknown content.
3283     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
3284       if (Record.size() < 1)
3285         return error("Invalid record");
3286       // Only version #0 and #1 are supported so far.
3287       unsigned module_version = Record[0];
3288       switch (module_version) {
3289         default:
3290           return error("Invalid value");
3291         case 0:
3292           UseRelativeIDs = false;
3293           break;
3294         case 1:
3295           UseRelativeIDs = true;
3296           break;
3297       }
3298       break;
3299     }
3300     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3301       std::string S;
3302       if (convertToString(Record, 0, S))
3303         return error("Invalid record");
3304       TheModule->setTargetTriple(S);
3305       break;
3306     }
3307     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3308       std::string S;
3309       if (convertToString(Record, 0, S))
3310         return error("Invalid record");
3311       TheModule->setDataLayout(S);
3312       break;
3313     }
3314     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3315       std::string S;
3316       if (convertToString(Record, 0, S))
3317         return error("Invalid record");
3318       TheModule->setModuleInlineAsm(S);
3319       break;
3320     }
3321     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3322       // FIXME: Remove in 4.0.
3323       std::string S;
3324       if (convertToString(Record, 0, S))
3325         return error("Invalid record");
3326       // Ignore value.
3327       break;
3328     }
3329     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3330       std::string S;
3331       if (convertToString(Record, 0, S))
3332         return error("Invalid record");
3333       SectionTable.push_back(S);
3334       break;
3335     }
3336     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3337       std::string S;
3338       if (convertToString(Record, 0, S))
3339         return error("Invalid record");
3340       GCTable.push_back(S);
3341       break;
3342     }
3343     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3344       if (Record.size() < 2)
3345         return error("Invalid record");
3346       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3347       unsigned ComdatNameSize = Record[1];
3348       std::string ComdatName;
3349       ComdatName.reserve(ComdatNameSize);
3350       for (unsigned i = 0; i != ComdatNameSize; ++i)
3351         ComdatName += (char)Record[2 + i];
3352       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3353       C->setSelectionKind(SK);
3354       ComdatList.push_back(C);
3355       break;
3356     }
3357     // GLOBALVAR: [pointer type, isconst, initid,
3358     //             linkage, alignment, section, visibility, threadlocal,
3359     //             unnamed_addr, externally_initialized, dllstorageclass,
3360     //             comdat]
3361     case bitc::MODULE_CODE_GLOBALVAR: {
3362       if (Record.size() < 6)
3363         return error("Invalid record");
3364       Type *Ty = getTypeByID(Record[0]);
3365       if (!Ty)
3366         return error("Invalid record");
3367       bool isConstant = Record[1] & 1;
3368       bool explicitType = Record[1] & 2;
3369       unsigned AddressSpace;
3370       if (explicitType) {
3371         AddressSpace = Record[1] >> 2;
3372       } else {
3373         if (!Ty->isPointerTy())
3374           return error("Invalid type for value");
3375         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3376         Ty = cast<PointerType>(Ty)->getElementType();
3377       }
3378
3379       uint64_t RawLinkage = Record[3];
3380       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3381       unsigned Alignment;
3382       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3383         return EC;
3384       std::string Section;
3385       if (Record[5]) {
3386         if (Record[5]-1 >= SectionTable.size())
3387           return error("Invalid ID");
3388         Section = SectionTable[Record[5]-1];
3389       }
3390       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3391       // Local linkage must have default visibility.
3392       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3393         // FIXME: Change to an error if non-default in 4.0.
3394         Visibility = getDecodedVisibility(Record[6]);
3395
3396       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3397       if (Record.size() > 7)
3398         TLM = getDecodedThreadLocalMode(Record[7]);
3399
3400       bool UnnamedAddr = false;
3401       if (Record.size() > 8)
3402         UnnamedAddr = Record[8];
3403
3404       bool ExternallyInitialized = false;
3405       if (Record.size() > 9)
3406         ExternallyInitialized = Record[9];
3407
3408       GlobalVariable *NewGV =
3409         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3410                            TLM, AddressSpace, ExternallyInitialized);
3411       NewGV->setAlignment(Alignment);
3412       if (!Section.empty())
3413         NewGV->setSection(Section);
3414       NewGV->setVisibility(Visibility);
3415       NewGV->setUnnamedAddr(UnnamedAddr);
3416
3417       if (Record.size() > 10)
3418         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3419       else
3420         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3421
3422       ValueList.push_back(NewGV);
3423
3424       // Remember which value to use for the global initializer.
3425       if (unsigned InitID = Record[2])
3426         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3427
3428       if (Record.size() > 11) {
3429         if (unsigned ComdatID = Record[11]) {
3430           if (ComdatID > ComdatList.size())
3431             return error("Invalid global variable comdat ID");
3432           NewGV->setComdat(ComdatList[ComdatID - 1]);
3433         }
3434       } else if (hasImplicitComdat(RawLinkage)) {
3435         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3436       }
3437       break;
3438     }
3439     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
3440     //             alignment, section, visibility, gc, unnamed_addr,
3441     //             prologuedata, dllstorageclass, comdat, prefixdata]
3442     case bitc::MODULE_CODE_FUNCTION: {
3443       if (Record.size() < 8)
3444         return error("Invalid record");
3445       Type *Ty = getTypeByID(Record[0]);
3446       if (!Ty)
3447         return error("Invalid record");
3448       if (auto *PTy = dyn_cast<PointerType>(Ty))
3449         Ty = PTy->getElementType();
3450       auto *FTy = dyn_cast<FunctionType>(Ty);
3451       if (!FTy)
3452         return error("Invalid type for value");
3453       auto CC = static_cast<CallingConv::ID>(Record[1]);
3454       if (CC & ~CallingConv::MaxID)
3455         return error("Invalid calling convention ID");
3456
3457       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3458                                         "", TheModule);
3459
3460       Func->setCallingConv(CC);
3461       bool isProto = Record[2];
3462       uint64_t RawLinkage = Record[3];
3463       Func->setLinkage(getDecodedLinkage(RawLinkage));
3464       Func->setAttributes(getAttributes(Record[4]));
3465
3466       unsigned Alignment;
3467       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3468         return EC;
3469       Func->setAlignment(Alignment);
3470       if (Record[6]) {
3471         if (Record[6]-1 >= SectionTable.size())
3472           return error("Invalid ID");
3473         Func->setSection(SectionTable[Record[6]-1]);
3474       }
3475       // Local linkage must have default visibility.
3476       if (!Func->hasLocalLinkage())
3477         // FIXME: Change to an error if non-default in 4.0.
3478         Func->setVisibility(getDecodedVisibility(Record[7]));
3479       if (Record.size() > 8 && Record[8]) {
3480         if (Record[8]-1 >= GCTable.size())
3481           return error("Invalid ID");
3482         Func->setGC(GCTable[Record[8]-1].c_str());
3483       }
3484       bool UnnamedAddr = false;
3485       if (Record.size() > 9)
3486         UnnamedAddr = Record[9];
3487       Func->setUnnamedAddr(UnnamedAddr);
3488       if (Record.size() > 10 && Record[10] != 0)
3489         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3490
3491       if (Record.size() > 11)
3492         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3493       else
3494         upgradeDLLImportExportLinkage(Func, RawLinkage);
3495
3496       if (Record.size() > 12) {
3497         if (unsigned ComdatID = Record[12]) {
3498           if (ComdatID > ComdatList.size())
3499             return error("Invalid function comdat ID");
3500           Func->setComdat(ComdatList[ComdatID - 1]);
3501         }
3502       } else if (hasImplicitComdat(RawLinkage)) {
3503         Func->setComdat(reinterpret_cast<Comdat *>(1));
3504       }
3505
3506       if (Record.size() > 13 && Record[13] != 0)
3507         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3508
3509       if (Record.size() > 14 && Record[14] != 0)
3510         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3511
3512       ValueList.push_back(Func);
3513
3514       // If this is a function with a body, remember the prototype we are
3515       // creating now, so that we can match up the body with them later.
3516       if (!isProto) {
3517         Func->setIsMaterializable(true);
3518         FunctionsWithBodies.push_back(Func);
3519         DeferredFunctionInfo[Func] = 0;
3520       }
3521       break;
3522     }
3523     // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3524     // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3525     case bitc::MODULE_CODE_ALIAS:
3526     case bitc::MODULE_CODE_ALIAS_OLD: {
3527       bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3528       if (Record.size() < (3 + (unsigned)NewRecord))
3529         return error("Invalid record");
3530       unsigned OpNum = 0;
3531       Type *Ty = getTypeByID(Record[OpNum++]);
3532       if (!Ty)
3533         return error("Invalid record");
3534
3535       unsigned AddrSpace;
3536       if (!NewRecord) {
3537         auto *PTy = dyn_cast<PointerType>(Ty);
3538         if (!PTy)
3539           return error("Invalid type for value");
3540         Ty = PTy->getElementType();
3541         AddrSpace = PTy->getAddressSpace();
3542       } else {
3543         AddrSpace = Record[OpNum++];
3544       }
3545
3546       auto Val = Record[OpNum++];
3547       auto Linkage = Record[OpNum++];
3548       auto *NewGA = GlobalAlias::create(
3549           Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3550       // Old bitcode files didn't have visibility field.
3551       // Local linkage must have default visibility.
3552       if (OpNum != Record.size()) {
3553         auto VisInd = OpNum++;
3554         if (!NewGA->hasLocalLinkage())
3555           // FIXME: Change to an error if non-default in 4.0.
3556           NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3557       }
3558       if (OpNum != Record.size())
3559         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3560       else
3561         upgradeDLLImportExportLinkage(NewGA, Linkage);
3562       if (OpNum != Record.size())
3563         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3564       if (OpNum != Record.size())
3565         NewGA->setUnnamedAddr(Record[OpNum++]);
3566       ValueList.push_back(NewGA);
3567       AliasInits.push_back(std::make_pair(NewGA, Val));
3568       break;
3569     }
3570     /// MODULE_CODE_PURGEVALS: [numvals]
3571     case bitc::MODULE_CODE_PURGEVALS:
3572       // Trim down the value list to the specified size.
3573       if (Record.size() < 1 || Record[0] > ValueList.size())
3574         return error("Invalid record");
3575       ValueList.shrinkTo(Record[0]);
3576       break;
3577     /// MODULE_CODE_VSTOFFSET: [offset]
3578     case bitc::MODULE_CODE_VSTOFFSET:
3579       if (Record.size() < 1)
3580         return error("Invalid record");
3581       VSTOffset = Record[0];
3582       break;
3583     }
3584     Record.clear();
3585   }
3586 }
3587
3588 /// Helper to read the header common to all bitcode files.
3589 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3590   // Sniff for the signature.
3591   if (Stream.Read(8) != 'B' ||
3592       Stream.Read(8) != 'C' ||
3593       Stream.Read(4) != 0x0 ||
3594       Stream.Read(4) != 0xC ||
3595       Stream.Read(4) != 0xE ||
3596       Stream.Read(4) != 0xD)
3597     return false;
3598   return true;
3599 }
3600
3601 std::error_code
3602 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3603                                 Module *M, bool ShouldLazyLoadMetadata) {
3604   TheModule = M;
3605
3606   if (std::error_code EC = initStream(std::move(Streamer)))
3607     return EC;
3608
3609   // Sniff for the signature.
3610   if (!hasValidBitcodeHeader(Stream))
3611     return error("Invalid bitcode signature");
3612
3613   // We expect a number of well-defined blocks, though we don't necessarily
3614   // need to understand them all.
3615   while (1) {
3616     if (Stream.AtEndOfStream()) {
3617       // We didn't really read a proper Module.
3618       return error("Malformed IR file");
3619     }
3620
3621     BitstreamEntry Entry =
3622       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3623
3624     if (Entry.Kind != BitstreamEntry::SubBlock)
3625       return error("Malformed block");
3626
3627     if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3628       parseBitcodeVersion();
3629       continue;
3630     }
3631
3632     if (Entry.ID == bitc::MODULE_BLOCK_ID)
3633       return parseModule(0, ShouldLazyLoadMetadata);
3634
3635     if (Stream.SkipBlock())
3636       return error("Invalid record");
3637   }
3638 }
3639
3640 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3641   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3642     return error("Invalid record");
3643
3644   SmallVector<uint64_t, 64> Record;
3645
3646   std::string Triple;
3647   // Read all the records for this module.
3648   while (1) {
3649     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3650
3651     switch (Entry.Kind) {
3652     case BitstreamEntry::SubBlock: // Handled for us already.
3653     case BitstreamEntry::Error:
3654       return error("Malformed block");
3655     case BitstreamEntry::EndBlock:
3656       return Triple;
3657     case BitstreamEntry::Record:
3658       // The interesting case.
3659       break;
3660     }
3661
3662     // Read a record.
3663     switch (Stream.readRecord(Entry.ID, Record)) {
3664     default: break;  // Default behavior, ignore unknown content.
3665     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3666       std::string S;
3667       if (convertToString(Record, 0, S))
3668         return error("Invalid record");
3669       Triple = S;
3670       break;
3671     }
3672     }
3673     Record.clear();
3674   }
3675   llvm_unreachable("Exit infinite loop");
3676 }
3677
3678 ErrorOr<std::string> BitcodeReader::parseTriple() {
3679   if (std::error_code EC = initStream(nullptr))
3680     return EC;
3681
3682   // Sniff for the signature.
3683   if (!hasValidBitcodeHeader(Stream))
3684     return error("Invalid bitcode signature");
3685
3686   // We expect a number of well-defined blocks, though we don't necessarily
3687   // need to understand them all.
3688   while (1) {
3689     BitstreamEntry Entry = Stream.advance();
3690
3691     switch (Entry.Kind) {
3692     case BitstreamEntry::Error:
3693       return error("Malformed block");
3694     case BitstreamEntry::EndBlock:
3695       return std::error_code();
3696
3697     case BitstreamEntry::SubBlock:
3698       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3699         return parseModuleTriple();
3700
3701       // Ignore other sub-blocks.
3702       if (Stream.SkipBlock())
3703         return error("Malformed block");
3704       continue;
3705
3706     case BitstreamEntry::Record:
3707       Stream.skipRecord(Entry.ID);
3708       continue;
3709     }
3710   }
3711 }
3712
3713 /// Parse metadata attachments.
3714 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3715   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3716     return error("Invalid record");
3717
3718   SmallVector<uint64_t, 64> Record;
3719   while (1) {
3720     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3721
3722     switch (Entry.Kind) {
3723     case BitstreamEntry::SubBlock: // Handled for us already.
3724     case BitstreamEntry::Error:
3725       return error("Malformed block");
3726     case BitstreamEntry::EndBlock:
3727       return std::error_code();
3728     case BitstreamEntry::Record:
3729       // The interesting case.
3730       break;
3731     }
3732
3733     // Read a metadata attachment record.
3734     Record.clear();
3735     switch (Stream.readRecord(Entry.ID, Record)) {
3736     default:  // Default behavior: ignore.
3737       break;
3738     case bitc::METADATA_ATTACHMENT: {
3739       unsigned RecordLength = Record.size();
3740       if (Record.empty())
3741         return error("Invalid record");
3742       if (RecordLength % 2 == 0) {
3743         // A function attachment.
3744         for (unsigned I = 0; I != RecordLength; I += 2) {
3745           auto K = MDKindMap.find(Record[I]);
3746           if (K == MDKindMap.end())
3747             return error("Invalid ID");
3748           Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3749           F.setMetadata(K->second, cast<MDNode>(MD));
3750         }
3751         continue;
3752       }
3753
3754       // An instruction attachment.
3755       Instruction *Inst = InstructionList[Record[0]];
3756       for (unsigned i = 1; i != RecordLength; i = i+2) {
3757         unsigned Kind = Record[i];
3758         DenseMap<unsigned, unsigned>::iterator I =
3759           MDKindMap.find(Kind);
3760         if (I == MDKindMap.end())
3761           return error("Invalid ID");
3762         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3763         if (isa<LocalAsMetadata>(Node))
3764           // Drop the attachment.  This used to be legal, but there's no
3765           // upgrade path.
3766           break;
3767         Inst->setMetadata(I->second, cast<MDNode>(Node));
3768         if (I->second == LLVMContext::MD_tbaa)
3769           InstsWithTBAATag.push_back(Inst);
3770       }
3771       break;
3772     }
3773     }
3774   }
3775 }
3776
3777 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3778                                               Type *ValType, Type *PtrType) {
3779   if (!isa<PointerType>(PtrType))
3780     return error(DH, "Load/Store operand is not a pointer type");
3781   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3782
3783   if (ValType && ValType != ElemType)
3784     return error(DH, "Explicit load/store type does not match pointee type of "
3785                      "pointer operand");
3786   if (!PointerType::isLoadableOrStorableType(ElemType))
3787     return error(DH, "Cannot load/store from pointer");
3788   return std::error_code();
3789 }
3790
3791 /// Lazily parse the specified function body block.
3792 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3793   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3794     return error("Invalid record");
3795
3796   InstructionList.clear();
3797   unsigned ModuleValueListSize = ValueList.size();
3798   unsigned ModuleMDValueListSize = MDValueList.size();
3799
3800   // Add all the function arguments to the value table.
3801   for (Argument &I : F->args())
3802     ValueList.push_back(&I);
3803
3804   unsigned NextValueNo = ValueList.size();
3805   BasicBlock *CurBB = nullptr;
3806   unsigned CurBBNo = 0;
3807
3808   DebugLoc LastLoc;
3809   auto getLastInstruction = [&]() -> Instruction * {
3810     if (CurBB && !CurBB->empty())
3811       return &CurBB->back();
3812     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3813              !FunctionBBs[CurBBNo - 1]->empty())
3814       return &FunctionBBs[CurBBNo - 1]->back();
3815     return nullptr;
3816   };
3817
3818   std::vector<OperandBundleDef> OperandBundles;
3819
3820   // Read all the records.
3821   SmallVector<uint64_t, 64> Record;
3822   while (1) {
3823     BitstreamEntry Entry = Stream.advance();
3824
3825     switch (Entry.Kind) {
3826     case BitstreamEntry::Error:
3827       return error("Malformed block");
3828     case BitstreamEntry::EndBlock:
3829       goto OutOfRecordLoop;
3830
3831     case BitstreamEntry::SubBlock:
3832       switch (Entry.ID) {
3833       default:  // Skip unknown content.
3834         if (Stream.SkipBlock())
3835           return error("Invalid record");
3836         break;
3837       case bitc::CONSTANTS_BLOCK_ID:
3838         if (std::error_code EC = parseConstants())
3839           return EC;
3840         NextValueNo = ValueList.size();
3841         break;
3842       case bitc::VALUE_SYMTAB_BLOCK_ID:
3843         if (std::error_code EC = parseValueSymbolTable())
3844           return EC;
3845         break;
3846       case bitc::METADATA_ATTACHMENT_ID:
3847         if (std::error_code EC = parseMetadataAttachment(*F))
3848           return EC;
3849         break;
3850       case bitc::METADATA_BLOCK_ID:
3851         if (std::error_code EC = parseMetadata())
3852           return EC;
3853         break;
3854       case bitc::USELIST_BLOCK_ID:
3855         if (std::error_code EC = parseUseLists())
3856           return EC;
3857         break;
3858       }
3859       continue;
3860
3861     case BitstreamEntry::Record:
3862       // The interesting case.
3863       break;
3864     }
3865
3866     // Read a record.
3867     Record.clear();
3868     Instruction *I = nullptr;
3869     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3870     switch (BitCode) {
3871     default: // Default behavior: reject
3872       return error("Invalid value");
3873     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3874       if (Record.size() < 1 || Record[0] == 0)
3875         return error("Invalid record");
3876       // Create all the basic blocks for the function.
3877       FunctionBBs.resize(Record[0]);
3878
3879       // See if anything took the address of blocks in this function.
3880       auto BBFRI = BasicBlockFwdRefs.find(F);
3881       if (BBFRI == BasicBlockFwdRefs.end()) {
3882         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3883           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3884       } else {
3885         auto &BBRefs = BBFRI->second;
3886         // Check for invalid basic block references.
3887         if (BBRefs.size() > FunctionBBs.size())
3888           return error("Invalid ID");
3889         assert(!BBRefs.empty() && "Unexpected empty array");
3890         assert(!BBRefs.front() && "Invalid reference to entry block");
3891         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3892              ++I)
3893           if (I < RE && BBRefs[I]) {
3894             BBRefs[I]->insertInto(F);
3895             FunctionBBs[I] = BBRefs[I];
3896           } else {
3897             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3898           }
3899
3900         // Erase from the table.
3901         BasicBlockFwdRefs.erase(BBFRI);
3902       }
3903
3904       CurBB = FunctionBBs[0];
3905       continue;
3906     }
3907
3908     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3909       // This record indicates that the last instruction is at the same
3910       // location as the previous instruction with a location.
3911       I = getLastInstruction();
3912
3913       if (!I)
3914         return error("Invalid record");
3915       I->setDebugLoc(LastLoc);
3916       I = nullptr;
3917       continue;
3918
3919     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3920       I = getLastInstruction();
3921       if (!I || Record.size() < 4)
3922         return error("Invalid record");
3923
3924       unsigned Line = Record[0], Col = Record[1];
3925       unsigned ScopeID = Record[2], IAID = Record[3];
3926
3927       MDNode *Scope = nullptr, *IA = nullptr;
3928       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3929       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3930       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3931       I->setDebugLoc(LastLoc);
3932       I = nullptr;
3933       continue;
3934     }
3935
3936     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3937       unsigned OpNum = 0;
3938       Value *LHS, *RHS;
3939       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3940           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3941           OpNum+1 > Record.size())
3942         return error("Invalid record");
3943
3944       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3945       if (Opc == -1)
3946         return error("Invalid record");
3947       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3948       InstructionList.push_back(I);
3949       if (OpNum < Record.size()) {
3950         if (Opc == Instruction::Add ||
3951             Opc == Instruction::Sub ||
3952             Opc == Instruction::Mul ||
3953             Opc == Instruction::Shl) {
3954           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3955             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3956           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3957             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3958         } else if (Opc == Instruction::SDiv ||
3959                    Opc == Instruction::UDiv ||
3960                    Opc == Instruction::LShr ||
3961                    Opc == Instruction::AShr) {
3962           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3963             cast<BinaryOperator>(I)->setIsExact(true);
3964         } else if (isa<FPMathOperator>(I)) {
3965           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3966           if (FMF.any())
3967             I->setFastMathFlags(FMF);
3968         }
3969
3970       }
3971       break;
3972     }
3973     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3974       unsigned OpNum = 0;
3975       Value *Op;
3976       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3977           OpNum+2 != Record.size())
3978         return error("Invalid record");
3979
3980       Type *ResTy = getTypeByID(Record[OpNum]);
3981       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3982       if (Opc == -1 || !ResTy)
3983         return error("Invalid record");
3984       Instruction *Temp = nullptr;
3985       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3986         if (Temp) {
3987           InstructionList.push_back(Temp);
3988           CurBB->getInstList().push_back(Temp);
3989         }
3990       } else {
3991         auto CastOp = (Instruction::CastOps)Opc;
3992         if (!CastInst::castIsValid(CastOp, Op, ResTy))
3993           return error("Invalid cast");
3994         I = CastInst::Create(CastOp, Op, ResTy);
3995       }
3996       InstructionList.push_back(I);
3997       break;
3998     }
3999     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4000     case bitc::FUNC_CODE_INST_GEP_OLD:
4001     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4002       unsigned OpNum = 0;
4003
4004       Type *Ty;
4005       bool InBounds;
4006
4007       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4008         InBounds = Record[OpNum++];
4009         Ty = getTypeByID(Record[OpNum++]);
4010       } else {
4011         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4012         Ty = nullptr;
4013       }
4014
4015       Value *BasePtr;
4016       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4017         return error("Invalid record");
4018
4019       if (!Ty)
4020         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4021                  ->getElementType();
4022       else if (Ty !=
4023                cast<SequentialType>(BasePtr->getType()->getScalarType())
4024                    ->getElementType())
4025         return error(
4026             "Explicit gep type does not match pointee type of pointer operand");
4027
4028       SmallVector<Value*, 16> GEPIdx;
4029       while (OpNum != Record.size()) {
4030         Value *Op;
4031         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4032           return error("Invalid record");
4033         GEPIdx.push_back(Op);
4034       }
4035
4036       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4037
4038       InstructionList.push_back(I);
4039       if (InBounds)
4040         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4041       break;
4042     }
4043
4044     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4045                                        // EXTRACTVAL: [opty, opval, n x indices]
4046       unsigned OpNum = 0;
4047       Value *Agg;
4048       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4049         return error("Invalid record");
4050
4051       unsigned RecSize = Record.size();
4052       if (OpNum == RecSize)
4053         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4054
4055       SmallVector<unsigned, 4> EXTRACTVALIdx;
4056       Type *CurTy = Agg->getType();
4057       for (; OpNum != RecSize; ++OpNum) {
4058         bool IsArray = CurTy->isArrayTy();
4059         bool IsStruct = CurTy->isStructTy();
4060         uint64_t Index = Record[OpNum];
4061
4062         if (!IsStruct && !IsArray)
4063           return error("EXTRACTVAL: Invalid type");
4064         if ((unsigned)Index != Index)
4065           return error("Invalid value");
4066         if (IsStruct && Index >= CurTy->subtypes().size())
4067           return error("EXTRACTVAL: Invalid struct index");
4068         if (IsArray && Index >= CurTy->getArrayNumElements())
4069           return error("EXTRACTVAL: Invalid array index");
4070         EXTRACTVALIdx.push_back((unsigned)Index);
4071
4072         if (IsStruct)
4073           CurTy = CurTy->subtypes()[Index];
4074         else
4075           CurTy = CurTy->subtypes()[0];
4076       }
4077
4078       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4079       InstructionList.push_back(I);
4080       break;
4081     }
4082
4083     case bitc::FUNC_CODE_INST_INSERTVAL: {
4084                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4085       unsigned OpNum = 0;
4086       Value *Agg;
4087       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4088         return error("Invalid record");
4089       Value *Val;
4090       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4091         return error("Invalid record");
4092
4093       unsigned RecSize = Record.size();
4094       if (OpNum == RecSize)
4095         return error("INSERTVAL: Invalid instruction with 0 indices");
4096
4097       SmallVector<unsigned, 4> INSERTVALIdx;
4098       Type *CurTy = Agg->getType();
4099       for (; OpNum != RecSize; ++OpNum) {
4100         bool IsArray = CurTy->isArrayTy();
4101         bool IsStruct = CurTy->isStructTy();
4102         uint64_t Index = Record[OpNum];
4103
4104         if (!IsStruct && !IsArray)
4105           return error("INSERTVAL: Invalid type");
4106         if ((unsigned)Index != Index)
4107           return error("Invalid value");
4108         if (IsStruct && Index >= CurTy->subtypes().size())
4109           return error("INSERTVAL: Invalid struct index");
4110         if (IsArray && Index >= CurTy->getArrayNumElements())
4111           return error("INSERTVAL: Invalid array index");
4112
4113         INSERTVALIdx.push_back((unsigned)Index);
4114         if (IsStruct)
4115           CurTy = CurTy->subtypes()[Index];
4116         else
4117           CurTy = CurTy->subtypes()[0];
4118       }
4119
4120       if (CurTy != Val->getType())
4121         return error("Inserted value type doesn't match aggregate type");
4122
4123       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4124       InstructionList.push_back(I);
4125       break;
4126     }
4127
4128     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4129       // obsolete form of select
4130       // handles select i1 ... in old bitcode
4131       unsigned OpNum = 0;
4132       Value *TrueVal, *FalseVal, *Cond;
4133       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4134           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4135           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4136         return error("Invalid record");
4137
4138       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4139       InstructionList.push_back(I);
4140       break;
4141     }
4142
4143     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4144       // new form of select
4145       // handles select i1 or select [N x i1]
4146       unsigned OpNum = 0;
4147       Value *TrueVal, *FalseVal, *Cond;
4148       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4149           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4150           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4151         return error("Invalid record");
4152
4153       // select condition can be either i1 or [N x i1]
4154       if (VectorType* vector_type =
4155           dyn_cast<VectorType>(Cond->getType())) {
4156         // expect <n x i1>
4157         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4158           return error("Invalid type for value");
4159       } else {
4160         // expect i1
4161         if (Cond->getType() != Type::getInt1Ty(Context))
4162           return error("Invalid type for value");
4163       }
4164
4165       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4166       InstructionList.push_back(I);
4167       break;
4168     }
4169
4170     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4171       unsigned OpNum = 0;
4172       Value *Vec, *Idx;
4173       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4174           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4175         return error("Invalid record");
4176       if (!Vec->getType()->isVectorTy())
4177         return error("Invalid type for value");
4178       I = ExtractElementInst::Create(Vec, Idx);
4179       InstructionList.push_back(I);
4180       break;
4181     }
4182
4183     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4184       unsigned OpNum = 0;
4185       Value *Vec, *Elt, *Idx;
4186       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4187         return error("Invalid record");
4188       if (!Vec->getType()->isVectorTy())
4189         return error("Invalid type for value");
4190       if (popValue(Record, OpNum, NextValueNo,
4191                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4192           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4193         return error("Invalid record");
4194       I = InsertElementInst::Create(Vec, Elt, Idx);
4195       InstructionList.push_back(I);
4196       break;
4197     }
4198
4199     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4200       unsigned OpNum = 0;
4201       Value *Vec1, *Vec2, *Mask;
4202       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4203           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4204         return error("Invalid record");
4205
4206       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4207         return error("Invalid record");
4208       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4209         return error("Invalid type for value");
4210       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4211       InstructionList.push_back(I);
4212       break;
4213     }
4214
4215     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4216       // Old form of ICmp/FCmp returning bool
4217       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4218       // both legal on vectors but had different behaviour.
4219     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4220       // FCmp/ICmp returning bool or vector of bool
4221
4222       unsigned OpNum = 0;
4223       Value *LHS, *RHS;
4224       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4225           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4226         return error("Invalid record");
4227
4228       unsigned PredVal = Record[OpNum];
4229       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4230       FastMathFlags FMF;
4231       if (IsFP && Record.size() > OpNum+1)
4232         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4233
4234       if (OpNum+1 != Record.size())
4235         return error("Invalid record");
4236
4237       if (LHS->getType()->isFPOrFPVectorTy())
4238         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4239       else
4240         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4241
4242       if (FMF.any())
4243         I->setFastMathFlags(FMF);
4244       InstructionList.push_back(I);
4245       break;
4246     }
4247
4248     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4249       {
4250         unsigned Size = Record.size();
4251         if (Size == 0) {
4252           I = ReturnInst::Create(Context);
4253           InstructionList.push_back(I);
4254           break;
4255         }
4256
4257         unsigned OpNum = 0;
4258         Value *Op = nullptr;
4259         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4260           return error("Invalid record");
4261         if (OpNum != Record.size())
4262           return error("Invalid record");
4263
4264         I = ReturnInst::Create(Context, Op);
4265         InstructionList.push_back(I);
4266         break;
4267       }
4268     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4269       if (Record.size() != 1 && Record.size() != 3)
4270         return error("Invalid record");
4271       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4272       if (!TrueDest)
4273         return error("Invalid record");
4274
4275       if (Record.size() == 1) {
4276         I = BranchInst::Create(TrueDest);
4277         InstructionList.push_back(I);
4278       }
4279       else {
4280         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4281         Value *Cond = getValue(Record, 2, NextValueNo,
4282                                Type::getInt1Ty(Context));
4283         if (!FalseDest || !Cond)
4284           return error("Invalid record");
4285         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4286         InstructionList.push_back(I);
4287       }
4288       break;
4289     }
4290     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4291       if (Record.size() != 1 && Record.size() != 2)
4292         return error("Invalid record");
4293       unsigned Idx = 0;
4294       Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4295                                    Type::getTokenTy(Context), OC_CleanupPad);
4296       if (!CleanupPad)
4297         return error("Invalid record");
4298       BasicBlock *UnwindDest = nullptr;
4299       if (Record.size() == 2) {
4300         UnwindDest = getBasicBlock(Record[Idx++]);
4301         if (!UnwindDest)
4302           return error("Invalid record");
4303       }
4304
4305       I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4306                                     UnwindDest);
4307       InstructionList.push_back(I);
4308       break;
4309     }
4310     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4311       if (Record.size() != 2)
4312         return error("Invalid record");
4313       unsigned Idx = 0;
4314       Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4315                                  Type::getTokenTy(Context), OC_CatchPad);
4316       if (!CatchPad)
4317         return error("Invalid record");
4318       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4319       if (!BB)
4320         return error("Invalid record");
4321
4322       I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
4323       InstructionList.push_back(I);
4324       break;
4325     }
4326     case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4327       if (Record.size() < 3)
4328         return error("Invalid record");
4329       unsigned Idx = 0;
4330       BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4331       if (!NormalBB)
4332         return error("Invalid record");
4333       BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4334       if (!UnwindBB)
4335         return error("Invalid record");
4336       unsigned NumArgOperands = Record[Idx++];
4337       SmallVector<Value *, 2> Args;
4338       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4339         Value *Val;
4340         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4341           return error("Invalid record");
4342         Args.push_back(Val);
4343       }
4344       if (Record.size() != Idx)
4345         return error("Invalid record");
4346
4347       I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
4348       InstructionList.push_back(I);
4349       break;
4350     }
4351     case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4352       if (Record.size() < 1)
4353         return error("Invalid record");
4354       unsigned Idx = 0;
4355       bool HasUnwindDest = !!Record[Idx++];
4356       BasicBlock *UnwindDest = nullptr;
4357       if (HasUnwindDest) {
4358         if (Idx == Record.size())
4359           return error("Invalid record");
4360         UnwindDest = getBasicBlock(Record[Idx++]);
4361         if (!UnwindDest)
4362           return error("Invalid record");
4363       }
4364       unsigned NumArgOperands = Record[Idx++];
4365       SmallVector<Value *, 2> Args;
4366       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4367         Value *Val;
4368         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4369           return error("Invalid record");
4370         Args.push_back(Val);
4371       }
4372       if (Record.size() != Idx)
4373         return error("Invalid record");
4374
4375       I = TerminatePadInst::Create(Context, UnwindDest, Args);
4376       InstructionList.push_back(I);
4377       break;
4378     }
4379     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4380       if (Record.size() < 1)
4381         return error("Invalid record");
4382       unsigned Idx = 0;
4383       unsigned NumArgOperands = Record[Idx++];
4384       SmallVector<Value *, 2> Args;
4385       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4386         Value *Val;
4387         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4388           return error("Invalid record");
4389         Args.push_back(Val);
4390       }
4391       if (Record.size() != Idx)
4392         return error("Invalid record");
4393
4394       I = CleanupPadInst::Create(Context, Args);
4395       InstructionList.push_back(I);
4396       break;
4397     }
4398     case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4399       if (Record.size() > 1)
4400         return error("Invalid record");
4401       BasicBlock *BB = nullptr;
4402       if (Record.size() == 1) {
4403         BB = getBasicBlock(Record[0]);
4404         if (!BB)
4405           return error("Invalid record");
4406       }
4407       I = CatchEndPadInst::Create(Context, BB);
4408       InstructionList.push_back(I);
4409       break;
4410     }
4411     case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4412       if (Record.size() != 1 && Record.size() != 2)
4413         return error("Invalid record");
4414       unsigned Idx = 0;
4415       Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4416                                    Type::getTokenTy(Context), OC_CleanupPad);
4417       if (!CleanupPad)
4418         return error("Invalid record");
4419
4420       BasicBlock *BB = nullptr;
4421       if (Record.size() == 2) {
4422         BB = getBasicBlock(Record[Idx++]);
4423         if (!BB)
4424           return error("Invalid record");
4425       }
4426       I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4427       InstructionList.push_back(I);
4428       break;
4429     }
4430     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4431       // Check magic
4432       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4433         // "New" SwitchInst format with case ranges. The changes to write this
4434         // format were reverted but we still recognize bitcode that uses it.
4435         // Hopefully someday we will have support for case ranges and can use
4436         // this format again.
4437
4438         Type *OpTy = getTypeByID(Record[1]);
4439         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4440
4441         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4442         BasicBlock *Default = getBasicBlock(Record[3]);
4443         if (!OpTy || !Cond || !Default)
4444           return error("Invalid record");
4445
4446         unsigned NumCases = Record[4];
4447
4448         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4449         InstructionList.push_back(SI);
4450
4451         unsigned CurIdx = 5;
4452         for (unsigned i = 0; i != NumCases; ++i) {
4453           SmallVector<ConstantInt*, 1> CaseVals;
4454           unsigned NumItems = Record[CurIdx++];
4455           for (unsigned ci = 0; ci != NumItems; ++ci) {
4456             bool isSingleNumber = Record[CurIdx++];
4457
4458             APInt Low;
4459             unsigned ActiveWords = 1;
4460             if (ValueBitWidth > 64)
4461               ActiveWords = Record[CurIdx++];
4462             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4463                                 ValueBitWidth);
4464             CurIdx += ActiveWords;
4465
4466             if (!isSingleNumber) {
4467               ActiveWords = 1;
4468               if (ValueBitWidth > 64)
4469                 ActiveWords = Record[CurIdx++];
4470               APInt High = readWideAPInt(
4471                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4472               CurIdx += ActiveWords;
4473
4474               // FIXME: It is not clear whether values in the range should be
4475               // compared as signed or unsigned values. The partially
4476               // implemented changes that used this format in the past used
4477               // unsigned comparisons.
4478               for ( ; Low.ule(High); ++Low)
4479                 CaseVals.push_back(ConstantInt::get(Context, Low));
4480             } else
4481               CaseVals.push_back(ConstantInt::get(Context, Low));
4482           }
4483           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4484           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4485                  cve = CaseVals.end(); cvi != cve; ++cvi)
4486             SI->addCase(*cvi, DestBB);
4487         }
4488         I = SI;
4489         break;
4490       }
4491
4492       // Old SwitchInst format without case ranges.
4493
4494       if (Record.size() < 3 || (Record.size() & 1) == 0)
4495         return error("Invalid record");
4496       Type *OpTy = getTypeByID(Record[0]);
4497       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4498       BasicBlock *Default = getBasicBlock(Record[2]);
4499       if (!OpTy || !Cond || !Default)
4500         return error("Invalid record");
4501       unsigned NumCases = (Record.size()-3)/2;
4502       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4503       InstructionList.push_back(SI);
4504       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4505         ConstantInt *CaseVal =
4506           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4507         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4508         if (!CaseVal || !DestBB) {
4509           delete SI;
4510           return error("Invalid record");
4511         }
4512         SI->addCase(CaseVal, DestBB);
4513       }
4514       I = SI;
4515       break;
4516     }
4517     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4518       if (Record.size() < 2)
4519         return error("Invalid record");
4520       Type *OpTy = getTypeByID(Record[0]);
4521       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4522       if (!OpTy || !Address)
4523         return error("Invalid record");
4524       unsigned NumDests = Record.size()-2;
4525       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4526       InstructionList.push_back(IBI);
4527       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4528         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4529           IBI->addDestination(DestBB);
4530         } else {
4531           delete IBI;
4532           return error("Invalid record");
4533         }
4534       }
4535       I = IBI;
4536       break;
4537     }
4538
4539     case bitc::FUNC_CODE_INST_INVOKE: {
4540       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4541       if (Record.size() < 4)
4542         return error("Invalid record");
4543       unsigned OpNum = 0;
4544       AttributeSet PAL = getAttributes(Record[OpNum++]);
4545       unsigned CCInfo = Record[OpNum++];
4546       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4547       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4548
4549       FunctionType *FTy = nullptr;
4550       if (CCInfo >> 13 & 1 &&
4551           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4552         return error("Explicit invoke type is not a function type");
4553
4554       Value *Callee;
4555       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4556         return error("Invalid record");
4557
4558       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4559       if (!CalleeTy)
4560         return error("Callee is not a pointer");
4561       if (!FTy) {
4562         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4563         if (!FTy)
4564           return error("Callee is not of pointer to function type");
4565       } else if (CalleeTy->getElementType() != FTy)
4566         return error("Explicit invoke type does not match pointee type of "
4567                      "callee operand");
4568       if (Record.size() < FTy->getNumParams() + OpNum)
4569         return error("Insufficient operands to call");
4570
4571       SmallVector<Value*, 16> Ops;
4572       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4573         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4574                                FTy->getParamType(i)));
4575         if (!Ops.back())
4576           return error("Invalid record");
4577       }
4578
4579       if (!FTy->isVarArg()) {
4580         if (Record.size() != OpNum)
4581           return error("Invalid record");
4582       } else {
4583         // Read type/value pairs for varargs params.
4584         while (OpNum != Record.size()) {
4585           Value *Op;
4586           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4587             return error("Invalid record");
4588           Ops.push_back(Op);
4589         }
4590       }
4591
4592       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4593       OperandBundles.clear();
4594       InstructionList.push_back(I);
4595       cast<InvokeInst>(I)->setCallingConv(
4596           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4597       cast<InvokeInst>(I)->setAttributes(PAL);
4598       break;
4599     }
4600     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4601       unsigned Idx = 0;
4602       Value *Val = nullptr;
4603       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4604         return error("Invalid record");
4605       I = ResumeInst::Create(Val);
4606       InstructionList.push_back(I);
4607       break;
4608     }
4609     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4610       I = new UnreachableInst(Context);
4611       InstructionList.push_back(I);
4612       break;
4613     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4614       if (Record.size() < 1 || ((Record.size()-1)&1))
4615         return error("Invalid record");
4616       Type *Ty = getTypeByID(Record[0]);
4617       if (!Ty)
4618         return error("Invalid record");
4619
4620       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4621       InstructionList.push_back(PN);
4622
4623       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4624         Value *V;
4625         // With the new function encoding, it is possible that operands have
4626         // negative IDs (for forward references).  Use a signed VBR
4627         // representation to keep the encoding small.
4628         if (UseRelativeIDs)
4629           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4630         else
4631           V = getValue(Record, 1+i, NextValueNo, Ty);
4632         BasicBlock *BB = getBasicBlock(Record[2+i]);
4633         if (!V || !BB)
4634           return error("Invalid record");
4635         PN->addIncoming(V, BB);
4636       }
4637       I = PN;
4638       break;
4639     }
4640
4641     case bitc::FUNC_CODE_INST_LANDINGPAD:
4642     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4643       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4644       unsigned Idx = 0;
4645       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4646         if (Record.size() < 3)
4647           return error("Invalid record");
4648       } else {
4649         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4650         if (Record.size() < 4)
4651           return error("Invalid record");
4652       }
4653       Type *Ty = getTypeByID(Record[Idx++]);
4654       if (!Ty)
4655         return error("Invalid record");
4656       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4657         Value *PersFn = nullptr;
4658         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4659           return error("Invalid record");
4660
4661         if (!F->hasPersonalityFn())
4662           F->setPersonalityFn(cast<Constant>(PersFn));
4663         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4664           return error("Personality function mismatch");
4665       }
4666
4667       bool IsCleanup = !!Record[Idx++];
4668       unsigned NumClauses = Record[Idx++];
4669       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4670       LP->setCleanup(IsCleanup);
4671       for (unsigned J = 0; J != NumClauses; ++J) {
4672         LandingPadInst::ClauseType CT =
4673           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4674         Value *Val;
4675
4676         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4677           delete LP;
4678           return error("Invalid record");
4679         }
4680
4681         assert((CT != LandingPadInst::Catch ||
4682                 !isa<ArrayType>(Val->getType())) &&
4683                "Catch clause has a invalid type!");
4684         assert((CT != LandingPadInst::Filter ||
4685                 isa<ArrayType>(Val->getType())) &&
4686                "Filter clause has invalid type!");
4687         LP->addClause(cast<Constant>(Val));
4688       }
4689
4690       I = LP;
4691       InstructionList.push_back(I);
4692       break;
4693     }
4694
4695     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4696       if (Record.size() != 4)
4697         return error("Invalid record");
4698       uint64_t AlignRecord = Record[3];
4699       const uint64_t InAllocaMask = uint64_t(1) << 5;
4700       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4701       // Reserve bit 7 for SwiftError flag.
4702       // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4703       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4704       bool InAlloca = AlignRecord & InAllocaMask;
4705       Type *Ty = getTypeByID(Record[0]);
4706       if ((AlignRecord & ExplicitTypeMask) == 0) {
4707         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4708         if (!PTy)
4709           return error("Old-style alloca with a non-pointer type");
4710         Ty = PTy->getElementType();
4711       }
4712       Type *OpTy = getTypeByID(Record[1]);
4713       Value *Size = getFnValueByID(Record[2], OpTy);
4714       unsigned Align;
4715       if (std::error_code EC =
4716               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4717         return EC;
4718       }
4719       if (!Ty || !Size)
4720         return error("Invalid record");
4721       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4722       AI->setUsedWithInAlloca(InAlloca);
4723       I = AI;
4724       InstructionList.push_back(I);
4725       break;
4726     }
4727     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4728       unsigned OpNum = 0;
4729       Value *Op;
4730       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4731           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4732         return error("Invalid record");
4733
4734       Type *Ty = nullptr;
4735       if (OpNum + 3 == Record.size())
4736         Ty = getTypeByID(Record[OpNum++]);
4737       if (std::error_code EC =
4738               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4739         return EC;
4740       if (!Ty)
4741         Ty = cast<PointerType>(Op->getType())->getElementType();
4742
4743       unsigned Align;
4744       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4745         return EC;
4746       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4747
4748       InstructionList.push_back(I);
4749       break;
4750     }
4751     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4752        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4753       unsigned OpNum = 0;
4754       Value *Op;
4755       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4756           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4757         return error("Invalid record");
4758
4759       Type *Ty = nullptr;
4760       if (OpNum + 5 == Record.size())
4761         Ty = getTypeByID(Record[OpNum++]);
4762       if (std::error_code EC =
4763               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4764         return EC;
4765       if (!Ty)
4766         Ty = cast<PointerType>(Op->getType())->getElementType();
4767
4768       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4769       if (Ordering == NotAtomic || Ordering == Release ||
4770           Ordering == AcquireRelease)
4771         return error("Invalid record");
4772       if (Ordering != NotAtomic && Record[OpNum] == 0)
4773         return error("Invalid record");
4774       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4775
4776       unsigned Align;
4777       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4778         return EC;
4779       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4780
4781       InstructionList.push_back(I);
4782       break;
4783     }
4784     case bitc::FUNC_CODE_INST_STORE:
4785     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4786       unsigned OpNum = 0;
4787       Value *Val, *Ptr;
4788       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4789           (BitCode == bitc::FUNC_CODE_INST_STORE
4790                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4791                : popValue(Record, OpNum, NextValueNo,
4792                           cast<PointerType>(Ptr->getType())->getElementType(),
4793                           Val)) ||
4794           OpNum + 2 != Record.size())
4795         return error("Invalid record");
4796
4797       if (std::error_code EC = typeCheckLoadStoreInst(
4798               DiagnosticHandler, Val->getType(), Ptr->getType()))
4799         return EC;
4800       unsigned Align;
4801       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4802         return EC;
4803       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4804       InstructionList.push_back(I);
4805       break;
4806     }
4807     case bitc::FUNC_CODE_INST_STOREATOMIC:
4808     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4809       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4810       unsigned OpNum = 0;
4811       Value *Val, *Ptr;
4812       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4813           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4814                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4815                : popValue(Record, OpNum, NextValueNo,
4816                           cast<PointerType>(Ptr->getType())->getElementType(),
4817                           Val)) ||
4818           OpNum + 4 != Record.size())
4819         return error("Invalid record");
4820
4821       if (std::error_code EC = typeCheckLoadStoreInst(
4822               DiagnosticHandler, Val->getType(), Ptr->getType()))
4823         return EC;
4824       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4825       if (Ordering == NotAtomic || Ordering == Acquire ||
4826           Ordering == AcquireRelease)
4827         return error("Invalid record");
4828       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4829       if (Ordering != NotAtomic && Record[OpNum] == 0)
4830         return error("Invalid record");
4831
4832       unsigned Align;
4833       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4834         return EC;
4835       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4836       InstructionList.push_back(I);
4837       break;
4838     }
4839     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4840     case bitc::FUNC_CODE_INST_CMPXCHG: {
4841       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4842       //          failureordering?, isweak?]
4843       unsigned OpNum = 0;
4844       Value *Ptr, *Cmp, *New;
4845       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4846           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4847                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4848                : popValue(Record, OpNum, NextValueNo,
4849                           cast<PointerType>(Ptr->getType())->getElementType(),
4850                           Cmp)) ||
4851           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4852           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4853         return error("Invalid record");
4854       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4855       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4856         return error("Invalid record");
4857       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4858
4859       if (std::error_code EC = typeCheckLoadStoreInst(
4860               DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4861         return EC;
4862       AtomicOrdering FailureOrdering;
4863       if (Record.size() < 7)
4864         FailureOrdering =
4865             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4866       else
4867         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4868
4869       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4870                                 SynchScope);
4871       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4872
4873       if (Record.size() < 8) {
4874         // Before weak cmpxchgs existed, the instruction simply returned the
4875         // value loaded from memory, so bitcode files from that era will be
4876         // expecting the first component of a modern cmpxchg.
4877         CurBB->getInstList().push_back(I);
4878         I = ExtractValueInst::Create(I, 0);
4879       } else {
4880         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4881       }
4882
4883       InstructionList.push_back(I);
4884       break;
4885     }
4886     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4887       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4888       unsigned OpNum = 0;
4889       Value *Ptr, *Val;
4890       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4891           popValue(Record, OpNum, NextValueNo,
4892                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4893           OpNum+4 != Record.size())
4894         return error("Invalid record");
4895       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4896       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4897           Operation > AtomicRMWInst::LAST_BINOP)
4898         return error("Invalid record");
4899       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4900       if (Ordering == NotAtomic || Ordering == Unordered)
4901         return error("Invalid record");
4902       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4903       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4904       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4905       InstructionList.push_back(I);
4906       break;
4907     }
4908     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4909       if (2 != Record.size())
4910         return error("Invalid record");
4911       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4912       if (Ordering == NotAtomic || Ordering == Unordered ||
4913           Ordering == Monotonic)
4914         return error("Invalid record");
4915       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4916       I = new FenceInst(Context, Ordering, SynchScope);
4917       InstructionList.push_back(I);
4918       break;
4919     }
4920     case bitc::FUNC_CODE_INST_CALL: {
4921       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4922       if (Record.size() < 3)
4923         return error("Invalid record");
4924
4925       unsigned OpNum = 0;
4926       AttributeSet PAL = getAttributes(Record[OpNum++]);
4927       unsigned CCInfo = Record[OpNum++];
4928
4929       FunctionType *FTy = nullptr;
4930       if (CCInfo >> 15 & 1 &&
4931           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4932         return error("Explicit call type is not a function type");
4933
4934       Value *Callee;
4935       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4936         return error("Invalid record");
4937
4938       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4939       if (!OpTy)
4940         return error("Callee is not a pointer type");
4941       if (!FTy) {
4942         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4943         if (!FTy)
4944           return error("Callee is not of pointer to function type");
4945       } else if (OpTy->getElementType() != FTy)
4946         return error("Explicit call type does not match pointee type of "
4947                      "callee operand");
4948       if (Record.size() < FTy->getNumParams() + OpNum)
4949         return error("Insufficient operands to call");
4950
4951       SmallVector<Value*, 16> Args;
4952       // Read the fixed params.
4953       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4954         if (FTy->getParamType(i)->isLabelTy())
4955           Args.push_back(getBasicBlock(Record[OpNum]));
4956         else
4957           Args.push_back(getValue(Record, OpNum, NextValueNo,
4958                                   FTy->getParamType(i)));
4959         if (!Args.back())
4960           return error("Invalid record");
4961       }
4962
4963       // Read type/value pairs for varargs params.
4964       if (!FTy->isVarArg()) {
4965         if (OpNum != Record.size())
4966           return error("Invalid record");
4967       } else {
4968         while (OpNum != Record.size()) {
4969           Value *Op;
4970           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4971             return error("Invalid record");
4972           Args.push_back(Op);
4973         }
4974       }
4975
4976       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4977       OperandBundles.clear();
4978       InstructionList.push_back(I);
4979       cast<CallInst>(I)->setCallingConv(
4980           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> 1));
4981       CallInst::TailCallKind TCK = CallInst::TCK_None;
4982       if (CCInfo & 1)
4983         TCK = CallInst::TCK_Tail;
4984       if (CCInfo & (1 << 14))
4985         TCK = CallInst::TCK_MustTail;
4986       cast<CallInst>(I)->setTailCallKind(TCK);
4987       cast<CallInst>(I)->setAttributes(PAL);
4988       break;
4989     }
4990     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4991       if (Record.size() < 3)
4992         return error("Invalid record");
4993       Type *OpTy = getTypeByID(Record[0]);
4994       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4995       Type *ResTy = getTypeByID(Record[2]);
4996       if (!OpTy || !Op || !ResTy)
4997         return error("Invalid record");
4998       I = new VAArgInst(Op, ResTy);
4999       InstructionList.push_back(I);
5000       break;
5001     }
5002
5003     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5004       // A call or an invoke can be optionally prefixed with some variable
5005       // number of operand bundle blocks.  These blocks are read into
5006       // OperandBundles and consumed at the next call or invoke instruction.
5007
5008       if (Record.size() < 1 || Record[0] >= BundleTags.size())
5009         return error("Invalid record");
5010
5011       OperandBundles.emplace_back();
5012       OperandBundles.back().Tag = BundleTags[Record[0]];
5013
5014       std::vector<Value *> &Inputs = OperandBundles.back().Inputs;
5015
5016       unsigned OpNum = 1;
5017       while (OpNum != Record.size()) {
5018         Value *Op;
5019         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5020           return error("Invalid record");
5021         Inputs.push_back(Op);
5022       }
5023
5024       continue;
5025     }
5026     }
5027
5028     // Add instruction to end of current BB.  If there is no current BB, reject
5029     // this file.
5030     if (!CurBB) {
5031       delete I;
5032       return error("Invalid instruction with no BB");
5033     }
5034     if (!OperandBundles.empty()) {
5035       delete I;
5036       return error("Operand bundles found with no consumer");
5037     }
5038     CurBB->getInstList().push_back(I);
5039
5040     // If this was a terminator instruction, move to the next block.
5041     if (isa<TerminatorInst>(I)) {
5042       ++CurBBNo;
5043       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5044     }
5045
5046     // Non-void values get registered in the value table for future use.
5047     if (I && !I->getType()->isVoidTy())
5048       if (ValueList.assignValue(I, NextValueNo++))
5049         return error("Invalid forward reference");
5050   }
5051
5052 OutOfRecordLoop:
5053
5054   if (!OperandBundles.empty())
5055     return error("Operand bundles found with no consumer");
5056
5057   // Check the function list for unresolved values.
5058   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5059     if (!A->getParent()) {
5060       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5061       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5062         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5063           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5064           delete A;
5065         }
5066       }
5067       return error("Never resolved value found in function");
5068     }
5069   }
5070
5071   // FIXME: Check for unresolved forward-declared metadata references
5072   // and clean up leaks.
5073
5074   // Trim the value list down to the size it was before we parsed this function.
5075   ValueList.shrinkTo(ModuleValueListSize);
5076   MDValueList.shrinkTo(ModuleMDValueListSize);
5077   std::vector<BasicBlock*>().swap(FunctionBBs);
5078   return std::error_code();
5079 }
5080
5081 /// Find the function body in the bitcode stream
5082 std::error_code BitcodeReader::findFunctionInStream(
5083     Function *F,
5084     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5085   while (DeferredFunctionInfoIterator->second == 0) {
5086     // This is the fallback handling for the old format bitcode that
5087     // didn't contain the function index in the VST, or when we have
5088     // an anonymous function which would not have a VST entry.
5089     // Assert that we have one of those two cases.
5090     assert(VSTOffset == 0 || !F->hasName());
5091     // Parse the next body in the stream and set its position in the
5092     // DeferredFunctionInfo map.
5093     if (std::error_code EC = rememberAndSkipFunctionBodies())
5094       return EC;
5095   }
5096   return std::error_code();
5097 }
5098
5099 //===----------------------------------------------------------------------===//
5100 // GVMaterializer implementation
5101 //===----------------------------------------------------------------------===//
5102
5103 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5104
5105 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5106   if (std::error_code EC = materializeMetadata())
5107     return EC;
5108
5109   Function *F = dyn_cast<Function>(GV);
5110   // If it's not a function or is already material, ignore the request.
5111   if (!F || !F->isMaterializable())
5112     return std::error_code();
5113
5114   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5115   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5116   // If its position is recorded as 0, its body is somewhere in the stream
5117   // but we haven't seen it yet.
5118   if (DFII->second == 0)
5119     if (std::error_code EC = findFunctionInStream(F, DFII))
5120       return EC;
5121
5122   // Move the bit stream to the saved position of the deferred function body.
5123   Stream.JumpToBit(DFII->second);
5124
5125   if (std::error_code EC = parseFunctionBody(F))
5126     return EC;
5127   F->setIsMaterializable(false);
5128
5129   if (StripDebugInfo)
5130     stripDebugInfo(*F);
5131
5132   // Upgrade any old intrinsic calls in the function.
5133   for (auto &I : UpgradedIntrinsics) {
5134     for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5135       User *U = *UI;
5136       ++UI;
5137       if (CallInst *CI = dyn_cast<CallInst>(U))
5138         UpgradeIntrinsicCall(CI, I.second);
5139     }
5140   }
5141
5142   // Bring in any functions that this function forward-referenced via
5143   // blockaddresses.
5144   return materializeForwardReferencedFunctions();
5145 }
5146
5147 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5148   const Function *F = dyn_cast<Function>(GV);
5149   if (!F || F->isDeclaration())
5150     return false;
5151
5152   // Dematerializing F would leave dangling references that wouldn't be
5153   // reconnected on re-materialization.
5154   if (BlockAddressesTaken.count(F))
5155     return false;
5156
5157   return DeferredFunctionInfo.count(const_cast<Function*>(F));
5158 }
5159
5160 void BitcodeReader::dematerialize(GlobalValue *GV) {
5161   Function *F = dyn_cast<Function>(GV);
5162   // If this function isn't dematerializable, this is a noop.
5163   if (!F || !isDematerializable(F))
5164     return;
5165
5166   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
5167
5168   // Just forget the function body, we can remat it later.
5169   F->dropAllReferences();
5170   F->setIsMaterializable(true);
5171 }
5172
5173 std::error_code BitcodeReader::materializeModule(Module *M) {
5174   assert(M == TheModule &&
5175          "Can only Materialize the Module this BitcodeReader is attached to.");
5176
5177   if (std::error_code EC = materializeMetadata())
5178     return EC;
5179
5180   // Promise to materialize all forward references.
5181   WillMaterializeAllForwardRefs = true;
5182
5183   // Iterate over the module, deserializing any functions that are still on
5184   // disk.
5185   for (Function &F : *TheModule) {
5186     if (std::error_code EC = materialize(&F))
5187       return EC;
5188   }
5189   // At this point, if there are any function bodies, parse the rest of
5190   // the bits in the module past the last function block we have recorded
5191   // through either lazy scanning or the VST.
5192   if (LastFunctionBlockBit || NextUnreadBit)
5193     parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5194                                                      : NextUnreadBit);
5195
5196   // Check that all block address forward references got resolved (as we
5197   // promised above).
5198   if (!BasicBlockFwdRefs.empty())
5199     return error("Never resolved function from blockaddress");
5200
5201   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5202   // delete the old functions to clean up. We can't do this unless the entire
5203   // module is materialized because there could always be another function body
5204   // with calls to the old function.
5205   for (auto &I : UpgradedIntrinsics) {
5206     for (auto *U : I.first->users()) {
5207       if (CallInst *CI = dyn_cast<CallInst>(U))
5208         UpgradeIntrinsicCall(CI, I.second);
5209     }
5210     if (!I.first->use_empty())
5211       I.first->replaceAllUsesWith(I.second);
5212     I.first->eraseFromParent();
5213   }
5214   UpgradedIntrinsics.clear();
5215
5216   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5217     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5218
5219   UpgradeDebugInfo(*M);
5220   return std::error_code();
5221 }
5222
5223 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5224   return IdentifiedStructTypes;
5225 }
5226
5227 std::error_code
5228 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5229   if (Streamer)
5230     return initLazyStream(std::move(Streamer));
5231   return initStreamFromBuffer();
5232 }
5233
5234 std::error_code BitcodeReader::initStreamFromBuffer() {
5235   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5236   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5237
5238   if (Buffer->getBufferSize() & 3)
5239     return error("Invalid bitcode signature");
5240
5241   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5242   // The magic number is 0x0B17C0DE stored in little endian.
5243   if (isBitcodeWrapper(BufPtr, BufEnd))
5244     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5245       return error("Invalid bitcode wrapper header");
5246
5247   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5248   Stream.init(&*StreamFile);
5249
5250   return std::error_code();
5251 }
5252
5253 std::error_code
5254 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5255   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5256   // see it.
5257   auto OwnedBytes =
5258       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5259   StreamingMemoryObject &Bytes = *OwnedBytes;
5260   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5261   Stream.init(&*StreamFile);
5262
5263   unsigned char buf[16];
5264   if (Bytes.readBytes(buf, 16, 0) != 16)
5265     return error("Invalid bitcode signature");
5266
5267   if (!isBitcode(buf, buf + 16))
5268     return error("Invalid bitcode signature");
5269
5270   if (isBitcodeWrapper(buf, buf + 4)) {
5271     const unsigned char *bitcodeStart = buf;
5272     const unsigned char *bitcodeEnd = buf + 16;
5273     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5274     Bytes.dropLeadingBytes(bitcodeStart - buf);
5275     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5276   }
5277   return std::error_code();
5278 }
5279
5280 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5281                                                   const Twine &Message) {
5282   return ::error(DiagnosticHandler, make_error_code(E), Message);
5283 }
5284
5285 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5286   return ::error(DiagnosticHandler,
5287                  make_error_code(BitcodeError::CorruptedBitcode), Message);
5288 }
5289
5290 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5291   return ::error(DiagnosticHandler, make_error_code(E));
5292 }
5293
5294 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5295     MemoryBuffer *Buffer, LLVMContext &Context,
5296     DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5297     bool CheckFuncSummaryPresenceOnly)
5298     : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5299       Buffer(Buffer), IsLazy(IsLazy),
5300       CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5301
5302 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5303     LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler,
5304     bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5305     : DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
5306       Buffer(nullptr), IsLazy(IsLazy),
5307       CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5308
5309 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5310
5311 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5312
5313 // Specialized value symbol table parser used when reading function index
5314 // blocks where we don't actually create global values.
5315 // At the end of this routine the function index is populated with a map
5316 // from function name to FunctionInfo. The function info contains
5317 // the function block's bitcode offset as well as the offset into the
5318 // function summary section.
5319 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5320   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5321     return error("Invalid record");
5322
5323   SmallVector<uint64_t, 64> Record;
5324
5325   // Read all the records for this value table.
5326   SmallString<128> ValueName;
5327   while (1) {
5328     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5329
5330     switch (Entry.Kind) {
5331     case BitstreamEntry::SubBlock: // Handled for us already.
5332     case BitstreamEntry::Error:
5333       return error("Malformed block");
5334     case BitstreamEntry::EndBlock:
5335       return std::error_code();
5336     case BitstreamEntry::Record:
5337       // The interesting case.
5338       break;
5339     }
5340
5341     // Read a record.
5342     Record.clear();
5343     switch (Stream.readRecord(Entry.ID, Record)) {
5344     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5345       break;
5346     case bitc::VST_CODE_FNENTRY: {
5347       // VST_FNENTRY: [valueid, offset, namechar x N]
5348       if (convertToString(Record, 2, ValueName))
5349         return error("Invalid record");
5350       unsigned ValueID = Record[0];
5351       uint64_t FuncOffset = Record[1];
5352       std::unique_ptr<FunctionInfo> FuncInfo =
5353           llvm::make_unique<FunctionInfo>(FuncOffset);
5354       if (foundFuncSummary() && !IsLazy) {
5355         DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5356             SummaryMap.find(ValueID);
5357         assert(SMI != SummaryMap.end() && "Summary info not found");
5358         FuncInfo->setFunctionSummary(std::move(SMI->second));
5359       }
5360       TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5361
5362       ValueName.clear();
5363       break;
5364     }
5365     case bitc::VST_CODE_COMBINED_FNENTRY: {
5366       // VST_FNENTRY: [offset, namechar x N]
5367       if (convertToString(Record, 1, ValueName))
5368         return error("Invalid record");
5369       uint64_t FuncSummaryOffset = Record[0];
5370       std::unique_ptr<FunctionInfo> FuncInfo =
5371           llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5372       if (foundFuncSummary() && !IsLazy) {
5373         DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5374             SummaryMap.find(FuncSummaryOffset);
5375         assert(SMI != SummaryMap.end() && "Summary info not found");
5376         FuncInfo->setFunctionSummary(std::move(SMI->second));
5377       }
5378       TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5379
5380       ValueName.clear();
5381       break;
5382     }
5383     }
5384   }
5385 }
5386
5387 // Parse just the blocks needed for function index building out of the module.
5388 // At the end of this routine the function Index is populated with a map
5389 // from function name to FunctionInfo. The function info contains
5390 // either the parsed function summary information (when parsing summaries
5391 // eagerly), or just to the function summary record's offset
5392 // if parsing lazily (IsLazy).
5393 std::error_code FunctionIndexBitcodeReader::parseModule() {
5394   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5395     return error("Invalid record");
5396
5397   // Read the function index for this module.
5398   while (1) {
5399     BitstreamEntry Entry = Stream.advance();
5400
5401     switch (Entry.Kind) {
5402     case BitstreamEntry::Error:
5403       return error("Malformed block");
5404     case BitstreamEntry::EndBlock:
5405       return std::error_code();
5406
5407     case BitstreamEntry::SubBlock:
5408       if (CheckFuncSummaryPresenceOnly) {
5409         if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID)
5410           SeenFuncSummary = true;
5411         if (Stream.SkipBlock())
5412           return error("Invalid record");
5413         // No need to parse the rest since we found the summary.
5414         return std::error_code();
5415       }
5416       switch (Entry.ID) {
5417       default: // Skip unknown content.
5418         if (Stream.SkipBlock())
5419           return error("Invalid record");
5420         break;
5421       case bitc::BLOCKINFO_BLOCK_ID:
5422         // Need to parse these to get abbrev ids (e.g. for VST)
5423         if (Stream.ReadBlockInfoBlock())
5424           return error("Malformed block");
5425         break;
5426       case bitc::VALUE_SYMTAB_BLOCK_ID:
5427         if (std::error_code EC = parseValueSymbolTable())
5428           return EC;
5429         break;
5430       case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5431         SeenFuncSummary = true;
5432         if (IsLazy) {
5433           // Lazy parsing of summary info, skip it.
5434           if (Stream.SkipBlock())
5435             return error("Invalid record");
5436         } else if (std::error_code EC = parseEntireSummary())
5437           return EC;
5438         break;
5439       case bitc::MODULE_STRTAB_BLOCK_ID:
5440         if (std::error_code EC = parseModuleStringTable())
5441           return EC;
5442         break;
5443       }
5444       continue;
5445
5446     case BitstreamEntry::Record:
5447       Stream.skipRecord(Entry.ID);
5448       continue;
5449     }
5450   }
5451 }
5452
5453 // Eagerly parse the entire function summary block (i.e. for all functions
5454 // in the index). This populates the FunctionSummary objects in
5455 // the index.
5456 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5457   if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5458     return error("Invalid record");
5459
5460   SmallVector<uint64_t, 64> Record;
5461
5462   while (1) {
5463     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5464
5465     switch (Entry.Kind) {
5466     case BitstreamEntry::SubBlock: // Handled for us already.
5467     case BitstreamEntry::Error:
5468       return error("Malformed block");
5469     case BitstreamEntry::EndBlock:
5470       return std::error_code();
5471     case BitstreamEntry::Record:
5472       // The interesting case.
5473       break;
5474     }
5475
5476     // Read a record. The record format depends on whether this
5477     // is a per-module index or a combined index file. In the per-module
5478     // case the records contain the associated value's ID for correlation
5479     // with VST entries. In the combined index the correlation is done
5480     // via the bitcode offset of the summary records (which were saved
5481     // in the combined index VST entries). The records also contain
5482     // information used for ThinLTO renaming and importing.
5483     Record.clear();
5484     uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5485     switch (Stream.readRecord(Entry.ID, Record)) {
5486     default: // Default behavior: ignore.
5487       break;
5488     // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5489     case bitc::FS_CODE_PERMODULE_ENTRY: {
5490       unsigned ValueID = Record[0];
5491       bool IsLocal = Record[1];
5492       unsigned InstCount = Record[2];
5493       std::unique_ptr<FunctionSummary> FS =
5494           llvm::make_unique<FunctionSummary>(InstCount);
5495       FS->setLocalFunction(IsLocal);
5496       // The module path string ref set in the summary must be owned by the
5497       // index's module string table. Since we don't have a module path
5498       // string table section in the per-module index, we create a single
5499       // module path string table entry with an empty (0) ID to take
5500       // ownership.
5501       FS->setModulePath(
5502           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5503       SummaryMap[ValueID] = std::move(FS);
5504     }
5505     // FS_COMBINED_ENTRY: [modid, instcount]
5506     case bitc::FS_CODE_COMBINED_ENTRY: {
5507       uint64_t ModuleId = Record[0];
5508       unsigned InstCount = Record[1];
5509       std::unique_ptr<FunctionSummary> FS =
5510           llvm::make_unique<FunctionSummary>(InstCount);
5511       FS->setModulePath(ModuleIdMap[ModuleId]);
5512       SummaryMap[CurRecordBit] = std::move(FS);
5513     }
5514     }
5515   }
5516   llvm_unreachable("Exit infinite loop");
5517 }
5518
5519 // Parse the  module string table block into the Index.
5520 // This populates the ModulePathStringTable map in the index.
5521 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5522   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5523     return error("Invalid record");
5524
5525   SmallVector<uint64_t, 64> Record;
5526
5527   SmallString<128> ModulePath;
5528   while (1) {
5529     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5530
5531     switch (Entry.Kind) {
5532     case BitstreamEntry::SubBlock: // Handled for us already.
5533     case BitstreamEntry::Error:
5534       return error("Malformed block");
5535     case BitstreamEntry::EndBlock:
5536       return std::error_code();
5537     case BitstreamEntry::Record:
5538       // The interesting case.
5539       break;
5540     }
5541
5542     Record.clear();
5543     switch (Stream.readRecord(Entry.ID, Record)) {
5544     default: // Default behavior: ignore.
5545       break;
5546     case bitc::MST_CODE_ENTRY: {
5547       // MST_ENTRY: [modid, namechar x N]
5548       if (convertToString(Record, 1, ModulePath))
5549         return error("Invalid record");
5550       uint64_t ModuleId = Record[0];
5551       StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5552       ModuleIdMap[ModuleId] = ModulePathInMap;
5553       ModulePath.clear();
5554       break;
5555     }
5556     }
5557   }
5558   llvm_unreachable("Exit infinite loop");
5559 }
5560
5561 // Parse the function info index from the bitcode streamer into the given index.
5562 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5563     std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5564   TheIndex = I;
5565
5566   if (std::error_code EC = initStream(std::move(Streamer)))
5567     return EC;
5568
5569   // Sniff for the signature.
5570   if (!hasValidBitcodeHeader(Stream))
5571     return error("Invalid bitcode signature");
5572
5573   // We expect a number of well-defined blocks, though we don't necessarily
5574   // need to understand them all.
5575   while (1) {
5576     if (Stream.AtEndOfStream()) {
5577       // We didn't really read a proper Module block.
5578       return error("Malformed block");
5579     }
5580
5581     BitstreamEntry Entry =
5582         Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5583
5584     if (Entry.Kind != BitstreamEntry::SubBlock)
5585       return error("Malformed block");
5586
5587     // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5588     // building the function summary index.
5589     if (Entry.ID == bitc::MODULE_BLOCK_ID)
5590       return parseModule();
5591
5592     if (Stream.SkipBlock())
5593       return error("Invalid record");
5594   }
5595 }
5596
5597 // Parse the function information at the given offset in the buffer into
5598 // the index. Used to support lazy parsing of function summaries from the
5599 // combined index during importing.
5600 // TODO: This function is not yet complete as it won't have a consumer
5601 // until ThinLTO function importing is added.
5602 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5603     std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5604     size_t FunctionSummaryOffset) {
5605   TheIndex = I;
5606
5607   if (std::error_code EC = initStream(std::move(Streamer)))
5608     return EC;
5609
5610   // Sniff for the signature.
5611   if (!hasValidBitcodeHeader(Stream))
5612     return error("Invalid bitcode signature");
5613
5614   Stream.JumpToBit(FunctionSummaryOffset);
5615
5616   BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5617
5618   switch (Entry.Kind) {
5619   default:
5620     return error("Malformed block");
5621   case BitstreamEntry::Record:
5622     // The expected case.
5623     break;
5624   }
5625
5626   // TODO: Read a record. This interface will be completed when ThinLTO
5627   // importing is added so that it can be tested.
5628   SmallVector<uint64_t, 64> Record;
5629   switch (Stream.readRecord(Entry.ID, Record)) {
5630   case bitc::FS_CODE_COMBINED_ENTRY:
5631   default:
5632     return error("Invalid record");
5633   }
5634
5635   return std::error_code();
5636 }
5637
5638 std::error_code
5639 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5640   if (Streamer)
5641     return initLazyStream(std::move(Streamer));
5642   return initStreamFromBuffer();
5643 }
5644
5645 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5646   const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5647   const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5648
5649   if (Buffer->getBufferSize() & 3)
5650     return error("Invalid bitcode signature");
5651
5652   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5653   // The magic number is 0x0B17C0DE stored in little endian.
5654   if (isBitcodeWrapper(BufPtr, BufEnd))
5655     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5656       return error("Invalid bitcode wrapper header");
5657
5658   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5659   Stream.init(&*StreamFile);
5660
5661   return std::error_code();
5662 }
5663
5664 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5665     std::unique_ptr<DataStreamer> Streamer) {
5666   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5667   // see it.
5668   auto OwnedBytes =
5669       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5670   StreamingMemoryObject &Bytes = *OwnedBytes;
5671   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5672   Stream.init(&*StreamFile);
5673
5674   unsigned char buf[16];
5675   if (Bytes.readBytes(buf, 16, 0) != 16)
5676     return error("Invalid bitcode signature");
5677
5678   if (!isBitcode(buf, buf + 16))
5679     return error("Invalid bitcode signature");
5680
5681   if (isBitcodeWrapper(buf, buf + 4)) {
5682     const unsigned char *bitcodeStart = buf;
5683     const unsigned char *bitcodeEnd = buf + 16;
5684     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5685     Bytes.dropLeadingBytes(bitcodeStart - buf);
5686     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5687   }
5688   return std::error_code();
5689 }
5690
5691 namespace {
5692 class BitcodeErrorCategoryType : public std::error_category {
5693   const char *name() const LLVM_NOEXCEPT override {
5694     return "llvm.bitcode";
5695   }
5696   std::string message(int IE) const override {
5697     BitcodeError E = static_cast<BitcodeError>(IE);
5698     switch (E) {
5699     case BitcodeError::InvalidBitcodeSignature:
5700       return "Invalid bitcode signature";
5701     case BitcodeError::CorruptedBitcode:
5702       return "Corrupted bitcode";
5703     }
5704     llvm_unreachable("Unknown error type!");
5705   }
5706 };
5707 }
5708
5709 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5710
5711 const std::error_category &llvm::BitcodeErrorCategory() {
5712   return *ErrorCategory;
5713 }
5714
5715 //===----------------------------------------------------------------------===//
5716 // External interface
5717 //===----------------------------------------------------------------------===//
5718
5719 static ErrorOr<std::unique_ptr<Module>>
5720 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5721                      BitcodeReader *R, LLVMContext &Context,
5722                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5723   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5724   M->setMaterializer(R);
5725
5726   auto cleanupOnError = [&](std::error_code EC) {
5727     R->releaseBuffer(); // Never take ownership on error.
5728     return EC;
5729   };
5730
5731   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5732   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5733                                                ShouldLazyLoadMetadata))
5734     return cleanupOnError(EC);
5735
5736   if (MaterializeAll) {
5737     // Read in the entire module, and destroy the BitcodeReader.
5738     if (std::error_code EC = M->materializeAllPermanently())
5739       return cleanupOnError(EC);
5740   } else {
5741     // Resolve forward references from blockaddresses.
5742     if (std::error_code EC = R->materializeForwardReferencedFunctions())
5743       return cleanupOnError(EC);
5744   }
5745   return std::move(M);
5746 }
5747
5748 /// \brief Get a lazy one-at-time loading module from bitcode.
5749 ///
5750 /// This isn't always used in a lazy context.  In particular, it's also used by
5751 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
5752 /// in forward-referenced functions from block address references.
5753 ///
5754 /// \param[in] MaterializeAll Set to \c true if we should materialize
5755 /// everything.
5756 static ErrorOr<std::unique_ptr<Module>>
5757 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5758                          LLVMContext &Context, bool MaterializeAll,
5759                          DiagnosticHandlerFunction DiagnosticHandler,
5760                          bool ShouldLazyLoadMetadata = false) {
5761   BitcodeReader *R =
5762       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
5763
5764   ErrorOr<std::unique_ptr<Module>> Ret =
5765       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5766                            MaterializeAll, ShouldLazyLoadMetadata);
5767   if (!Ret)
5768     return Ret;
5769
5770   Buffer.release(); // The BitcodeReader owns it now.
5771   return Ret;
5772 }
5773
5774 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5775     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5776     DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
5777   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5778                                   DiagnosticHandler, ShouldLazyLoadMetadata);
5779 }
5780
5781 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5782     StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5783     LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
5784   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5785   BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
5786
5787   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5788                               false);
5789 }
5790
5791 ErrorOr<std::unique_ptr<Module>>
5792 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5793                        DiagnosticHandlerFunction DiagnosticHandler) {
5794   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5795   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5796                                   DiagnosticHandler);
5797   // TODO: Restore the use-lists to the in-memory state when the bitcode was
5798   // written.  We must defer until the Module has been fully materialized.
5799 }
5800
5801 std::string
5802 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5803                              DiagnosticHandlerFunction DiagnosticHandler) {
5804   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5805   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5806                                             DiagnosticHandler);
5807   ErrorOr<std::string> Triple = R->parseTriple();
5808   if (Triple.getError())
5809     return "";
5810   return Triple.get();
5811 }
5812
5813 // Parse the specified bitcode buffer, returning the function info index.
5814 // If IsLazy is false, parse the entire function summary into
5815 // the index. Otherwise skip the function summary section, and only create
5816 // an index object with a map from function name to function summary offset.
5817 // The index is used to perform lazy function summary reading later.
5818 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5819 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, LLVMContext &Context,
5820                            DiagnosticHandlerFunction DiagnosticHandler,
5821                            const Module *ExportingModule, bool IsLazy) {
5822   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5823   FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, IsLazy);
5824
5825   std::unique_ptr<FunctionInfoIndex> Index =
5826       llvm::make_unique<FunctionInfoIndex>(ExportingModule);
5827
5828   auto cleanupOnError = [&](std::error_code EC) {
5829     R.releaseBuffer(); // Never take ownership on error.
5830     return EC;
5831   };
5832
5833   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5834     return cleanupOnError(EC);
5835
5836   Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5837   return std::move(Index);
5838 }
5839
5840 // Check if the given bitcode buffer contains a function summary block.
5841 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5842                               DiagnosticHandlerFunction DiagnosticHandler) {
5843   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5844   FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler, false,
5845                                true);
5846
5847   auto cleanupOnError = [&](std::error_code EC) {
5848     R.releaseBuffer(); // Never take ownership on error.
5849     return false;
5850   };
5851
5852   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5853     return cleanupOnError(EC);
5854
5855   Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5856   return R.foundFuncSummary();
5857 }
5858
5859 // This method supports lazy reading of function summary data from the combined
5860 // index during ThinLTO function importing. When reading the combined index
5861 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5862 // Then this method is called for each function considered for importing,
5863 // to parse the summary information for the given function name into
5864 // the index.
5865 std::error_code
5866 llvm::readFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
5867                           DiagnosticHandlerFunction DiagnosticHandler,
5868                           StringRef FunctionName,
5869                           std::unique_ptr<FunctionInfoIndex> Index) {
5870   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5871   FunctionIndexBitcodeReader R(Buf.get(), Context, DiagnosticHandler);
5872
5873   auto cleanupOnError = [&](std::error_code EC) {
5874     R.releaseBuffer(); // Never take ownership on error.
5875     return EC;
5876   };
5877
5878   // Lookup the given function name in the FunctionMap, which may
5879   // contain a list of function infos in the case of a COMDAT. Walk through
5880   // and parse each function summary info at the function summary offset
5881   // recorded when parsing the value symbol table.
5882   for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5883     size_t FunctionSummaryOffset = FI->bitcodeIndex();
5884     if (std::error_code EC =
5885             R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5886       return cleanupOnError(EC);
5887   }
5888
5889   Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5890   return std::error_code();
5891 }