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