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