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