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