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