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