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