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