[IR] Give catchret an optional 'return value' operand
[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_TOKEN:     // TOKEN
1364       ResultTy = Type::getTokenTy(Context);
1365       break;
1366     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1367       if (Record.size() < 1)
1368         return error("Invalid record");
1369
1370       uint64_t NumBits = Record[0];
1371       if (NumBits < IntegerType::MIN_INT_BITS ||
1372           NumBits > IntegerType::MAX_INT_BITS)
1373         return error("Bitwidth for integer type out of range");
1374       ResultTy = IntegerType::get(Context, NumBits);
1375       break;
1376     }
1377     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1378                                     //          [pointee type, address space]
1379       if (Record.size() < 1)
1380         return error("Invalid record");
1381       unsigned AddressSpace = 0;
1382       if (Record.size() == 2)
1383         AddressSpace = Record[1];
1384       ResultTy = getTypeByID(Record[0]);
1385       if (!ResultTy ||
1386           !PointerType::isValidElementType(ResultTy))
1387         return error("Invalid type");
1388       ResultTy = PointerType::get(ResultTy, AddressSpace);
1389       break;
1390     }
1391     case bitc::TYPE_CODE_FUNCTION_OLD: {
1392       // FIXME: attrid is dead, remove it in LLVM 4.0
1393       // FUNCTION: [vararg, attrid, retty, paramty x N]
1394       if (Record.size() < 3)
1395         return error("Invalid record");
1396       SmallVector<Type*, 8> ArgTys;
1397       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1398         if (Type *T = getTypeByID(Record[i]))
1399           ArgTys.push_back(T);
1400         else
1401           break;
1402       }
1403
1404       ResultTy = getTypeByID(Record[2]);
1405       if (!ResultTy || ArgTys.size() < Record.size()-3)
1406         return error("Invalid type");
1407
1408       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1409       break;
1410     }
1411     case bitc::TYPE_CODE_FUNCTION: {
1412       // FUNCTION: [vararg, retty, paramty x N]
1413       if (Record.size() < 2)
1414         return error("Invalid record");
1415       SmallVector<Type*, 8> ArgTys;
1416       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1417         if (Type *T = getTypeByID(Record[i])) {
1418           if (!FunctionType::isValidArgumentType(T))
1419             return error("Invalid function argument type");
1420           ArgTys.push_back(T);
1421         }
1422         else
1423           break;
1424       }
1425
1426       ResultTy = getTypeByID(Record[1]);
1427       if (!ResultTy || ArgTys.size() < Record.size()-2)
1428         return error("Invalid type");
1429
1430       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1431       break;
1432     }
1433     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1434       if (Record.size() < 1)
1435         return error("Invalid record");
1436       SmallVector<Type*, 8> EltTys;
1437       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1438         if (Type *T = getTypeByID(Record[i]))
1439           EltTys.push_back(T);
1440         else
1441           break;
1442       }
1443       if (EltTys.size() != Record.size()-1)
1444         return error("Invalid type");
1445       ResultTy = StructType::get(Context, EltTys, Record[0]);
1446       break;
1447     }
1448     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1449       if (convertToString(Record, 0, TypeName))
1450         return error("Invalid record");
1451       continue;
1452
1453     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1454       if (Record.size() < 1)
1455         return error("Invalid record");
1456
1457       if (NumRecords >= TypeList.size())
1458         return error("Invalid TYPE table");
1459
1460       // Check to see if this was forward referenced, if so fill in the temp.
1461       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1462       if (Res) {
1463         Res->setName(TypeName);
1464         TypeList[NumRecords] = nullptr;
1465       } else  // Otherwise, create a new struct.
1466         Res = createIdentifiedStructType(Context, TypeName);
1467       TypeName.clear();
1468
1469       SmallVector<Type*, 8> EltTys;
1470       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1471         if (Type *T = getTypeByID(Record[i]))
1472           EltTys.push_back(T);
1473         else
1474           break;
1475       }
1476       if (EltTys.size() != Record.size()-1)
1477         return error("Invalid record");
1478       Res->setBody(EltTys, Record[0]);
1479       ResultTy = Res;
1480       break;
1481     }
1482     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1483       if (Record.size() != 1)
1484         return error("Invalid record");
1485
1486       if (NumRecords >= TypeList.size())
1487         return error("Invalid TYPE table");
1488
1489       // Check to see if this was forward referenced, if so fill in the temp.
1490       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1491       if (Res) {
1492         Res->setName(TypeName);
1493         TypeList[NumRecords] = nullptr;
1494       } else  // Otherwise, create a new struct with no body.
1495         Res = createIdentifiedStructType(Context, TypeName);
1496       TypeName.clear();
1497       ResultTy = Res;
1498       break;
1499     }
1500     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1501       if (Record.size() < 2)
1502         return error("Invalid record");
1503       ResultTy = getTypeByID(Record[1]);
1504       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1505         return error("Invalid type");
1506       ResultTy = ArrayType::get(ResultTy, Record[0]);
1507       break;
1508     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1509       if (Record.size() < 2)
1510         return error("Invalid record");
1511       if (Record[0] == 0)
1512         return error("Invalid vector length");
1513       ResultTy = getTypeByID(Record[1]);
1514       if (!ResultTy || !StructType::isValidElementType(ResultTy))
1515         return error("Invalid type");
1516       ResultTy = VectorType::get(ResultTy, Record[0]);
1517       break;
1518     }
1519
1520     if (NumRecords >= TypeList.size())
1521       return error("Invalid TYPE table");
1522     if (TypeList[NumRecords])
1523       return error(
1524           "Invalid TYPE table: Only named structs can be forward referenced");
1525     assert(ResultTy && "Didn't read a type?");
1526     TypeList[NumRecords++] = ResultTy;
1527   }
1528 }
1529
1530 std::error_code BitcodeReader::parseValueSymbolTable() {
1531   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1532     return error("Invalid record");
1533
1534   SmallVector<uint64_t, 64> Record;
1535
1536   Triple TT(TheModule->getTargetTriple());
1537
1538   // Read all the records for this value table.
1539   SmallString<128> ValueName;
1540   while (1) {
1541     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1542
1543     switch (Entry.Kind) {
1544     case BitstreamEntry::SubBlock: // Handled for us already.
1545     case BitstreamEntry::Error:
1546       return error("Malformed block");
1547     case BitstreamEntry::EndBlock:
1548       return std::error_code();
1549     case BitstreamEntry::Record:
1550       // The interesting case.
1551       break;
1552     }
1553
1554     // Read a record.
1555     Record.clear();
1556     switch (Stream.readRecord(Entry.ID, Record)) {
1557     default:  // Default behavior: unknown type.
1558       break;
1559     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1560       if (convertToString(Record, 1, ValueName))
1561         return error("Invalid record");
1562       unsigned ValueID = Record[0];
1563       if (ValueID >= ValueList.size() || !ValueList[ValueID])
1564         return error("Invalid record");
1565       Value *V = ValueList[ValueID];
1566
1567       V->setName(StringRef(ValueName.data(), ValueName.size()));
1568       if (auto *GO = dyn_cast<GlobalObject>(V)) {
1569         if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1570           if (TT.isOSBinFormatMachO())
1571             GO->setComdat(nullptr);
1572           else
1573             GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1574         }
1575       }
1576       ValueName.clear();
1577       break;
1578     }
1579     case bitc::VST_CODE_BBENTRY: {
1580       if (convertToString(Record, 1, ValueName))
1581         return error("Invalid record");
1582       BasicBlock *BB = getBasicBlock(Record[0]);
1583       if (!BB)
1584         return error("Invalid record");
1585
1586       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1587       ValueName.clear();
1588       break;
1589     }
1590     }
1591   }
1592 }
1593
1594 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1595
1596 std::error_code BitcodeReader::parseMetadata() {
1597   IsMetadataMaterialized = true;
1598   unsigned NextMDValueNo = MDValueList.size();
1599
1600   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1601     return error("Invalid record");
1602
1603   SmallVector<uint64_t, 64> Record;
1604
1605   auto getMD =
1606       [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1607   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1608     if (ID)
1609       return getMD(ID - 1);
1610     return nullptr;
1611   };
1612   auto getMDString = [&](unsigned ID) -> MDString *{
1613     // This requires that the ID is not really a forward reference.  In
1614     // particular, the MDString must already have been resolved.
1615     return cast_or_null<MDString>(getMDOrNull(ID));
1616   };
1617
1618 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
1619   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1620
1621   // Read all the records.
1622   while (1) {
1623     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1624
1625     switch (Entry.Kind) {
1626     case BitstreamEntry::SubBlock: // Handled for us already.
1627     case BitstreamEntry::Error:
1628       return error("Malformed block");
1629     case BitstreamEntry::EndBlock:
1630       MDValueList.tryToResolveCycles();
1631       return std::error_code();
1632     case BitstreamEntry::Record:
1633       // The interesting case.
1634       break;
1635     }
1636
1637     // Read a record.
1638     Record.clear();
1639     unsigned Code = Stream.readRecord(Entry.ID, Record);
1640     bool IsDistinct = false;
1641     switch (Code) {
1642     default:  // Default behavior: ignore.
1643       break;
1644     case bitc::METADATA_NAME: {
1645       // Read name of the named metadata.
1646       SmallString<8> Name(Record.begin(), Record.end());
1647       Record.clear();
1648       Code = Stream.ReadCode();
1649
1650       unsigned NextBitCode = Stream.readRecord(Code, Record);
1651       if (NextBitCode != bitc::METADATA_NAMED_NODE)
1652         return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1653
1654       // Read named metadata elements.
1655       unsigned Size = Record.size();
1656       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1657       for (unsigned i = 0; i != Size; ++i) {
1658         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1659         if (!MD)
1660           return error("Invalid record");
1661         NMD->addOperand(MD);
1662       }
1663       break;
1664     }
1665     case bitc::METADATA_OLD_FN_NODE: {
1666       // FIXME: Remove in 4.0.
1667       // This is a LocalAsMetadata record, the only type of function-local
1668       // metadata.
1669       if (Record.size() % 2 == 1)
1670         return error("Invalid record");
1671
1672       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
1673       // to be legal, but there's no upgrade path.
1674       auto dropRecord = [&] {
1675         MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
1676       };
1677       if (Record.size() != 2) {
1678         dropRecord();
1679         break;
1680       }
1681
1682       Type *Ty = getTypeByID(Record[0]);
1683       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1684         dropRecord();
1685         break;
1686       }
1687
1688       MDValueList.assignValue(
1689           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1690           NextMDValueNo++);
1691       break;
1692     }
1693     case bitc::METADATA_OLD_NODE: {
1694       // FIXME: Remove in 4.0.
1695       if (Record.size() % 2 == 1)
1696         return error("Invalid record");
1697
1698       unsigned Size = Record.size();
1699       SmallVector<Metadata *, 8> Elts;
1700       for (unsigned i = 0; i != Size; i += 2) {
1701         Type *Ty = getTypeByID(Record[i]);
1702         if (!Ty)
1703           return error("Invalid record");
1704         if (Ty->isMetadataTy())
1705           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1706         else if (!Ty->isVoidTy()) {
1707           auto *MD =
1708               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1709           assert(isa<ConstantAsMetadata>(MD) &&
1710                  "Expected non-function-local metadata");
1711           Elts.push_back(MD);
1712         } else
1713           Elts.push_back(nullptr);
1714       }
1715       MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1716       break;
1717     }
1718     case bitc::METADATA_VALUE: {
1719       if (Record.size() != 2)
1720         return error("Invalid record");
1721
1722       Type *Ty = getTypeByID(Record[0]);
1723       if (Ty->isMetadataTy() || Ty->isVoidTy())
1724         return error("Invalid record");
1725
1726       MDValueList.assignValue(
1727           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1728           NextMDValueNo++);
1729       break;
1730     }
1731     case bitc::METADATA_DISTINCT_NODE:
1732       IsDistinct = true;
1733       // fallthrough...
1734     case bitc::METADATA_NODE: {
1735       SmallVector<Metadata *, 8> Elts;
1736       Elts.reserve(Record.size());
1737       for (unsigned ID : Record)
1738         Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1739       MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1740                                          : MDNode::get(Context, Elts),
1741                               NextMDValueNo++);
1742       break;
1743     }
1744     case bitc::METADATA_LOCATION: {
1745       if (Record.size() != 5)
1746         return error("Invalid record");
1747
1748       unsigned Line = Record[1];
1749       unsigned Column = Record[2];
1750       MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1751       Metadata *InlinedAt =
1752           Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1753       MDValueList.assignValue(
1754           GET_OR_DISTINCT(DILocation, Record[0],
1755                           (Context, Line, Column, Scope, InlinedAt)),
1756           NextMDValueNo++);
1757       break;
1758     }
1759     case bitc::METADATA_GENERIC_DEBUG: {
1760       if (Record.size() < 4)
1761         return error("Invalid record");
1762
1763       unsigned Tag = Record[1];
1764       unsigned Version = Record[2];
1765
1766       if (Tag >= 1u << 16 || Version != 0)
1767         return error("Invalid record");
1768
1769       auto *Header = getMDString(Record[3]);
1770       SmallVector<Metadata *, 8> DwarfOps;
1771       for (unsigned I = 4, E = Record.size(); I != E; ++I)
1772         DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1773                                      : nullptr);
1774       MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
1775                                               (Context, Tag, Header, DwarfOps)),
1776                               NextMDValueNo++);
1777       break;
1778     }
1779     case bitc::METADATA_SUBRANGE: {
1780       if (Record.size() != 3)
1781         return error("Invalid record");
1782
1783       MDValueList.assignValue(
1784           GET_OR_DISTINCT(DISubrange, Record[0],
1785                           (Context, Record[1], unrotateSign(Record[2]))),
1786           NextMDValueNo++);
1787       break;
1788     }
1789     case bitc::METADATA_ENUMERATOR: {
1790       if (Record.size() != 3)
1791         return error("Invalid record");
1792
1793       MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
1794                                               (Context, unrotateSign(Record[1]),
1795                                                getMDString(Record[2]))),
1796                               NextMDValueNo++);
1797       break;
1798     }
1799     case bitc::METADATA_BASIC_TYPE: {
1800       if (Record.size() != 6)
1801         return error("Invalid record");
1802
1803       MDValueList.assignValue(
1804           GET_OR_DISTINCT(DIBasicType, Record[0],
1805                           (Context, Record[1], getMDString(Record[2]),
1806                            Record[3], Record[4], Record[5])),
1807           NextMDValueNo++);
1808       break;
1809     }
1810     case bitc::METADATA_DERIVED_TYPE: {
1811       if (Record.size() != 12)
1812         return error("Invalid record");
1813
1814       MDValueList.assignValue(
1815           GET_OR_DISTINCT(DIDerivedType, Record[0],
1816                           (Context, Record[1], getMDString(Record[2]),
1817                            getMDOrNull(Record[3]), Record[4],
1818                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1819                            Record[7], Record[8], Record[9], Record[10],
1820                            getMDOrNull(Record[11]))),
1821           NextMDValueNo++);
1822       break;
1823     }
1824     case bitc::METADATA_COMPOSITE_TYPE: {
1825       if (Record.size() != 16)
1826         return error("Invalid record");
1827
1828       MDValueList.assignValue(
1829           GET_OR_DISTINCT(DICompositeType, Record[0],
1830                           (Context, Record[1], getMDString(Record[2]),
1831                            getMDOrNull(Record[3]), Record[4],
1832                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1833                            Record[7], Record[8], Record[9], Record[10],
1834                            getMDOrNull(Record[11]), Record[12],
1835                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1836                            getMDString(Record[15]))),
1837           NextMDValueNo++);
1838       break;
1839     }
1840     case bitc::METADATA_SUBROUTINE_TYPE: {
1841       if (Record.size() != 3)
1842         return error("Invalid record");
1843
1844       MDValueList.assignValue(
1845           GET_OR_DISTINCT(DISubroutineType, Record[0],
1846                           (Context, Record[1], getMDOrNull(Record[2]))),
1847           NextMDValueNo++);
1848       break;
1849     }
1850
1851     case bitc::METADATA_MODULE: {
1852       if (Record.size() != 6)
1853         return error("Invalid record");
1854
1855       MDValueList.assignValue(
1856           GET_OR_DISTINCT(DIModule, Record[0],
1857                           (Context, getMDOrNull(Record[1]),
1858                           getMDString(Record[2]), getMDString(Record[3]),
1859                           getMDString(Record[4]), getMDString(Record[5]))),
1860           NextMDValueNo++);
1861       break;
1862     }
1863
1864     case bitc::METADATA_FILE: {
1865       if (Record.size() != 3)
1866         return error("Invalid record");
1867
1868       MDValueList.assignValue(
1869           GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1870                                               getMDString(Record[2]))),
1871           NextMDValueNo++);
1872       break;
1873     }
1874     case bitc::METADATA_COMPILE_UNIT: {
1875       if (Record.size() < 14 || Record.size() > 15)
1876         return error("Invalid record");
1877
1878       // Ignore Record[1], which indicates whether this compile unit is
1879       // distinct.  It's always distinct.
1880       MDValueList.assignValue(
1881           DICompileUnit::getDistinct(
1882               Context, Record[1], getMDOrNull(Record[2]),
1883               getMDString(Record[3]), Record[4], getMDString(Record[5]),
1884               Record[6], getMDString(Record[7]), Record[8],
1885               getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1886               getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1887               getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
1888           NextMDValueNo++);
1889       break;
1890     }
1891     case bitc::METADATA_SUBPROGRAM: {
1892       if (Record.size() != 19)
1893         return error("Invalid record");
1894
1895       MDValueList.assignValue(
1896           GET_OR_DISTINCT(
1897               DISubprogram, Record[0],
1898               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1899                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1900                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1901                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1902                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1903                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1904           NextMDValueNo++);
1905       break;
1906     }
1907     case bitc::METADATA_LEXICAL_BLOCK: {
1908       if (Record.size() != 5)
1909         return error("Invalid record");
1910
1911       MDValueList.assignValue(
1912           GET_OR_DISTINCT(DILexicalBlock, Record[0],
1913                           (Context, getMDOrNull(Record[1]),
1914                            getMDOrNull(Record[2]), Record[3], Record[4])),
1915           NextMDValueNo++);
1916       break;
1917     }
1918     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1919       if (Record.size() != 4)
1920         return error("Invalid record");
1921
1922       MDValueList.assignValue(
1923           GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1924                           (Context, getMDOrNull(Record[1]),
1925                            getMDOrNull(Record[2]), Record[3])),
1926           NextMDValueNo++);
1927       break;
1928     }
1929     case bitc::METADATA_NAMESPACE: {
1930       if (Record.size() != 5)
1931         return error("Invalid record");
1932
1933       MDValueList.assignValue(
1934           GET_OR_DISTINCT(DINamespace, Record[0],
1935                           (Context, getMDOrNull(Record[1]),
1936                            getMDOrNull(Record[2]), getMDString(Record[3]),
1937                            Record[4])),
1938           NextMDValueNo++);
1939       break;
1940     }
1941     case bitc::METADATA_TEMPLATE_TYPE: {
1942       if (Record.size() != 3)
1943         return error("Invalid record");
1944
1945       MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1946                                               Record[0],
1947                                               (Context, getMDString(Record[1]),
1948                                                getMDOrNull(Record[2]))),
1949                               NextMDValueNo++);
1950       break;
1951     }
1952     case bitc::METADATA_TEMPLATE_VALUE: {
1953       if (Record.size() != 5)
1954         return error("Invalid record");
1955
1956       MDValueList.assignValue(
1957           GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1958                           (Context, Record[1], getMDString(Record[2]),
1959                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1960           NextMDValueNo++);
1961       break;
1962     }
1963     case bitc::METADATA_GLOBAL_VAR: {
1964       if (Record.size() != 11)
1965         return error("Invalid record");
1966
1967       MDValueList.assignValue(
1968           GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1969                           (Context, getMDOrNull(Record[1]),
1970                            getMDString(Record[2]), getMDString(Record[3]),
1971                            getMDOrNull(Record[4]), Record[5],
1972                            getMDOrNull(Record[6]), Record[7], Record[8],
1973                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1974           NextMDValueNo++);
1975       break;
1976     }
1977     case bitc::METADATA_LOCAL_VAR: {
1978       // 10th field is for the obseleted 'inlinedAt:' field.
1979       if (Record.size() < 8 || Record.size() > 10)
1980         return error("Invalid record");
1981
1982       // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1983       // DW_TAG_arg_variable.
1984       bool HasTag = Record.size() > 8;
1985       MDValueList.assignValue(
1986           GET_OR_DISTINCT(DILocalVariable, Record[0],
1987                           (Context, getMDOrNull(Record[1 + HasTag]),
1988                            getMDString(Record[2 + HasTag]),
1989                            getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1990                            getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
1991                            Record[7 + HasTag])),
1992           NextMDValueNo++);
1993       break;
1994     }
1995     case bitc::METADATA_EXPRESSION: {
1996       if (Record.size() < 1)
1997         return error("Invalid record");
1998
1999       MDValueList.assignValue(
2000           GET_OR_DISTINCT(DIExpression, Record[0],
2001                           (Context, makeArrayRef(Record).slice(1))),
2002           NextMDValueNo++);
2003       break;
2004     }
2005     case bitc::METADATA_OBJC_PROPERTY: {
2006       if (Record.size() != 8)
2007         return error("Invalid record");
2008
2009       MDValueList.assignValue(
2010           GET_OR_DISTINCT(DIObjCProperty, Record[0],
2011                           (Context, getMDString(Record[1]),
2012                            getMDOrNull(Record[2]), Record[3],
2013                            getMDString(Record[4]), getMDString(Record[5]),
2014                            Record[6], getMDOrNull(Record[7]))),
2015           NextMDValueNo++);
2016       break;
2017     }
2018     case bitc::METADATA_IMPORTED_ENTITY: {
2019       if (Record.size() != 6)
2020         return error("Invalid record");
2021
2022       MDValueList.assignValue(
2023           GET_OR_DISTINCT(DIImportedEntity, Record[0],
2024                           (Context, Record[1], getMDOrNull(Record[2]),
2025                            getMDOrNull(Record[3]), Record[4],
2026                            getMDString(Record[5]))),
2027           NextMDValueNo++);
2028       break;
2029     }
2030     case bitc::METADATA_STRING: {
2031       std::string String(Record.begin(), Record.end());
2032       llvm::UpgradeMDStringConstant(String);
2033       Metadata *MD = MDString::get(Context, String);
2034       MDValueList.assignValue(MD, NextMDValueNo++);
2035       break;
2036     }
2037     case bitc::METADATA_KIND: {
2038       if (Record.size() < 2)
2039         return error("Invalid record");
2040
2041       unsigned Kind = Record[0];
2042       SmallString<8> Name(Record.begin()+1, Record.end());
2043
2044       unsigned NewKind = TheModule->getMDKindID(Name.str());
2045       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2046         return error("Conflicting METADATA_KIND records");
2047       break;
2048     }
2049     }
2050   }
2051 #undef GET_OR_DISTINCT
2052 }
2053
2054 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2055 /// encoding.
2056 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2057   if ((V & 1) == 0)
2058     return V >> 1;
2059   if (V != 1)
2060     return -(V >> 1);
2061   // There is no such thing as -0 with integers.  "-0" really means MININT.
2062   return 1ULL << 63;
2063 }
2064
2065 /// Resolve all of the initializers for global values and aliases that we can.
2066 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2067   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2068   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2069   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2070   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2071   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2072
2073   GlobalInitWorklist.swap(GlobalInits);
2074   AliasInitWorklist.swap(AliasInits);
2075   FunctionPrefixWorklist.swap(FunctionPrefixes);
2076   FunctionPrologueWorklist.swap(FunctionPrologues);
2077   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2078
2079   while (!GlobalInitWorklist.empty()) {
2080     unsigned ValID = GlobalInitWorklist.back().second;
2081     if (ValID >= ValueList.size()) {
2082       // Not ready to resolve this yet, it requires something later in the file.
2083       GlobalInits.push_back(GlobalInitWorklist.back());
2084     } else {
2085       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2086         GlobalInitWorklist.back().first->setInitializer(C);
2087       else
2088         return error("Expected a constant");
2089     }
2090     GlobalInitWorklist.pop_back();
2091   }
2092
2093   while (!AliasInitWorklist.empty()) {
2094     unsigned ValID = AliasInitWorklist.back().second;
2095     if (ValID >= ValueList.size()) {
2096       AliasInits.push_back(AliasInitWorklist.back());
2097     } else {
2098       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2099       if (!C)
2100         return error("Expected a constant");
2101       GlobalAlias *Alias = AliasInitWorklist.back().first;
2102       if (C->getType() != Alias->getType())
2103         return error("Alias and aliasee types don't match");
2104       Alias->setAliasee(C);
2105     }
2106     AliasInitWorklist.pop_back();
2107   }
2108
2109   while (!FunctionPrefixWorklist.empty()) {
2110     unsigned ValID = FunctionPrefixWorklist.back().second;
2111     if (ValID >= ValueList.size()) {
2112       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2113     } else {
2114       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2115         FunctionPrefixWorklist.back().first->setPrefixData(C);
2116       else
2117         return error("Expected a constant");
2118     }
2119     FunctionPrefixWorklist.pop_back();
2120   }
2121
2122   while (!FunctionPrologueWorklist.empty()) {
2123     unsigned ValID = FunctionPrologueWorklist.back().second;
2124     if (ValID >= ValueList.size()) {
2125       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2126     } else {
2127       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2128         FunctionPrologueWorklist.back().first->setPrologueData(C);
2129       else
2130         return error("Expected a constant");
2131     }
2132     FunctionPrologueWorklist.pop_back();
2133   }
2134
2135   while (!FunctionPersonalityFnWorklist.empty()) {
2136     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2137     if (ValID >= ValueList.size()) {
2138       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2139     } else {
2140       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2141         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2142       else
2143         return error("Expected a constant");
2144     }
2145     FunctionPersonalityFnWorklist.pop_back();
2146   }
2147
2148   return std::error_code();
2149 }
2150
2151 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2152   SmallVector<uint64_t, 8> Words(Vals.size());
2153   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2154                  BitcodeReader::decodeSignRotatedValue);
2155
2156   return APInt(TypeBits, Words);
2157 }
2158
2159 std::error_code BitcodeReader::parseConstants() {
2160   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2161     return error("Invalid record");
2162
2163   SmallVector<uint64_t, 64> Record;
2164
2165   // Read all the records for this value table.
2166   Type *CurTy = Type::getInt32Ty(Context);
2167   unsigned NextCstNo = ValueList.size();
2168   while (1) {
2169     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2170
2171     switch (Entry.Kind) {
2172     case BitstreamEntry::SubBlock: // Handled for us already.
2173     case BitstreamEntry::Error:
2174       return error("Malformed block");
2175     case BitstreamEntry::EndBlock:
2176       if (NextCstNo != ValueList.size())
2177         return error("Invalid ronstant reference");
2178
2179       // Once all the constants have been read, go through and resolve forward
2180       // references.
2181       ValueList.resolveConstantForwardRefs();
2182       return std::error_code();
2183     case BitstreamEntry::Record:
2184       // The interesting case.
2185       break;
2186     }
2187
2188     // Read a record.
2189     Record.clear();
2190     Value *V = nullptr;
2191     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2192     switch (BitCode) {
2193     default:  // Default behavior: unknown constant
2194     case bitc::CST_CODE_UNDEF:     // UNDEF
2195       V = UndefValue::get(CurTy);
2196       break;
2197     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2198       if (Record.empty())
2199         return error("Invalid record");
2200       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2201         return error("Invalid record");
2202       CurTy = TypeList[Record[0]];
2203       continue;  // Skip the ValueList manipulation.
2204     case bitc::CST_CODE_NULL:      // NULL
2205       V = Constant::getNullValue(CurTy);
2206       break;
2207     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2208       if (!CurTy->isIntegerTy() || Record.empty())
2209         return error("Invalid record");
2210       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2211       break;
2212     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2213       if (!CurTy->isIntegerTy() || Record.empty())
2214         return error("Invalid record");
2215
2216       APInt VInt =
2217           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2218       V = ConstantInt::get(Context, VInt);
2219
2220       break;
2221     }
2222     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2223       if (Record.empty())
2224         return error("Invalid record");
2225       if (CurTy->isHalfTy())
2226         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2227                                              APInt(16, (uint16_t)Record[0])));
2228       else if (CurTy->isFloatTy())
2229         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2230                                              APInt(32, (uint32_t)Record[0])));
2231       else if (CurTy->isDoubleTy())
2232         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2233                                              APInt(64, Record[0])));
2234       else if (CurTy->isX86_FP80Ty()) {
2235         // Bits are not stored the same way as a normal i80 APInt, compensate.
2236         uint64_t Rearrange[2];
2237         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2238         Rearrange[1] = Record[0] >> 48;
2239         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2240                                              APInt(80, Rearrange)));
2241       } else if (CurTy->isFP128Ty())
2242         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2243                                              APInt(128, Record)));
2244       else if (CurTy->isPPC_FP128Ty())
2245         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2246                                              APInt(128, Record)));
2247       else
2248         V = UndefValue::get(CurTy);
2249       break;
2250     }
2251
2252     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2253       if (Record.empty())
2254         return error("Invalid record");
2255
2256       unsigned Size = Record.size();
2257       SmallVector<Constant*, 16> Elts;
2258
2259       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2260         for (unsigned i = 0; i != Size; ++i)
2261           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2262                                                      STy->getElementType(i)));
2263         V = ConstantStruct::get(STy, Elts);
2264       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2265         Type *EltTy = ATy->getElementType();
2266         for (unsigned i = 0; i != Size; ++i)
2267           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2268         V = ConstantArray::get(ATy, Elts);
2269       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2270         Type *EltTy = VTy->getElementType();
2271         for (unsigned i = 0; i != Size; ++i)
2272           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2273         V = ConstantVector::get(Elts);
2274       } else {
2275         V = UndefValue::get(CurTy);
2276       }
2277       break;
2278     }
2279     case bitc::CST_CODE_STRING:    // STRING: [values]
2280     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2281       if (Record.empty())
2282         return error("Invalid record");
2283
2284       SmallString<16> Elts(Record.begin(), Record.end());
2285       V = ConstantDataArray::getString(Context, Elts,
2286                                        BitCode == bitc::CST_CODE_CSTRING);
2287       break;
2288     }
2289     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2290       if (Record.empty())
2291         return error("Invalid record");
2292
2293       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2294       unsigned Size = Record.size();
2295
2296       if (EltTy->isIntegerTy(8)) {
2297         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2298         if (isa<VectorType>(CurTy))
2299           V = ConstantDataVector::get(Context, Elts);
2300         else
2301           V = ConstantDataArray::get(Context, Elts);
2302       } else if (EltTy->isIntegerTy(16)) {
2303         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2304         if (isa<VectorType>(CurTy))
2305           V = ConstantDataVector::get(Context, Elts);
2306         else
2307           V = ConstantDataArray::get(Context, Elts);
2308       } else if (EltTy->isIntegerTy(32)) {
2309         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2310         if (isa<VectorType>(CurTy))
2311           V = ConstantDataVector::get(Context, Elts);
2312         else
2313           V = ConstantDataArray::get(Context, Elts);
2314       } else if (EltTy->isIntegerTy(64)) {
2315         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2316         if (isa<VectorType>(CurTy))
2317           V = ConstantDataVector::get(Context, Elts);
2318         else
2319           V = ConstantDataArray::get(Context, Elts);
2320       } else if (EltTy->isFloatTy()) {
2321         SmallVector<float, 16> Elts(Size);
2322         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2323         if (isa<VectorType>(CurTy))
2324           V = ConstantDataVector::get(Context, Elts);
2325         else
2326           V = ConstantDataArray::get(Context, Elts);
2327       } else if (EltTy->isDoubleTy()) {
2328         SmallVector<double, 16> Elts(Size);
2329         std::transform(Record.begin(), Record.end(), Elts.begin(),
2330                        BitsToDouble);
2331         if (isa<VectorType>(CurTy))
2332           V = ConstantDataVector::get(Context, Elts);
2333         else
2334           V = ConstantDataArray::get(Context, Elts);
2335       } else {
2336         return error("Invalid type for value");
2337       }
2338       break;
2339     }
2340
2341     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2342       if (Record.size() < 3)
2343         return error("Invalid record");
2344       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2345       if (Opc < 0) {
2346         V = UndefValue::get(CurTy);  // Unknown binop.
2347       } else {
2348         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2349         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2350         unsigned Flags = 0;
2351         if (Record.size() >= 4) {
2352           if (Opc == Instruction::Add ||
2353               Opc == Instruction::Sub ||
2354               Opc == Instruction::Mul ||
2355               Opc == Instruction::Shl) {
2356             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2357               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2358             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2359               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2360           } else if (Opc == Instruction::SDiv ||
2361                      Opc == Instruction::UDiv ||
2362                      Opc == Instruction::LShr ||
2363                      Opc == Instruction::AShr) {
2364             if (Record[3] & (1 << bitc::PEO_EXACT))
2365               Flags |= SDivOperator::IsExact;
2366           }
2367         }
2368         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2369       }
2370       break;
2371     }
2372     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2373       if (Record.size() < 3)
2374         return error("Invalid record");
2375       int Opc = getDecodedCastOpcode(Record[0]);
2376       if (Opc < 0) {
2377         V = UndefValue::get(CurTy);  // Unknown cast.
2378       } else {
2379         Type *OpTy = getTypeByID(Record[1]);
2380         if (!OpTy)
2381           return error("Invalid record");
2382         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2383         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2384         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2385       }
2386       break;
2387     }
2388     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2389     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2390       unsigned OpNum = 0;
2391       Type *PointeeType = nullptr;
2392       if (Record.size() % 2)
2393         PointeeType = getTypeByID(Record[OpNum++]);
2394       SmallVector<Constant*, 16> Elts;
2395       while (OpNum != Record.size()) {
2396         Type *ElTy = getTypeByID(Record[OpNum++]);
2397         if (!ElTy)
2398           return error("Invalid record");
2399         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2400       }
2401
2402       if (PointeeType &&
2403           PointeeType !=
2404               cast<SequentialType>(Elts[0]->getType()->getScalarType())
2405                   ->getElementType())
2406         return error("Explicit gep operator type does not match pointee type "
2407                      "of pointer operand");
2408
2409       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2410       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2411                                          BitCode ==
2412                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
2413       break;
2414     }
2415     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2416       if (Record.size() < 3)
2417         return error("Invalid record");
2418
2419       Type *SelectorTy = Type::getInt1Ty(Context);
2420
2421       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2422       // vector. Otherwise, it must be a single bit.
2423       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2424         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2425                                      VTy->getNumElements());
2426
2427       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2428                                                               SelectorTy),
2429                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2430                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2431       break;
2432     }
2433     case bitc::CST_CODE_CE_EXTRACTELT
2434         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2435       if (Record.size() < 3)
2436         return error("Invalid record");
2437       VectorType *OpTy =
2438         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2439       if (!OpTy)
2440         return error("Invalid record");
2441       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2442       Constant *Op1 = nullptr;
2443       if (Record.size() == 4) {
2444         Type *IdxTy = getTypeByID(Record[2]);
2445         if (!IdxTy)
2446           return error("Invalid record");
2447         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2448       } else // TODO: Remove with llvm 4.0
2449         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2450       if (!Op1)
2451         return error("Invalid record");
2452       V = ConstantExpr::getExtractElement(Op0, Op1);
2453       break;
2454     }
2455     case bitc::CST_CODE_CE_INSERTELT
2456         : { // CE_INSERTELT: [opval, opval, opty, opval]
2457       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2458       if (Record.size() < 3 || !OpTy)
2459         return error("Invalid record");
2460       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2461       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2462                                                   OpTy->getElementType());
2463       Constant *Op2 = nullptr;
2464       if (Record.size() == 4) {
2465         Type *IdxTy = getTypeByID(Record[2]);
2466         if (!IdxTy)
2467           return error("Invalid record");
2468         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2469       } else // TODO: Remove with llvm 4.0
2470         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2471       if (!Op2)
2472         return error("Invalid record");
2473       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2474       break;
2475     }
2476     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2477       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2478       if (Record.size() < 3 || !OpTy)
2479         return error("Invalid record");
2480       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2481       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2482       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2483                                                  OpTy->getNumElements());
2484       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2485       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2486       break;
2487     }
2488     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2489       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2490       VectorType *OpTy =
2491         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2492       if (Record.size() < 4 || !RTy || !OpTy)
2493         return error("Invalid record");
2494       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2495       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2496       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2497                                                  RTy->getNumElements());
2498       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2499       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2500       break;
2501     }
2502     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2503       if (Record.size() < 4)
2504         return error("Invalid record");
2505       Type *OpTy = getTypeByID(Record[0]);
2506       if (!OpTy)
2507         return error("Invalid record");
2508       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2509       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2510
2511       if (OpTy->isFPOrFPVectorTy())
2512         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2513       else
2514         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2515       break;
2516     }
2517     // This maintains backward compatibility, pre-asm dialect keywords.
2518     // FIXME: Remove with the 4.0 release.
2519     case bitc::CST_CODE_INLINEASM_OLD: {
2520       if (Record.size() < 2)
2521         return error("Invalid record");
2522       std::string AsmStr, ConstrStr;
2523       bool HasSideEffects = Record[0] & 1;
2524       bool IsAlignStack = Record[0] >> 1;
2525       unsigned AsmStrSize = Record[1];
2526       if (2+AsmStrSize >= Record.size())
2527         return error("Invalid record");
2528       unsigned ConstStrSize = Record[2+AsmStrSize];
2529       if (3+AsmStrSize+ConstStrSize > Record.size())
2530         return error("Invalid record");
2531
2532       for (unsigned i = 0; i != AsmStrSize; ++i)
2533         AsmStr += (char)Record[2+i];
2534       for (unsigned i = 0; i != ConstStrSize; ++i)
2535         ConstrStr += (char)Record[3+AsmStrSize+i];
2536       PointerType *PTy = cast<PointerType>(CurTy);
2537       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2538                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2539       break;
2540     }
2541     // This version adds support for the asm dialect keywords (e.g.,
2542     // inteldialect).
2543     case bitc::CST_CODE_INLINEASM: {
2544       if (Record.size() < 2)
2545         return error("Invalid record");
2546       std::string AsmStr, ConstrStr;
2547       bool HasSideEffects = Record[0] & 1;
2548       bool IsAlignStack = (Record[0] >> 1) & 1;
2549       unsigned AsmDialect = Record[0] >> 2;
2550       unsigned AsmStrSize = Record[1];
2551       if (2+AsmStrSize >= Record.size())
2552         return error("Invalid record");
2553       unsigned ConstStrSize = Record[2+AsmStrSize];
2554       if (3+AsmStrSize+ConstStrSize > Record.size())
2555         return error("Invalid record");
2556
2557       for (unsigned i = 0; i != AsmStrSize; ++i)
2558         AsmStr += (char)Record[2+i];
2559       for (unsigned i = 0; i != ConstStrSize; ++i)
2560         ConstrStr += (char)Record[3+AsmStrSize+i];
2561       PointerType *PTy = cast<PointerType>(CurTy);
2562       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2563                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2564                          InlineAsm::AsmDialect(AsmDialect));
2565       break;
2566     }
2567     case bitc::CST_CODE_BLOCKADDRESS:{
2568       if (Record.size() < 3)
2569         return error("Invalid record");
2570       Type *FnTy = getTypeByID(Record[0]);
2571       if (!FnTy)
2572         return error("Invalid record");
2573       Function *Fn =
2574         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2575       if (!Fn)
2576         return error("Invalid record");
2577
2578       // Don't let Fn get dematerialized.
2579       BlockAddressesTaken.insert(Fn);
2580
2581       // If the function is already parsed we can insert the block address right
2582       // away.
2583       BasicBlock *BB;
2584       unsigned BBID = Record[2];
2585       if (!BBID)
2586         // Invalid reference to entry block.
2587         return error("Invalid ID");
2588       if (!Fn->empty()) {
2589         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2590         for (size_t I = 0, E = BBID; I != E; ++I) {
2591           if (BBI == BBE)
2592             return error("Invalid ID");
2593           ++BBI;
2594         }
2595         BB = BBI;
2596       } else {
2597         // Otherwise insert a placeholder and remember it so it can be inserted
2598         // when the function is parsed.
2599         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2600         if (FwdBBs.empty())
2601           BasicBlockFwdRefQueue.push_back(Fn);
2602         if (FwdBBs.size() < BBID + 1)
2603           FwdBBs.resize(BBID + 1);
2604         if (!FwdBBs[BBID])
2605           FwdBBs[BBID] = BasicBlock::Create(Context);
2606         BB = FwdBBs[BBID];
2607       }
2608       V = BlockAddress::get(Fn, BB);
2609       break;
2610     }
2611     }
2612
2613     ValueList.assignValue(V, NextCstNo);
2614     ++NextCstNo;
2615   }
2616 }
2617
2618 std::error_code BitcodeReader::parseUseLists() {
2619   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2620     return error("Invalid record");
2621
2622   // Read all the records.
2623   SmallVector<uint64_t, 64> Record;
2624   while (1) {
2625     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2626
2627     switch (Entry.Kind) {
2628     case BitstreamEntry::SubBlock: // Handled for us already.
2629     case BitstreamEntry::Error:
2630       return error("Malformed block");
2631     case BitstreamEntry::EndBlock:
2632       return std::error_code();
2633     case BitstreamEntry::Record:
2634       // The interesting case.
2635       break;
2636     }
2637
2638     // Read a use list record.
2639     Record.clear();
2640     bool IsBB = false;
2641     switch (Stream.readRecord(Entry.ID, Record)) {
2642     default:  // Default behavior: unknown type.
2643       break;
2644     case bitc::USELIST_CODE_BB:
2645       IsBB = true;
2646       // fallthrough
2647     case bitc::USELIST_CODE_DEFAULT: {
2648       unsigned RecordLength = Record.size();
2649       if (RecordLength < 3)
2650         // Records should have at least an ID and two indexes.
2651         return error("Invalid record");
2652       unsigned ID = Record.back();
2653       Record.pop_back();
2654
2655       Value *V;
2656       if (IsBB) {
2657         assert(ID < FunctionBBs.size() && "Basic block not found");
2658         V = FunctionBBs[ID];
2659       } else
2660         V = ValueList[ID];
2661       unsigned NumUses = 0;
2662       SmallDenseMap<const Use *, unsigned, 16> Order;
2663       for (const Use &U : V->uses()) {
2664         if (++NumUses > Record.size())
2665           break;
2666         Order[&U] = Record[NumUses - 1];
2667       }
2668       if (Order.size() != Record.size() || NumUses > Record.size())
2669         // Mismatches can happen if the functions are being materialized lazily
2670         // (out-of-order), or a value has been upgraded.
2671         break;
2672
2673       V->sortUseList([&](const Use &L, const Use &R) {
2674         return Order.lookup(&L) < Order.lookup(&R);
2675       });
2676       break;
2677     }
2678     }
2679   }
2680 }
2681
2682 /// When we see the block for metadata, remember where it is and then skip it.
2683 /// This lets us lazily deserialize the metadata.
2684 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2685   // Save the current stream state.
2686   uint64_t CurBit = Stream.GetCurrentBitNo();
2687   DeferredMetadataInfo.push_back(CurBit);
2688
2689   // Skip over the block for now.
2690   if (Stream.SkipBlock())
2691     return error("Invalid record");
2692   return std::error_code();
2693 }
2694
2695 std::error_code BitcodeReader::materializeMetadata() {
2696   for (uint64_t BitPos : DeferredMetadataInfo) {
2697     // Move the bit stream to the saved position.
2698     Stream.JumpToBit(BitPos);
2699     if (std::error_code EC = parseMetadata())
2700       return EC;
2701   }
2702   DeferredMetadataInfo.clear();
2703   return std::error_code();
2704 }
2705
2706 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2707
2708 /// When we see the block for a function body, remember where it is and then
2709 /// skip it.  This lets us lazily deserialize the functions.
2710 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2711   // Get the function we are talking about.
2712   if (FunctionsWithBodies.empty())
2713     return error("Insufficient function protos");
2714
2715   Function *Fn = FunctionsWithBodies.back();
2716   FunctionsWithBodies.pop_back();
2717
2718   // Save the current stream state.
2719   uint64_t CurBit = Stream.GetCurrentBitNo();
2720   DeferredFunctionInfo[Fn] = CurBit;
2721
2722   // Skip over the function block for now.
2723   if (Stream.SkipBlock())
2724     return error("Invalid record");
2725   return std::error_code();
2726 }
2727
2728 std::error_code BitcodeReader::globalCleanup() {
2729   // Patch the initializers for globals and aliases up.
2730   resolveGlobalAndAliasInits();
2731   if (!GlobalInits.empty() || !AliasInits.empty())
2732     return error("Malformed global initializer set");
2733
2734   // Look for intrinsic functions which need to be upgraded at some point
2735   for (Function &F : *TheModule) {
2736     Function *NewFn;
2737     if (UpgradeIntrinsicFunction(&F, NewFn))
2738       UpgradedIntrinsics[&F] = NewFn;
2739   }
2740
2741   // Look for global variables which need to be renamed.
2742   for (GlobalVariable &GV : TheModule->globals())
2743     UpgradeGlobalVariable(&GV);
2744
2745   // Force deallocation of memory for these vectors to favor the client that
2746   // want lazy deserialization.
2747   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2748   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2749   return std::error_code();
2750 }
2751
2752 std::error_code BitcodeReader::parseModule(bool Resume,
2753                                            bool ShouldLazyLoadMetadata) {
2754   if (Resume)
2755     Stream.JumpToBit(NextUnreadBit);
2756   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2757     return error("Invalid record");
2758
2759   SmallVector<uint64_t, 64> Record;
2760   std::vector<std::string> SectionTable;
2761   std::vector<std::string> GCTable;
2762
2763   // Read all the records for this module.
2764   while (1) {
2765     BitstreamEntry Entry = Stream.advance();
2766
2767     switch (Entry.Kind) {
2768     case BitstreamEntry::Error:
2769       return error("Malformed block");
2770     case BitstreamEntry::EndBlock:
2771       return globalCleanup();
2772
2773     case BitstreamEntry::SubBlock:
2774       switch (Entry.ID) {
2775       default:  // Skip unknown content.
2776         if (Stream.SkipBlock())
2777           return error("Invalid record");
2778         break;
2779       case bitc::BLOCKINFO_BLOCK_ID:
2780         if (Stream.ReadBlockInfoBlock())
2781           return error("Malformed block");
2782         break;
2783       case bitc::PARAMATTR_BLOCK_ID:
2784         if (std::error_code EC = parseAttributeBlock())
2785           return EC;
2786         break;
2787       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2788         if (std::error_code EC = parseAttributeGroupBlock())
2789           return EC;
2790         break;
2791       case bitc::TYPE_BLOCK_ID_NEW:
2792         if (std::error_code EC = parseTypeTable())
2793           return EC;
2794         break;
2795       case bitc::VALUE_SYMTAB_BLOCK_ID:
2796         if (std::error_code EC = parseValueSymbolTable())
2797           return EC;
2798         SeenValueSymbolTable = true;
2799         break;
2800       case bitc::CONSTANTS_BLOCK_ID:
2801         if (std::error_code EC = parseConstants())
2802           return EC;
2803         if (std::error_code EC = resolveGlobalAndAliasInits())
2804           return EC;
2805         break;
2806       case bitc::METADATA_BLOCK_ID:
2807         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2808           if (std::error_code EC = rememberAndSkipMetadata())
2809             return EC;
2810           break;
2811         }
2812         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2813         if (std::error_code EC = parseMetadata())
2814           return EC;
2815         break;
2816       case bitc::FUNCTION_BLOCK_ID:
2817         // If this is the first function body we've seen, reverse the
2818         // FunctionsWithBodies list.
2819         if (!SeenFirstFunctionBody) {
2820           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2821           if (std::error_code EC = globalCleanup())
2822             return EC;
2823           SeenFirstFunctionBody = true;
2824         }
2825
2826         if (std::error_code EC = rememberAndSkipFunctionBody())
2827           return EC;
2828         // Suspend parsing when we reach the function bodies. Subsequent
2829         // materialization calls will resume it when necessary. If the bitcode
2830         // file is old, the symbol table will be at the end instead and will not
2831         // have been seen yet. In this case, just finish the parse now.
2832         if (SeenValueSymbolTable) {
2833           NextUnreadBit = Stream.GetCurrentBitNo();
2834           return std::error_code();
2835         }
2836         break;
2837       case bitc::USELIST_BLOCK_ID:
2838         if (std::error_code EC = parseUseLists())
2839           return EC;
2840         break;
2841       }
2842       continue;
2843
2844     case BitstreamEntry::Record:
2845       // The interesting case.
2846       break;
2847     }
2848
2849
2850     // Read a record.
2851     switch (Stream.readRecord(Entry.ID, Record)) {
2852     default: break;  // Default behavior, ignore unknown content.
2853     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2854       if (Record.size() < 1)
2855         return error("Invalid record");
2856       // Only version #0 and #1 are supported so far.
2857       unsigned module_version = Record[0];
2858       switch (module_version) {
2859         default:
2860           return error("Invalid value");
2861         case 0:
2862           UseRelativeIDs = false;
2863           break;
2864         case 1:
2865           UseRelativeIDs = true;
2866           break;
2867       }
2868       break;
2869     }
2870     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2871       std::string S;
2872       if (convertToString(Record, 0, S))
2873         return error("Invalid record");
2874       TheModule->setTargetTriple(S);
2875       break;
2876     }
2877     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2878       std::string S;
2879       if (convertToString(Record, 0, S))
2880         return error("Invalid record");
2881       TheModule->setDataLayout(S);
2882       break;
2883     }
2884     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2885       std::string S;
2886       if (convertToString(Record, 0, S))
2887         return error("Invalid record");
2888       TheModule->setModuleInlineAsm(S);
2889       break;
2890     }
2891     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2892       // FIXME: Remove in 4.0.
2893       std::string S;
2894       if (convertToString(Record, 0, S))
2895         return error("Invalid record");
2896       // Ignore value.
2897       break;
2898     }
2899     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2900       std::string S;
2901       if (convertToString(Record, 0, S))
2902         return error("Invalid record");
2903       SectionTable.push_back(S);
2904       break;
2905     }
2906     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2907       std::string S;
2908       if (convertToString(Record, 0, S))
2909         return error("Invalid record");
2910       GCTable.push_back(S);
2911       break;
2912     }
2913     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2914       if (Record.size() < 2)
2915         return error("Invalid record");
2916       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2917       unsigned ComdatNameSize = Record[1];
2918       std::string ComdatName;
2919       ComdatName.reserve(ComdatNameSize);
2920       for (unsigned i = 0; i != ComdatNameSize; ++i)
2921         ComdatName += (char)Record[2 + i];
2922       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2923       C->setSelectionKind(SK);
2924       ComdatList.push_back(C);
2925       break;
2926     }
2927     // GLOBALVAR: [pointer type, isconst, initid,
2928     //             linkage, alignment, section, visibility, threadlocal,
2929     //             unnamed_addr, externally_initialized, dllstorageclass,
2930     //             comdat]
2931     case bitc::MODULE_CODE_GLOBALVAR: {
2932       if (Record.size() < 6)
2933         return error("Invalid record");
2934       Type *Ty = getTypeByID(Record[0]);
2935       if (!Ty)
2936         return error("Invalid record");
2937       bool isConstant = Record[1] & 1;
2938       bool explicitType = Record[1] & 2;
2939       unsigned AddressSpace;
2940       if (explicitType) {
2941         AddressSpace = Record[1] >> 2;
2942       } else {
2943         if (!Ty->isPointerTy())
2944           return error("Invalid type for value");
2945         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2946         Ty = cast<PointerType>(Ty)->getElementType();
2947       }
2948
2949       uint64_t RawLinkage = Record[3];
2950       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2951       unsigned Alignment;
2952       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2953         return EC;
2954       std::string Section;
2955       if (Record[5]) {
2956         if (Record[5]-1 >= SectionTable.size())
2957           return error("Invalid ID");
2958         Section = SectionTable[Record[5]-1];
2959       }
2960       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2961       // Local linkage must have default visibility.
2962       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2963         // FIXME: Change to an error if non-default in 4.0.
2964         Visibility = getDecodedVisibility(Record[6]);
2965
2966       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2967       if (Record.size() > 7)
2968         TLM = getDecodedThreadLocalMode(Record[7]);
2969
2970       bool UnnamedAddr = false;
2971       if (Record.size() > 8)
2972         UnnamedAddr = Record[8];
2973
2974       bool ExternallyInitialized = false;
2975       if (Record.size() > 9)
2976         ExternallyInitialized = Record[9];
2977
2978       GlobalVariable *NewGV =
2979         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2980                            TLM, AddressSpace, ExternallyInitialized);
2981       NewGV->setAlignment(Alignment);
2982       if (!Section.empty())
2983         NewGV->setSection(Section);
2984       NewGV->setVisibility(Visibility);
2985       NewGV->setUnnamedAddr(UnnamedAddr);
2986
2987       if (Record.size() > 10)
2988         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2989       else
2990         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2991
2992       ValueList.push_back(NewGV);
2993
2994       // Remember which value to use for the global initializer.
2995       if (unsigned InitID = Record[2])
2996         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2997
2998       if (Record.size() > 11) {
2999         if (unsigned ComdatID = Record[11]) {
3000           if (ComdatID > ComdatList.size())
3001             return error("Invalid global variable comdat ID");
3002           NewGV->setComdat(ComdatList[ComdatID - 1]);
3003         }
3004       } else if (hasImplicitComdat(RawLinkage)) {
3005         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3006       }
3007       break;
3008     }
3009     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
3010     //             alignment, section, visibility, gc, unnamed_addr,
3011     //             prologuedata, dllstorageclass, comdat, prefixdata]
3012     case bitc::MODULE_CODE_FUNCTION: {
3013       if (Record.size() < 8)
3014         return error("Invalid record");
3015       Type *Ty = getTypeByID(Record[0]);
3016       if (!Ty)
3017         return error("Invalid record");
3018       if (auto *PTy = dyn_cast<PointerType>(Ty))
3019         Ty = PTy->getElementType();
3020       auto *FTy = dyn_cast<FunctionType>(Ty);
3021       if (!FTy)
3022         return error("Invalid type for value");
3023
3024       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3025                                         "", TheModule);
3026
3027       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3028       bool isProto = Record[2];
3029       uint64_t RawLinkage = Record[3];
3030       Func->setLinkage(getDecodedLinkage(RawLinkage));
3031       Func->setAttributes(getAttributes(Record[4]));
3032
3033       unsigned Alignment;
3034       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3035         return EC;
3036       Func->setAlignment(Alignment);
3037       if (Record[6]) {
3038         if (Record[6]-1 >= SectionTable.size())
3039           return error("Invalid ID");
3040         Func->setSection(SectionTable[Record[6]-1]);
3041       }
3042       // Local linkage must have default visibility.
3043       if (!Func->hasLocalLinkage())
3044         // FIXME: Change to an error if non-default in 4.0.
3045         Func->setVisibility(getDecodedVisibility(Record[7]));
3046       if (Record.size() > 8 && Record[8]) {
3047         if (Record[8]-1 >= GCTable.size())
3048           return error("Invalid ID");
3049         Func->setGC(GCTable[Record[8]-1].c_str());
3050       }
3051       bool UnnamedAddr = false;
3052       if (Record.size() > 9)
3053         UnnamedAddr = Record[9];
3054       Func->setUnnamedAddr(UnnamedAddr);
3055       if (Record.size() > 10 && Record[10] != 0)
3056         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3057
3058       if (Record.size() > 11)
3059         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3060       else
3061         upgradeDLLImportExportLinkage(Func, RawLinkage);
3062
3063       if (Record.size() > 12) {
3064         if (unsigned ComdatID = Record[12]) {
3065           if (ComdatID > ComdatList.size())
3066             return error("Invalid function comdat ID");
3067           Func->setComdat(ComdatList[ComdatID - 1]);
3068         }
3069       } else if (hasImplicitComdat(RawLinkage)) {
3070         Func->setComdat(reinterpret_cast<Comdat *>(1));
3071       }
3072
3073       if (Record.size() > 13 && Record[13] != 0)
3074         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3075
3076       if (Record.size() > 14 && Record[14] != 0)
3077         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3078
3079       ValueList.push_back(Func);
3080
3081       // If this is a function with a body, remember the prototype we are
3082       // creating now, so that we can match up the body with them later.
3083       if (!isProto) {
3084         Func->setIsMaterializable(true);
3085         FunctionsWithBodies.push_back(Func);
3086         DeferredFunctionInfo[Func] = 0;
3087       }
3088       break;
3089     }
3090     // ALIAS: [alias type, aliasee val#, linkage]
3091     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3092     case bitc::MODULE_CODE_ALIAS: {
3093       if (Record.size() < 3)
3094         return error("Invalid record");
3095       Type *Ty = getTypeByID(Record[0]);
3096       if (!Ty)
3097         return error("Invalid record");
3098       auto *PTy = dyn_cast<PointerType>(Ty);
3099       if (!PTy)
3100         return error("Invalid type for value");
3101
3102       auto *NewGA =
3103           GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3104       // Old bitcode files didn't have visibility field.
3105       // Local linkage must have default visibility.
3106       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3107         // FIXME: Change to an error if non-default in 4.0.
3108         NewGA->setVisibility(getDecodedVisibility(Record[3]));
3109       if (Record.size() > 4)
3110         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3111       else
3112         upgradeDLLImportExportLinkage(NewGA, Record[2]);
3113       if (Record.size() > 5)
3114         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3115       if (Record.size() > 6)
3116         NewGA->setUnnamedAddr(Record[6]);
3117       ValueList.push_back(NewGA);
3118       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3119       break;
3120     }
3121     /// MODULE_CODE_PURGEVALS: [numvals]
3122     case bitc::MODULE_CODE_PURGEVALS:
3123       // Trim down the value list to the specified size.
3124       if (Record.size() < 1 || Record[0] > ValueList.size())
3125         return error("Invalid record");
3126       ValueList.shrinkTo(Record[0]);
3127       break;
3128     }
3129     Record.clear();
3130   }
3131 }
3132
3133 std::error_code
3134 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3135                                 Module *M, bool ShouldLazyLoadMetadata) {
3136   TheModule = M;
3137
3138   if (std::error_code EC = initStream(std::move(Streamer)))
3139     return EC;
3140
3141   // Sniff for the signature.
3142   if (Stream.Read(8) != 'B' ||
3143       Stream.Read(8) != 'C' ||
3144       Stream.Read(4) != 0x0 ||
3145       Stream.Read(4) != 0xC ||
3146       Stream.Read(4) != 0xE ||
3147       Stream.Read(4) != 0xD)
3148     return error("Invalid bitcode signature");
3149
3150   // We expect a number of well-defined blocks, though we don't necessarily
3151   // need to understand them all.
3152   while (1) {
3153     if (Stream.AtEndOfStream()) {
3154       // We didn't really read a proper Module.
3155       return error("Malformed IR file");
3156     }
3157
3158     BitstreamEntry Entry =
3159       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3160
3161     if (Entry.Kind != BitstreamEntry::SubBlock)
3162       return error("Malformed block");
3163
3164     if (Entry.ID == bitc::MODULE_BLOCK_ID)
3165       return parseModule(false, ShouldLazyLoadMetadata);
3166
3167     if (Stream.SkipBlock())
3168       return error("Invalid record");
3169   }
3170 }
3171
3172 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3173   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3174     return error("Invalid record");
3175
3176   SmallVector<uint64_t, 64> Record;
3177
3178   std::string Triple;
3179   // Read all the records for this module.
3180   while (1) {
3181     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3182
3183     switch (Entry.Kind) {
3184     case BitstreamEntry::SubBlock: // Handled for us already.
3185     case BitstreamEntry::Error:
3186       return error("Malformed block");
3187     case BitstreamEntry::EndBlock:
3188       return Triple;
3189     case BitstreamEntry::Record:
3190       // The interesting case.
3191       break;
3192     }
3193
3194     // Read a record.
3195     switch (Stream.readRecord(Entry.ID, Record)) {
3196     default: break;  // Default behavior, ignore unknown content.
3197     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3198       std::string S;
3199       if (convertToString(Record, 0, S))
3200         return error("Invalid record");
3201       Triple = S;
3202       break;
3203     }
3204     }
3205     Record.clear();
3206   }
3207   llvm_unreachable("Exit infinite loop");
3208 }
3209
3210 ErrorOr<std::string> BitcodeReader::parseTriple() {
3211   if (std::error_code EC = initStream(nullptr))
3212     return EC;
3213
3214   // Sniff for the signature.
3215   if (Stream.Read(8) != 'B' ||
3216       Stream.Read(8) != 'C' ||
3217       Stream.Read(4) != 0x0 ||
3218       Stream.Read(4) != 0xC ||
3219       Stream.Read(4) != 0xE ||
3220       Stream.Read(4) != 0xD)
3221     return error("Invalid bitcode signature");
3222
3223   // We expect a number of well-defined blocks, though we don't necessarily
3224   // need to understand them all.
3225   while (1) {
3226     BitstreamEntry Entry = Stream.advance();
3227
3228     switch (Entry.Kind) {
3229     case BitstreamEntry::Error:
3230       return error("Malformed block");
3231     case BitstreamEntry::EndBlock:
3232       return std::error_code();
3233
3234     case BitstreamEntry::SubBlock:
3235       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3236         return parseModuleTriple();
3237
3238       // Ignore other sub-blocks.
3239       if (Stream.SkipBlock())
3240         return error("Malformed block");
3241       continue;
3242
3243     case BitstreamEntry::Record:
3244       Stream.skipRecord(Entry.ID);
3245       continue;
3246     }
3247   }
3248 }
3249
3250 /// Parse metadata attachments.
3251 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3252   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3253     return error("Invalid record");
3254
3255   SmallVector<uint64_t, 64> Record;
3256   while (1) {
3257     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3258
3259     switch (Entry.Kind) {
3260     case BitstreamEntry::SubBlock: // Handled for us already.
3261     case BitstreamEntry::Error:
3262       return error("Malformed block");
3263     case BitstreamEntry::EndBlock:
3264       return std::error_code();
3265     case BitstreamEntry::Record:
3266       // The interesting case.
3267       break;
3268     }
3269
3270     // Read a metadata attachment record.
3271     Record.clear();
3272     switch (Stream.readRecord(Entry.ID, Record)) {
3273     default:  // Default behavior: ignore.
3274       break;
3275     case bitc::METADATA_ATTACHMENT: {
3276       unsigned RecordLength = Record.size();
3277       if (Record.empty())
3278         return error("Invalid record");
3279       if (RecordLength % 2 == 0) {
3280         // A function attachment.
3281         for (unsigned I = 0; I != RecordLength; I += 2) {
3282           auto K = MDKindMap.find(Record[I]);
3283           if (K == MDKindMap.end())
3284             return error("Invalid ID");
3285           Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3286           F.setMetadata(K->second, cast<MDNode>(MD));
3287         }
3288         continue;
3289       }
3290
3291       // An instruction attachment.
3292       Instruction *Inst = InstructionList[Record[0]];
3293       for (unsigned i = 1; i != RecordLength; i = i+2) {
3294         unsigned Kind = Record[i];
3295         DenseMap<unsigned, unsigned>::iterator I =
3296           MDKindMap.find(Kind);
3297         if (I == MDKindMap.end())
3298           return error("Invalid ID");
3299         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3300         if (isa<LocalAsMetadata>(Node))
3301           // Drop the attachment.  This used to be legal, but there's no
3302           // upgrade path.
3303           break;
3304         Inst->setMetadata(I->second, cast<MDNode>(Node));
3305         if (I->second == LLVMContext::MD_tbaa)
3306           InstsWithTBAATag.push_back(Inst);
3307       }
3308       break;
3309     }
3310     }
3311   }
3312 }
3313
3314 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3315                                               Type *ValType, Type *PtrType) {
3316   if (!isa<PointerType>(PtrType))
3317     return error(DH, "Load/Store operand is not a pointer type");
3318   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3319
3320   if (ValType && ValType != ElemType)
3321     return error(DH, "Explicit load/store type does not match pointee type of "
3322                      "pointer operand");
3323   if (!PointerType::isLoadableOrStorableType(ElemType))
3324     return error(DH, "Cannot load/store from pointer");
3325   return std::error_code();
3326 }
3327
3328 /// Lazily parse the specified function body block.
3329 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3330   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3331     return error("Invalid record");
3332
3333   InstructionList.clear();
3334   unsigned ModuleValueListSize = ValueList.size();
3335   unsigned ModuleMDValueListSize = MDValueList.size();
3336
3337   // Add all the function arguments to the value table.
3338   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3339     ValueList.push_back(I);
3340
3341   unsigned NextValueNo = ValueList.size();
3342   BasicBlock *CurBB = nullptr;
3343   unsigned CurBBNo = 0;
3344
3345   DebugLoc LastLoc;
3346   auto getLastInstruction = [&]() -> Instruction * {
3347     if (CurBB && !CurBB->empty())
3348       return &CurBB->back();
3349     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3350              !FunctionBBs[CurBBNo - 1]->empty())
3351       return &FunctionBBs[CurBBNo - 1]->back();
3352     return nullptr;
3353   };
3354
3355   // Read all the records.
3356   SmallVector<uint64_t, 64> Record;
3357   while (1) {
3358     BitstreamEntry Entry = Stream.advance();
3359
3360     switch (Entry.Kind) {
3361     case BitstreamEntry::Error:
3362       return error("Malformed block");
3363     case BitstreamEntry::EndBlock:
3364       goto OutOfRecordLoop;
3365
3366     case BitstreamEntry::SubBlock:
3367       switch (Entry.ID) {
3368       default:  // Skip unknown content.
3369         if (Stream.SkipBlock())
3370           return error("Invalid record");
3371         break;
3372       case bitc::CONSTANTS_BLOCK_ID:
3373         if (std::error_code EC = parseConstants())
3374           return EC;
3375         NextValueNo = ValueList.size();
3376         break;
3377       case bitc::VALUE_SYMTAB_BLOCK_ID:
3378         if (std::error_code EC = parseValueSymbolTable())
3379           return EC;
3380         break;
3381       case bitc::METADATA_ATTACHMENT_ID:
3382         if (std::error_code EC = parseMetadataAttachment(*F))
3383           return EC;
3384         break;
3385       case bitc::METADATA_BLOCK_ID:
3386         if (std::error_code EC = parseMetadata())
3387           return EC;
3388         break;
3389       case bitc::USELIST_BLOCK_ID:
3390         if (std::error_code EC = parseUseLists())
3391           return EC;
3392         break;
3393       }
3394       continue;
3395
3396     case BitstreamEntry::Record:
3397       // The interesting case.
3398       break;
3399     }
3400
3401     // Read a record.
3402     Record.clear();
3403     Instruction *I = nullptr;
3404     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3405     switch (BitCode) {
3406     default: // Default behavior: reject
3407       return error("Invalid value");
3408     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3409       if (Record.size() < 1 || Record[0] == 0)
3410         return error("Invalid record");
3411       // Create all the basic blocks for the function.
3412       FunctionBBs.resize(Record[0]);
3413
3414       // See if anything took the address of blocks in this function.
3415       auto BBFRI = BasicBlockFwdRefs.find(F);
3416       if (BBFRI == BasicBlockFwdRefs.end()) {
3417         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3418           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3419       } else {
3420         auto &BBRefs = BBFRI->second;
3421         // Check for invalid basic block references.
3422         if (BBRefs.size() > FunctionBBs.size())
3423           return error("Invalid ID");
3424         assert(!BBRefs.empty() && "Unexpected empty array");
3425         assert(!BBRefs.front() && "Invalid reference to entry block");
3426         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3427              ++I)
3428           if (I < RE && BBRefs[I]) {
3429             BBRefs[I]->insertInto(F);
3430             FunctionBBs[I] = BBRefs[I];
3431           } else {
3432             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3433           }
3434
3435         // Erase from the table.
3436         BasicBlockFwdRefs.erase(BBFRI);
3437       }
3438
3439       CurBB = FunctionBBs[0];
3440       continue;
3441     }
3442
3443     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3444       // This record indicates that the last instruction is at the same
3445       // location as the previous instruction with a location.
3446       I = getLastInstruction();
3447
3448       if (!I)
3449         return error("Invalid record");
3450       I->setDebugLoc(LastLoc);
3451       I = nullptr;
3452       continue;
3453
3454     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3455       I = getLastInstruction();
3456       if (!I || Record.size() < 4)
3457         return error("Invalid record");
3458
3459       unsigned Line = Record[0], Col = Record[1];
3460       unsigned ScopeID = Record[2], IAID = Record[3];
3461
3462       MDNode *Scope = nullptr, *IA = nullptr;
3463       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3464       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3465       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3466       I->setDebugLoc(LastLoc);
3467       I = nullptr;
3468       continue;
3469     }
3470
3471     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3472       unsigned OpNum = 0;
3473       Value *LHS, *RHS;
3474       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3475           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3476           OpNum+1 > Record.size())
3477         return error("Invalid record");
3478
3479       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3480       if (Opc == -1)
3481         return error("Invalid record");
3482       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3483       InstructionList.push_back(I);
3484       if (OpNum < Record.size()) {
3485         if (Opc == Instruction::Add ||
3486             Opc == Instruction::Sub ||
3487             Opc == Instruction::Mul ||
3488             Opc == Instruction::Shl) {
3489           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3490             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3491           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3492             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3493         } else if (Opc == Instruction::SDiv ||
3494                    Opc == Instruction::UDiv ||
3495                    Opc == Instruction::LShr ||
3496                    Opc == Instruction::AShr) {
3497           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3498             cast<BinaryOperator>(I)->setIsExact(true);
3499         } else if (isa<FPMathOperator>(I)) {
3500           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3501           if (FMF.any())
3502             I->setFastMathFlags(FMF);
3503         }
3504
3505       }
3506       break;
3507     }
3508     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3509       unsigned OpNum = 0;
3510       Value *Op;
3511       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3512           OpNum+2 != Record.size())
3513         return error("Invalid record");
3514
3515       Type *ResTy = getTypeByID(Record[OpNum]);
3516       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3517       if (Opc == -1 || !ResTy)
3518         return error("Invalid record");
3519       Instruction *Temp = nullptr;
3520       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3521         if (Temp) {
3522           InstructionList.push_back(Temp);
3523           CurBB->getInstList().push_back(Temp);
3524         }
3525       } else {
3526         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3527       }
3528       InstructionList.push_back(I);
3529       break;
3530     }
3531     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3532     case bitc::FUNC_CODE_INST_GEP_OLD:
3533     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3534       unsigned OpNum = 0;
3535
3536       Type *Ty;
3537       bool InBounds;
3538
3539       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3540         InBounds = Record[OpNum++];
3541         Ty = getTypeByID(Record[OpNum++]);
3542       } else {
3543         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3544         Ty = nullptr;
3545       }
3546
3547       Value *BasePtr;
3548       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3549         return error("Invalid record");
3550
3551       if (!Ty)
3552         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3553                  ->getElementType();
3554       else if (Ty !=
3555                cast<SequentialType>(BasePtr->getType()->getScalarType())
3556                    ->getElementType())
3557         return error(
3558             "Explicit gep type does not match pointee type of pointer operand");
3559
3560       SmallVector<Value*, 16> GEPIdx;
3561       while (OpNum != Record.size()) {
3562         Value *Op;
3563         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3564           return error("Invalid record");
3565         GEPIdx.push_back(Op);
3566       }
3567
3568       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3569
3570       InstructionList.push_back(I);
3571       if (InBounds)
3572         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3573       break;
3574     }
3575
3576     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3577                                        // EXTRACTVAL: [opty, opval, n x indices]
3578       unsigned OpNum = 0;
3579       Value *Agg;
3580       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3581         return error("Invalid record");
3582
3583       unsigned RecSize = Record.size();
3584       if (OpNum == RecSize)
3585         return error("EXTRACTVAL: Invalid instruction with 0 indices");
3586
3587       SmallVector<unsigned, 4> EXTRACTVALIdx;
3588       Type *CurTy = Agg->getType();
3589       for (; OpNum != RecSize; ++OpNum) {
3590         bool IsArray = CurTy->isArrayTy();
3591         bool IsStruct = CurTy->isStructTy();
3592         uint64_t Index = Record[OpNum];
3593
3594         if (!IsStruct && !IsArray)
3595           return error("EXTRACTVAL: Invalid type");
3596         if ((unsigned)Index != Index)
3597           return error("Invalid value");
3598         if (IsStruct && Index >= CurTy->subtypes().size())
3599           return error("EXTRACTVAL: Invalid struct index");
3600         if (IsArray && Index >= CurTy->getArrayNumElements())
3601           return error("EXTRACTVAL: Invalid array index");
3602         EXTRACTVALIdx.push_back((unsigned)Index);
3603
3604         if (IsStruct)
3605           CurTy = CurTy->subtypes()[Index];
3606         else
3607           CurTy = CurTy->subtypes()[0];
3608       }
3609
3610       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3611       InstructionList.push_back(I);
3612       break;
3613     }
3614
3615     case bitc::FUNC_CODE_INST_INSERTVAL: {
3616                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3617       unsigned OpNum = 0;
3618       Value *Agg;
3619       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3620         return error("Invalid record");
3621       Value *Val;
3622       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3623         return error("Invalid record");
3624
3625       unsigned RecSize = Record.size();
3626       if (OpNum == RecSize)
3627         return error("INSERTVAL: Invalid instruction with 0 indices");
3628
3629       SmallVector<unsigned, 4> INSERTVALIdx;
3630       Type *CurTy = Agg->getType();
3631       for (; OpNum != RecSize; ++OpNum) {
3632         bool IsArray = CurTy->isArrayTy();
3633         bool IsStruct = CurTy->isStructTy();
3634         uint64_t Index = Record[OpNum];
3635
3636         if (!IsStruct && !IsArray)
3637           return error("INSERTVAL: Invalid type");
3638         if ((unsigned)Index != Index)
3639           return error("Invalid value");
3640         if (IsStruct && Index >= CurTy->subtypes().size())
3641           return error("INSERTVAL: Invalid struct index");
3642         if (IsArray && Index >= CurTy->getArrayNumElements())
3643           return error("INSERTVAL: Invalid array index");
3644
3645         INSERTVALIdx.push_back((unsigned)Index);
3646         if (IsStruct)
3647           CurTy = CurTy->subtypes()[Index];
3648         else
3649           CurTy = CurTy->subtypes()[0];
3650       }
3651
3652       if (CurTy != Val->getType())
3653         return error("Inserted value type doesn't match aggregate type");
3654
3655       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3656       InstructionList.push_back(I);
3657       break;
3658     }
3659
3660     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3661       // obsolete form of select
3662       // handles select i1 ... in old bitcode
3663       unsigned OpNum = 0;
3664       Value *TrueVal, *FalseVal, *Cond;
3665       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3666           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3667           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3668         return error("Invalid record");
3669
3670       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3671       InstructionList.push_back(I);
3672       break;
3673     }
3674
3675     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3676       // new form of select
3677       // handles select i1 or select [N x i1]
3678       unsigned OpNum = 0;
3679       Value *TrueVal, *FalseVal, *Cond;
3680       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3681           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3682           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3683         return error("Invalid record");
3684
3685       // select condition can be either i1 or [N x i1]
3686       if (VectorType* vector_type =
3687           dyn_cast<VectorType>(Cond->getType())) {
3688         // expect <n x i1>
3689         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3690           return error("Invalid type for value");
3691       } else {
3692         // expect i1
3693         if (Cond->getType() != Type::getInt1Ty(Context))
3694           return error("Invalid type for value");
3695       }
3696
3697       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3698       InstructionList.push_back(I);
3699       break;
3700     }
3701
3702     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3703       unsigned OpNum = 0;
3704       Value *Vec, *Idx;
3705       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3706           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3707         return error("Invalid record");
3708       if (!Vec->getType()->isVectorTy())
3709         return error("Invalid type for value");
3710       I = ExtractElementInst::Create(Vec, Idx);
3711       InstructionList.push_back(I);
3712       break;
3713     }
3714
3715     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3716       unsigned OpNum = 0;
3717       Value *Vec, *Elt, *Idx;
3718       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3719         return error("Invalid record");
3720       if (!Vec->getType()->isVectorTy())
3721         return error("Invalid type for value");
3722       if (popValue(Record, OpNum, NextValueNo,
3723                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3724           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3725         return error("Invalid record");
3726       I = InsertElementInst::Create(Vec, Elt, Idx);
3727       InstructionList.push_back(I);
3728       break;
3729     }
3730
3731     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3732       unsigned OpNum = 0;
3733       Value *Vec1, *Vec2, *Mask;
3734       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3735           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3736         return error("Invalid record");
3737
3738       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3739         return error("Invalid record");
3740       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3741         return error("Invalid type for value");
3742       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3743       InstructionList.push_back(I);
3744       break;
3745     }
3746
3747     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3748       // Old form of ICmp/FCmp returning bool
3749       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3750       // both legal on vectors but had different behaviour.
3751     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3752       // FCmp/ICmp returning bool or vector of bool
3753
3754       unsigned OpNum = 0;
3755       Value *LHS, *RHS;
3756       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3757           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3758         return error("Invalid record");
3759
3760       unsigned PredVal = Record[OpNum];
3761       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3762       FastMathFlags FMF;
3763       if (IsFP && Record.size() > OpNum+1)
3764         FMF = getDecodedFastMathFlags(Record[++OpNum]);
3765
3766       if (OpNum+1 != Record.size())
3767         return error("Invalid record");
3768
3769       if (LHS->getType()->isFPOrFPVectorTy())
3770         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3771       else
3772         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3773
3774       if (FMF.any())
3775         I->setFastMathFlags(FMF);
3776       InstructionList.push_back(I);
3777       break;
3778     }
3779
3780     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3781       {
3782         unsigned Size = Record.size();
3783         if (Size == 0) {
3784           I = ReturnInst::Create(Context);
3785           InstructionList.push_back(I);
3786           break;
3787         }
3788
3789         unsigned OpNum = 0;
3790         Value *Op = nullptr;
3791         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3792           return error("Invalid record");
3793         if (OpNum != Record.size())
3794           return error("Invalid record");
3795
3796         I = ReturnInst::Create(Context, Op);
3797         InstructionList.push_back(I);
3798         break;
3799       }
3800     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3801       if (Record.size() != 1 && Record.size() != 3)
3802         return error("Invalid record");
3803       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3804       if (!TrueDest)
3805         return error("Invalid record");
3806
3807       if (Record.size() == 1) {
3808         I = BranchInst::Create(TrueDest);
3809         InstructionList.push_back(I);
3810       }
3811       else {
3812         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3813         Value *Cond = getValue(Record, 2, NextValueNo,
3814                                Type::getInt1Ty(Context));
3815         if (!FalseDest || !Cond)
3816           return error("Invalid record");
3817         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3818         InstructionList.push_back(I);
3819       }
3820       break;
3821     }
3822     // CLEANUPRET: [] or [ty,val] or [bb#] or [ty,val,bb#]
3823     case bitc::FUNC_CODE_INST_CLEANUPRET: {
3824       if (Record.size() < 2)
3825         return error("Invalid record");
3826       unsigned Idx = 0;
3827       bool HasReturnValue = !!Record[Idx++];
3828       bool HasUnwindDest = !!Record[Idx++];
3829       Value *RetVal = nullptr;
3830       BasicBlock *UnwindDest = nullptr;
3831
3832       if (HasReturnValue && getValueTypePair(Record, Idx, NextValueNo, RetVal))
3833         return error("Invalid record");
3834       if (HasUnwindDest) {
3835         if (Idx == Record.size())
3836           return error("Invalid record");
3837         UnwindDest = getBasicBlock(Record[Idx++]);
3838         if (!UnwindDest)
3839           return error("Invalid record");
3840       }
3841
3842       if (Record.size() != Idx)
3843         return error("Invalid record");
3844
3845       I = CleanupReturnInst::Create(Context, RetVal, UnwindDest);
3846       InstructionList.push_back(I);
3847       break;
3848     }
3849     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [bb#]
3850       if (Record.size() != 1 && Record.size() != 3)
3851         return error("Invalid record");
3852       unsigned Idx = 0;
3853       BasicBlock *BB = getBasicBlock(Record[Idx++]);
3854       if (!BB)
3855         return error("Invalid record");
3856       Value *RetVal = nullptr;
3857       if (Record.size() == 3 &&
3858           getValueTypePair(Record, Idx, NextValueNo, RetVal))
3859         return error("Invalid record");
3860
3861       I = CatchReturnInst::Create(BB, RetVal);
3862       InstructionList.push_back(I);
3863       break;
3864     }
3865     case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [ty,bb#,bb#,num,(ty,val)*]
3866       if (Record.size() < 4)
3867         return error("Invalid record");
3868       unsigned Idx = 0;
3869       Type *Ty = getTypeByID(Record[Idx++]);
3870       if (!Ty)
3871         return error("Invalid record");
3872       BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
3873       if (!NormalBB)
3874         return error("Invalid record");
3875       BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
3876       if (!UnwindBB)
3877         return error("Invalid record");
3878       unsigned NumArgOperands = Record[Idx++];
3879       SmallVector<Value *, 2> Args;
3880       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3881         Value *Val;
3882         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3883           return error("Invalid record");
3884         Args.push_back(Val);
3885       }
3886       if (Record.size() != Idx)
3887         return error("Invalid record");
3888
3889       I = CatchPadInst::Create(Ty, NormalBB, UnwindBB, Args);
3890       InstructionList.push_back(I);
3891       break;
3892     }
3893     case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
3894       if (Record.size() < 1)
3895         return error("Invalid record");
3896       unsigned Idx = 0;
3897       bool HasUnwindDest = !!Record[Idx++];
3898       BasicBlock *UnwindDest = nullptr;
3899       if (HasUnwindDest) {
3900         if (Idx == Record.size())
3901           return error("Invalid record");
3902         UnwindDest = getBasicBlock(Record[Idx++]);
3903         if (!UnwindDest)
3904           return error("Invalid record");
3905       }
3906       unsigned NumArgOperands = Record[Idx++];
3907       SmallVector<Value *, 2> Args;
3908       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3909         Value *Val;
3910         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3911           return error("Invalid record");
3912         Args.push_back(Val);
3913       }
3914       if (Record.size() != Idx)
3915         return error("Invalid record");
3916
3917       I = TerminatePadInst::Create(Context, UnwindDest, Args);
3918       InstructionList.push_back(I);
3919       break;
3920     }
3921     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [ty, num,(ty,val)*]
3922       if (Record.size() < 2)
3923         return error("Invalid record");
3924       unsigned Idx = 0;
3925       Type *Ty = getTypeByID(Record[Idx++]);
3926       if (!Ty)
3927         return error("Invalid record");
3928       unsigned NumArgOperands = Record[Idx++];
3929       SmallVector<Value *, 2> Args;
3930       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3931         Value *Val;
3932         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3933           return error("Invalid record");
3934         Args.push_back(Val);
3935       }
3936       if (Record.size() != Idx)
3937         return error("Invalid record");
3938
3939       I = CleanupPadInst::Create(Ty, Args);
3940       InstructionList.push_back(I);
3941       break;
3942     }
3943     case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
3944       if (Record.size() > 1)
3945         return error("Invalid record");
3946       BasicBlock *BB = nullptr;
3947       if (Record.size() == 1) {
3948         BB = getBasicBlock(Record[0]);
3949         if (!BB)
3950           return error("Invalid record");
3951       }
3952       I = CatchEndPadInst::Create(Context, BB);
3953       InstructionList.push_back(I);
3954       break;
3955     }
3956     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3957       // Check magic
3958       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3959         // "New" SwitchInst format with case ranges. The changes to write this
3960         // format were reverted but we still recognize bitcode that uses it.
3961         // Hopefully someday we will have support for case ranges and can use
3962         // this format again.
3963
3964         Type *OpTy = getTypeByID(Record[1]);
3965         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3966
3967         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3968         BasicBlock *Default = getBasicBlock(Record[3]);
3969         if (!OpTy || !Cond || !Default)
3970           return error("Invalid record");
3971
3972         unsigned NumCases = Record[4];
3973
3974         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3975         InstructionList.push_back(SI);
3976
3977         unsigned CurIdx = 5;
3978         for (unsigned i = 0; i != NumCases; ++i) {
3979           SmallVector<ConstantInt*, 1> CaseVals;
3980           unsigned NumItems = Record[CurIdx++];
3981           for (unsigned ci = 0; ci != NumItems; ++ci) {
3982             bool isSingleNumber = Record[CurIdx++];
3983
3984             APInt Low;
3985             unsigned ActiveWords = 1;
3986             if (ValueBitWidth > 64)
3987               ActiveWords = Record[CurIdx++];
3988             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3989                                 ValueBitWidth);
3990             CurIdx += ActiveWords;
3991
3992             if (!isSingleNumber) {
3993               ActiveWords = 1;
3994               if (ValueBitWidth > 64)
3995                 ActiveWords = Record[CurIdx++];
3996               APInt High = readWideAPInt(
3997                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3998               CurIdx += ActiveWords;
3999
4000               // FIXME: It is not clear whether values in the range should be
4001               // compared as signed or unsigned values. The partially
4002               // implemented changes that used this format in the past used
4003               // unsigned comparisons.
4004               for ( ; Low.ule(High); ++Low)
4005                 CaseVals.push_back(ConstantInt::get(Context, Low));
4006             } else
4007               CaseVals.push_back(ConstantInt::get(Context, Low));
4008           }
4009           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4010           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4011                  cve = CaseVals.end(); cvi != cve; ++cvi)
4012             SI->addCase(*cvi, DestBB);
4013         }
4014         I = SI;
4015         break;
4016       }
4017
4018       // Old SwitchInst format without case ranges.
4019
4020       if (Record.size() < 3 || (Record.size() & 1) == 0)
4021         return error("Invalid record");
4022       Type *OpTy = getTypeByID(Record[0]);
4023       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4024       BasicBlock *Default = getBasicBlock(Record[2]);
4025       if (!OpTy || !Cond || !Default)
4026         return error("Invalid record");
4027       unsigned NumCases = (Record.size()-3)/2;
4028       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4029       InstructionList.push_back(SI);
4030       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4031         ConstantInt *CaseVal =
4032           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4033         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4034         if (!CaseVal || !DestBB) {
4035           delete SI;
4036           return error("Invalid record");
4037         }
4038         SI->addCase(CaseVal, DestBB);
4039       }
4040       I = SI;
4041       break;
4042     }
4043     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4044       if (Record.size() < 2)
4045         return error("Invalid record");
4046       Type *OpTy = getTypeByID(Record[0]);
4047       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4048       if (!OpTy || !Address)
4049         return error("Invalid record");
4050       unsigned NumDests = Record.size()-2;
4051       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4052       InstructionList.push_back(IBI);
4053       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4054         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4055           IBI->addDestination(DestBB);
4056         } else {
4057           delete IBI;
4058           return error("Invalid record");
4059         }
4060       }
4061       I = IBI;
4062       break;
4063     }
4064
4065     case bitc::FUNC_CODE_INST_INVOKE: {
4066       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4067       if (Record.size() < 4)
4068         return error("Invalid record");
4069       unsigned OpNum = 0;
4070       AttributeSet PAL = getAttributes(Record[OpNum++]);
4071       unsigned CCInfo = Record[OpNum++];
4072       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4073       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4074
4075       FunctionType *FTy = nullptr;
4076       if (CCInfo >> 13 & 1 &&
4077           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4078         return error("Explicit invoke type is not a function type");
4079
4080       Value *Callee;
4081       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4082         return error("Invalid record");
4083
4084       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4085       if (!CalleeTy)
4086         return error("Callee is not a pointer");
4087       if (!FTy) {
4088         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4089         if (!FTy)
4090           return error("Callee is not of pointer to function type");
4091       } else if (CalleeTy->getElementType() != FTy)
4092         return error("Explicit invoke type does not match pointee type of "
4093                      "callee operand");
4094       if (Record.size() < FTy->getNumParams() + OpNum)
4095         return error("Insufficient operands to call");
4096
4097       SmallVector<Value*, 16> Ops;
4098       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4099         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4100                                FTy->getParamType(i)));
4101         if (!Ops.back())
4102           return error("Invalid record");
4103       }
4104
4105       if (!FTy->isVarArg()) {
4106         if (Record.size() != OpNum)
4107           return error("Invalid record");
4108       } else {
4109         // Read type/value pairs for varargs params.
4110         while (OpNum != Record.size()) {
4111           Value *Op;
4112           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4113             return error("Invalid record");
4114           Ops.push_back(Op);
4115         }
4116       }
4117
4118       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
4119       InstructionList.push_back(I);
4120       cast<InvokeInst>(I)
4121           ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4122       cast<InvokeInst>(I)->setAttributes(PAL);
4123       break;
4124     }
4125     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4126       unsigned Idx = 0;
4127       Value *Val = nullptr;
4128       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4129         return error("Invalid record");
4130       I = ResumeInst::Create(Val);
4131       InstructionList.push_back(I);
4132       break;
4133     }
4134     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4135       I = new UnreachableInst(Context);
4136       InstructionList.push_back(I);
4137       break;
4138     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4139       if (Record.size() < 1 || ((Record.size()-1)&1))
4140         return error("Invalid record");
4141       Type *Ty = getTypeByID(Record[0]);
4142       if (!Ty)
4143         return error("Invalid record");
4144
4145       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4146       InstructionList.push_back(PN);
4147
4148       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4149         Value *V;
4150         // With the new function encoding, it is possible that operands have
4151         // negative IDs (for forward references).  Use a signed VBR
4152         // representation to keep the encoding small.
4153         if (UseRelativeIDs)
4154           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4155         else
4156           V = getValue(Record, 1+i, NextValueNo, Ty);
4157         BasicBlock *BB = getBasicBlock(Record[2+i]);
4158         if (!V || !BB)
4159           return error("Invalid record");
4160         PN->addIncoming(V, BB);
4161       }
4162       I = PN;
4163       break;
4164     }
4165
4166     case bitc::FUNC_CODE_INST_LANDINGPAD:
4167     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4168       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4169       unsigned Idx = 0;
4170       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4171         if (Record.size() < 3)
4172           return error("Invalid record");
4173       } else {
4174         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4175         if (Record.size() < 4)
4176           return error("Invalid record");
4177       }
4178       Type *Ty = getTypeByID(Record[Idx++]);
4179       if (!Ty)
4180         return error("Invalid record");
4181       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4182         Value *PersFn = nullptr;
4183         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4184           return error("Invalid record");
4185
4186         if (!F->hasPersonalityFn())
4187           F->setPersonalityFn(cast<Constant>(PersFn));
4188         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4189           return error("Personality function mismatch");
4190       }
4191
4192       bool IsCleanup = !!Record[Idx++];
4193       unsigned NumClauses = Record[Idx++];
4194       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4195       LP->setCleanup(IsCleanup);
4196       for (unsigned J = 0; J != NumClauses; ++J) {
4197         LandingPadInst::ClauseType CT =
4198           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4199         Value *Val;
4200
4201         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4202           delete LP;
4203           return error("Invalid record");
4204         }
4205
4206         assert((CT != LandingPadInst::Catch ||
4207                 !isa<ArrayType>(Val->getType())) &&
4208                "Catch clause has a invalid type!");
4209         assert((CT != LandingPadInst::Filter ||
4210                 isa<ArrayType>(Val->getType())) &&
4211                "Filter clause has invalid type!");
4212         LP->addClause(cast<Constant>(Val));
4213       }
4214
4215       I = LP;
4216       InstructionList.push_back(I);
4217       break;
4218     }
4219
4220     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4221       if (Record.size() != 4)
4222         return error("Invalid record");
4223       uint64_t AlignRecord = Record[3];
4224       const uint64_t InAllocaMask = uint64_t(1) << 5;
4225       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4226       // Reserve bit 7 for SwiftError flag.
4227       // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4228       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4229       bool InAlloca = AlignRecord & InAllocaMask;
4230       Type *Ty = getTypeByID(Record[0]);
4231       if ((AlignRecord & ExplicitTypeMask) == 0) {
4232         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4233         if (!PTy)
4234           return error("Old-style alloca with a non-pointer type");
4235         Ty = PTy->getElementType();
4236       }
4237       Type *OpTy = getTypeByID(Record[1]);
4238       Value *Size = getFnValueByID(Record[2], OpTy);
4239       unsigned Align;
4240       if (std::error_code EC =
4241               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4242         return EC;
4243       }
4244       if (!Ty || !Size)
4245         return error("Invalid record");
4246       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4247       AI->setUsedWithInAlloca(InAlloca);
4248       I = AI;
4249       InstructionList.push_back(I);
4250       break;
4251     }
4252     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4253       unsigned OpNum = 0;
4254       Value *Op;
4255       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4256           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4257         return error("Invalid record");
4258
4259       Type *Ty = nullptr;
4260       if (OpNum + 3 == Record.size())
4261         Ty = getTypeByID(Record[OpNum++]);
4262       if (std::error_code EC =
4263               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4264         return EC;
4265       if (!Ty)
4266         Ty = cast<PointerType>(Op->getType())->getElementType();
4267
4268       unsigned Align;
4269       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4270         return EC;
4271       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4272
4273       InstructionList.push_back(I);
4274       break;
4275     }
4276     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4277        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4278       unsigned OpNum = 0;
4279       Value *Op;
4280       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4281           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4282         return error("Invalid record");
4283
4284       Type *Ty = nullptr;
4285       if (OpNum + 5 == Record.size())
4286         Ty = getTypeByID(Record[OpNum++]);
4287       if (std::error_code EC =
4288               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4289         return EC;
4290       if (!Ty)
4291         Ty = cast<PointerType>(Op->getType())->getElementType();
4292
4293       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4294       if (Ordering == NotAtomic || Ordering == Release ||
4295           Ordering == AcquireRelease)
4296         return error("Invalid record");
4297       if (Ordering != NotAtomic && Record[OpNum] == 0)
4298         return error("Invalid record");
4299       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4300
4301       unsigned Align;
4302       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4303         return EC;
4304       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4305
4306       InstructionList.push_back(I);
4307       break;
4308     }
4309     case bitc::FUNC_CODE_INST_STORE:
4310     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4311       unsigned OpNum = 0;
4312       Value *Val, *Ptr;
4313       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4314           (BitCode == bitc::FUNC_CODE_INST_STORE
4315                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4316                : popValue(Record, OpNum, NextValueNo,
4317                           cast<PointerType>(Ptr->getType())->getElementType(),
4318                           Val)) ||
4319           OpNum + 2 != Record.size())
4320         return error("Invalid record");
4321
4322       if (std::error_code EC = typeCheckLoadStoreInst(
4323               DiagnosticHandler, Val->getType(), Ptr->getType()))
4324         return EC;
4325       unsigned Align;
4326       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4327         return EC;
4328       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4329       InstructionList.push_back(I);
4330       break;
4331     }
4332     case bitc::FUNC_CODE_INST_STOREATOMIC:
4333     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4334       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4335       unsigned OpNum = 0;
4336       Value *Val, *Ptr;
4337       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4338           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4339                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4340                : popValue(Record, OpNum, NextValueNo,
4341                           cast<PointerType>(Ptr->getType())->getElementType(),
4342                           Val)) ||
4343           OpNum + 4 != Record.size())
4344         return error("Invalid record");
4345
4346       if (std::error_code EC = typeCheckLoadStoreInst(
4347               DiagnosticHandler, Val->getType(), Ptr->getType()))
4348         return EC;
4349       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4350       if (Ordering == NotAtomic || Ordering == Acquire ||
4351           Ordering == AcquireRelease)
4352         return error("Invalid record");
4353       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4354       if (Ordering != NotAtomic && Record[OpNum] == 0)
4355         return error("Invalid record");
4356
4357       unsigned Align;
4358       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4359         return EC;
4360       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4361       InstructionList.push_back(I);
4362       break;
4363     }
4364     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4365     case bitc::FUNC_CODE_INST_CMPXCHG: {
4366       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4367       //          failureordering?, isweak?]
4368       unsigned OpNum = 0;
4369       Value *Ptr, *Cmp, *New;
4370       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4371           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4372                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4373                : popValue(Record, OpNum, NextValueNo,
4374                           cast<PointerType>(Ptr->getType())->getElementType(),
4375                           Cmp)) ||
4376           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4377           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4378         return error("Invalid record");
4379       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4380       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4381         return error("Invalid record");
4382       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4383
4384       if (std::error_code EC = typeCheckLoadStoreInst(
4385               DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4386         return EC;
4387       AtomicOrdering FailureOrdering;
4388       if (Record.size() < 7)
4389         FailureOrdering =
4390             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4391       else
4392         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4393
4394       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4395                                 SynchScope);
4396       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4397
4398       if (Record.size() < 8) {
4399         // Before weak cmpxchgs existed, the instruction simply returned the
4400         // value loaded from memory, so bitcode files from that era will be
4401         // expecting the first component of a modern cmpxchg.
4402         CurBB->getInstList().push_back(I);
4403         I = ExtractValueInst::Create(I, 0);
4404       } else {
4405         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4406       }
4407
4408       InstructionList.push_back(I);
4409       break;
4410     }
4411     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4412       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4413       unsigned OpNum = 0;
4414       Value *Ptr, *Val;
4415       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4416           popValue(Record, OpNum, NextValueNo,
4417                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4418           OpNum+4 != Record.size())
4419         return error("Invalid record");
4420       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4421       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4422           Operation > AtomicRMWInst::LAST_BINOP)
4423         return error("Invalid record");
4424       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4425       if (Ordering == NotAtomic || Ordering == Unordered)
4426         return error("Invalid record");
4427       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4428       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4429       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4430       InstructionList.push_back(I);
4431       break;
4432     }
4433     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4434       if (2 != Record.size())
4435         return error("Invalid record");
4436       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4437       if (Ordering == NotAtomic || Ordering == Unordered ||
4438           Ordering == Monotonic)
4439         return error("Invalid record");
4440       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4441       I = new FenceInst(Context, Ordering, SynchScope);
4442       InstructionList.push_back(I);
4443       break;
4444     }
4445     case bitc::FUNC_CODE_INST_CALL: {
4446       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4447       if (Record.size() < 3)
4448         return error("Invalid record");
4449
4450       unsigned OpNum = 0;
4451       AttributeSet PAL = getAttributes(Record[OpNum++]);
4452       unsigned CCInfo = Record[OpNum++];
4453
4454       FunctionType *FTy = nullptr;
4455       if (CCInfo >> 15 & 1 &&
4456           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4457         return error("Explicit call type is not a function type");
4458
4459       Value *Callee;
4460       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4461         return error("Invalid record");
4462
4463       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4464       if (!OpTy)
4465         return error("Callee is not a pointer type");
4466       if (!FTy) {
4467         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4468         if (!FTy)
4469           return error("Callee is not of pointer to function type");
4470       } else if (OpTy->getElementType() != FTy)
4471         return error("Explicit call type does not match pointee type of "
4472                      "callee operand");
4473       if (Record.size() < FTy->getNumParams() + OpNum)
4474         return error("Insufficient operands to call");
4475
4476       SmallVector<Value*, 16> Args;
4477       // Read the fixed params.
4478       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4479         if (FTy->getParamType(i)->isLabelTy())
4480           Args.push_back(getBasicBlock(Record[OpNum]));
4481         else
4482           Args.push_back(getValue(Record, OpNum, NextValueNo,
4483                                   FTy->getParamType(i)));
4484         if (!Args.back())
4485           return error("Invalid record");
4486       }
4487
4488       // Read type/value pairs for varargs params.
4489       if (!FTy->isVarArg()) {
4490         if (OpNum != Record.size())
4491           return error("Invalid record");
4492       } else {
4493         while (OpNum != Record.size()) {
4494           Value *Op;
4495           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4496             return error("Invalid record");
4497           Args.push_back(Op);
4498         }
4499       }
4500
4501       I = CallInst::Create(FTy, Callee, Args);
4502       InstructionList.push_back(I);
4503       cast<CallInst>(I)->setCallingConv(
4504           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4505       CallInst::TailCallKind TCK = CallInst::TCK_None;
4506       if (CCInfo & 1)
4507         TCK = CallInst::TCK_Tail;
4508       if (CCInfo & (1 << 14))
4509         TCK = CallInst::TCK_MustTail;
4510       cast<CallInst>(I)->setTailCallKind(TCK);
4511       cast<CallInst>(I)->setAttributes(PAL);
4512       break;
4513     }
4514     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4515       if (Record.size() < 3)
4516         return error("Invalid record");
4517       Type *OpTy = getTypeByID(Record[0]);
4518       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4519       Type *ResTy = getTypeByID(Record[2]);
4520       if (!OpTy || !Op || !ResTy)
4521         return error("Invalid record");
4522       I = new VAArgInst(Op, ResTy);
4523       InstructionList.push_back(I);
4524       break;
4525     }
4526     }
4527
4528     // Add instruction to end of current BB.  If there is no current BB, reject
4529     // this file.
4530     if (!CurBB) {
4531       delete I;
4532       return error("Invalid instruction with no BB");
4533     }
4534     CurBB->getInstList().push_back(I);
4535
4536     // If this was a terminator instruction, move to the next block.
4537     if (isa<TerminatorInst>(I)) {
4538       ++CurBBNo;
4539       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4540     }
4541
4542     // Non-void values get registered in the value table for future use.
4543     if (I && !I->getType()->isVoidTy())
4544       ValueList.assignValue(I, NextValueNo++);
4545   }
4546
4547 OutOfRecordLoop:
4548
4549   // Check the function list for unresolved values.
4550   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4551     if (!A->getParent()) {
4552       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4553       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4554         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4555           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4556           delete A;
4557         }
4558       }
4559       return error("Never resolved value found in function");
4560     }
4561   }
4562
4563   // FIXME: Check for unresolved forward-declared metadata references
4564   // and clean up leaks.
4565
4566   // Trim the value list down to the size it was before we parsed this function.
4567   ValueList.shrinkTo(ModuleValueListSize);
4568   MDValueList.shrinkTo(ModuleMDValueListSize);
4569   std::vector<BasicBlock*>().swap(FunctionBBs);
4570   return std::error_code();
4571 }
4572
4573 /// Find the function body in the bitcode stream
4574 std::error_code BitcodeReader::findFunctionInStream(
4575     Function *F,
4576     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4577   while (DeferredFunctionInfoIterator->second == 0) {
4578     if (Stream.AtEndOfStream())
4579       return error("Could not find function in stream");
4580     // ParseModule will parse the next body in the stream and set its
4581     // position in the DeferredFunctionInfo map.
4582     if (std::error_code EC = parseModule(true))
4583       return EC;
4584   }
4585   return std::error_code();
4586 }
4587
4588 //===----------------------------------------------------------------------===//
4589 // GVMaterializer implementation
4590 //===----------------------------------------------------------------------===//
4591
4592 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4593
4594 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4595   if (std::error_code EC = materializeMetadata())
4596     return EC;
4597
4598   Function *F = dyn_cast<Function>(GV);
4599   // If it's not a function or is already material, ignore the request.
4600   if (!F || !F->isMaterializable())
4601     return std::error_code();
4602
4603   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4604   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4605   // If its position is recorded as 0, its body is somewhere in the stream
4606   // but we haven't seen it yet.
4607   if (DFII->second == 0)
4608     if (std::error_code EC = findFunctionInStream(F, DFII))
4609       return EC;
4610
4611   // Move the bit stream to the saved position of the deferred function body.
4612   Stream.JumpToBit(DFII->second);
4613
4614   if (std::error_code EC = parseFunctionBody(F))
4615     return EC;
4616   F->setIsMaterializable(false);
4617
4618   if (StripDebugInfo)
4619     stripDebugInfo(*F);
4620
4621   // Upgrade any old intrinsic calls in the function.
4622   for (auto &I : UpgradedIntrinsics) {
4623     for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4624       User *U = *UI;
4625       ++UI;
4626       if (CallInst *CI = dyn_cast<CallInst>(U))
4627         UpgradeIntrinsicCall(CI, I.second);
4628     }
4629   }
4630
4631   // Bring in any functions that this function forward-referenced via
4632   // blockaddresses.
4633   return materializeForwardReferencedFunctions();
4634 }
4635
4636 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4637   const Function *F = dyn_cast<Function>(GV);
4638   if (!F || F->isDeclaration())
4639     return false;
4640
4641   // Dematerializing F would leave dangling references that wouldn't be
4642   // reconnected on re-materialization.
4643   if (BlockAddressesTaken.count(F))
4644     return false;
4645
4646   return DeferredFunctionInfo.count(const_cast<Function*>(F));
4647 }
4648
4649 void BitcodeReader::dematerialize(GlobalValue *GV) {
4650   Function *F = dyn_cast<Function>(GV);
4651   // If this function isn't dematerializable, this is a noop.
4652   if (!F || !isDematerializable(F))
4653     return;
4654
4655   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4656
4657   // Just forget the function body, we can remat it later.
4658   F->dropAllReferences();
4659   F->setIsMaterializable(true);
4660 }
4661
4662 std::error_code BitcodeReader::materializeModule(Module *M) {
4663   assert(M == TheModule &&
4664          "Can only Materialize the Module this BitcodeReader is attached to.");
4665
4666   if (std::error_code EC = materializeMetadata())
4667     return EC;
4668
4669   // Promise to materialize all forward references.
4670   WillMaterializeAllForwardRefs = true;
4671
4672   // Iterate over the module, deserializing any functions that are still on
4673   // disk.
4674   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4675        F != E; ++F) {
4676     if (std::error_code EC = materialize(F))
4677       return EC;
4678   }
4679   // At this point, if there are any function bodies, the current bit is
4680   // pointing to the END_BLOCK record after them. Now make sure the rest
4681   // of the bits in the module have been read.
4682   if (NextUnreadBit)
4683     parseModule(true);
4684
4685   // Check that all block address forward references got resolved (as we
4686   // promised above).
4687   if (!BasicBlockFwdRefs.empty())
4688     return error("Never resolved function from blockaddress");
4689
4690   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4691   // delete the old functions to clean up. We can't do this unless the entire
4692   // module is materialized because there could always be another function body
4693   // with calls to the old function.
4694   for (auto &I : UpgradedIntrinsics) {
4695     for (auto *U : I.first->users()) {
4696       if (CallInst *CI = dyn_cast<CallInst>(U))
4697         UpgradeIntrinsicCall(CI, I.second);
4698     }
4699     if (!I.first->use_empty())
4700       I.first->replaceAllUsesWith(I.second);
4701     I.first->eraseFromParent();
4702   }
4703   UpgradedIntrinsics.clear();
4704
4705   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4706     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4707
4708   UpgradeDebugInfo(*M);
4709   return std::error_code();
4710 }
4711
4712 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4713   return IdentifiedStructTypes;
4714 }
4715
4716 std::error_code
4717 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4718   if (Streamer)
4719     return initLazyStream(std::move(Streamer));
4720   return initStreamFromBuffer();
4721 }
4722
4723 std::error_code BitcodeReader::initStreamFromBuffer() {
4724   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4725   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4726
4727   if (Buffer->getBufferSize() & 3)
4728     return error("Invalid bitcode signature");
4729
4730   // If we have a wrapper header, parse it and ignore the non-bc file contents.
4731   // The magic number is 0x0B17C0DE stored in little endian.
4732   if (isBitcodeWrapper(BufPtr, BufEnd))
4733     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4734       return error("Invalid bitcode wrapper header");
4735
4736   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4737   Stream.init(&*StreamFile);
4738
4739   return std::error_code();
4740 }
4741
4742 std::error_code
4743 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4744   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4745   // see it.
4746   auto OwnedBytes =
4747       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4748   StreamingMemoryObject &Bytes = *OwnedBytes;
4749   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4750   Stream.init(&*StreamFile);
4751
4752   unsigned char buf[16];
4753   if (Bytes.readBytes(buf, 16, 0) != 16)
4754     return error("Invalid bitcode signature");
4755
4756   if (!isBitcode(buf, buf + 16))
4757     return error("Invalid bitcode signature");
4758
4759   if (isBitcodeWrapper(buf, buf + 4)) {
4760     const unsigned char *bitcodeStart = buf;
4761     const unsigned char *bitcodeEnd = buf + 16;
4762     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4763     Bytes.dropLeadingBytes(bitcodeStart - buf);
4764     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4765   }
4766   return std::error_code();
4767 }
4768
4769 namespace {
4770 class BitcodeErrorCategoryType : public std::error_category {
4771   const char *name() const LLVM_NOEXCEPT override {
4772     return "llvm.bitcode";
4773   }
4774   std::string message(int IE) const override {
4775     BitcodeError E = static_cast<BitcodeError>(IE);
4776     switch (E) {
4777     case BitcodeError::InvalidBitcodeSignature:
4778       return "Invalid bitcode signature";
4779     case BitcodeError::CorruptedBitcode:
4780       return "Corrupted bitcode";
4781     }
4782     llvm_unreachable("Unknown error type!");
4783   }
4784 };
4785 }
4786
4787 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4788
4789 const std::error_category &llvm::BitcodeErrorCategory() {
4790   return *ErrorCategory;
4791 }
4792
4793 //===----------------------------------------------------------------------===//
4794 // External interface
4795 //===----------------------------------------------------------------------===//
4796
4797 static ErrorOr<std::unique_ptr<Module>>
4798 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4799                      BitcodeReader *R, LLVMContext &Context,
4800                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4801   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4802   M->setMaterializer(R);
4803
4804   auto cleanupOnError = [&](std::error_code EC) {
4805     R->releaseBuffer(); // Never take ownership on error.
4806     return EC;
4807   };
4808
4809   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4810   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4811                                                ShouldLazyLoadMetadata))
4812     return cleanupOnError(EC);
4813
4814   if (MaterializeAll) {
4815     // Read in the entire module, and destroy the BitcodeReader.
4816     if (std::error_code EC = M->materializeAllPermanently())
4817       return cleanupOnError(EC);
4818   } else {
4819     // Resolve forward references from blockaddresses.
4820     if (std::error_code EC = R->materializeForwardReferencedFunctions())
4821       return cleanupOnError(EC);
4822   }
4823   return std::move(M);
4824 }
4825
4826 /// \brief Get a lazy one-at-time loading module from bitcode.
4827 ///
4828 /// This isn't always used in a lazy context.  In particular, it's also used by
4829 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
4830 /// in forward-referenced functions from block address references.
4831 ///
4832 /// \param[in] MaterializeAll Set to \c true if we should materialize
4833 /// everything.
4834 static ErrorOr<std::unique_ptr<Module>>
4835 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4836                          LLVMContext &Context, bool MaterializeAll,
4837                          DiagnosticHandlerFunction DiagnosticHandler,
4838                          bool ShouldLazyLoadMetadata = false) {
4839   BitcodeReader *R =
4840       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4841
4842   ErrorOr<std::unique_ptr<Module>> Ret =
4843       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4844                            MaterializeAll, ShouldLazyLoadMetadata);
4845   if (!Ret)
4846     return Ret;
4847
4848   Buffer.release(); // The BitcodeReader owns it now.
4849   return Ret;
4850 }
4851
4852 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4853     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4854     DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
4855   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4856                                   DiagnosticHandler, ShouldLazyLoadMetadata);
4857 }
4858
4859 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4860     StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4861     LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
4862   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4863   BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
4864
4865   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4866                               false);
4867 }
4868
4869 ErrorOr<std::unique_ptr<Module>>
4870 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4871                        DiagnosticHandlerFunction DiagnosticHandler) {
4872   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4873   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4874                                   DiagnosticHandler);
4875   // TODO: Restore the use-lists to the in-memory state when the bitcode was
4876   // written.  We must defer until the Module has been fully materialized.
4877 }
4878
4879 std::string
4880 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4881                              DiagnosticHandlerFunction DiagnosticHandler) {
4882   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4883   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4884                                             DiagnosticHandler);
4885   ErrorOr<std::string> Triple = R->parseTriple();
4886   if (Triple.getError())
4887     return "";
4888   return Triple.get();
4889 }