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