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