LLVM  mainline
BitcodeReader.cpp
Go to the documentation of this file.
00001 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/Bitcode/ReaderWriter.h"
00011 #include "llvm/ADT/STLExtras.h"
00012 #include "llvm/ADT/SmallString.h"
00013 #include "llvm/ADT/SmallVector.h"
00014 #include "llvm/ADT/Triple.h"
00015 #include "llvm/Bitcode/BitstreamReader.h"
00016 #include "llvm/Bitcode/LLVMBitCodes.h"
00017 #include "llvm/IR/AutoUpgrade.h"
00018 #include "llvm/IR/Constants.h"
00019 #include "llvm/IR/DebugInfo.h"
00020 #include "llvm/IR/DebugInfoMetadata.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/DiagnosticPrinter.h"
00023 #include "llvm/IR/GVMaterializer.h"
00024 #include "llvm/IR/InlineAsm.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/LLVMContext.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/OperandTraits.h"
00029 #include "llvm/IR/Operator.h"
00030 #include "llvm/IR/ValueHandle.h"
00031 #include "llvm/Support/DataStream.h"
00032 #include "llvm/Support/ManagedStatic.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/MemoryBuffer.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include <deque>
00037 using namespace llvm;
00038 
00039 namespace {
00040 enum {
00041   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
00042 };
00043 
00044 class BitcodeReaderValueList {
00045   std::vector<WeakVH> ValuePtrs;
00046 
00047   /// ResolveConstants - As we resolve forward-referenced constants, we add
00048   /// information about them to this vector.  This allows us to resolve them in
00049   /// bulk instead of resolving each reference at a time.  See the code in
00050   /// ResolveConstantForwardRefs for more information about this.
00051   ///
00052   /// The key of this vector is the placeholder constant, the value is the slot
00053   /// number that holds the resolved value.
00054   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
00055   ResolveConstantsTy ResolveConstants;
00056   LLVMContext &Context;
00057 public:
00058   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
00059   ~BitcodeReaderValueList() {
00060     assert(ResolveConstants.empty() && "Constants not resolved?");
00061   }
00062 
00063   // vector compatibility methods
00064   unsigned size() const { return ValuePtrs.size(); }
00065   void resize(unsigned N) { ValuePtrs.resize(N); }
00066   void push_back(Value *V) {
00067     ValuePtrs.push_back(V);
00068   }
00069 
00070   void clear() {
00071     assert(ResolveConstants.empty() && "Constants not resolved?");
00072     ValuePtrs.clear();
00073   }
00074 
00075   Value *operator[](unsigned i) const {
00076     assert(i < ValuePtrs.size());
00077     return ValuePtrs[i];
00078   }
00079 
00080   Value *back() const { return ValuePtrs.back(); }
00081     void pop_back() { ValuePtrs.pop_back(); }
00082   bool empty() const { return ValuePtrs.empty(); }
00083   void shrinkTo(unsigned N) {
00084     assert(N <= size() && "Invalid shrinkTo request!");
00085     ValuePtrs.resize(N);
00086   }
00087 
00088   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
00089   Value *getValueFwdRef(unsigned Idx, Type *Ty);
00090 
00091   void AssignValue(Value *V, unsigned Idx);
00092 
00093   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
00094   /// resolves any forward references.
00095   void ResolveConstantForwardRefs();
00096 };
00097 
00098 class BitcodeReaderMDValueList {
00099   unsigned NumFwdRefs;
00100   bool AnyFwdRefs;
00101   unsigned MinFwdRef;
00102   unsigned MaxFwdRef;
00103   std::vector<TrackingMDRef> MDValuePtrs;
00104 
00105   LLVMContext &Context;
00106 public:
00107   BitcodeReaderMDValueList(LLVMContext &C)
00108       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
00109 
00110   // vector compatibility methods
00111   unsigned size() const       { return MDValuePtrs.size(); }
00112   void resize(unsigned N)     { MDValuePtrs.resize(N); }
00113   void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
00114   void clear()                { MDValuePtrs.clear();  }
00115   Metadata *back() const      { return MDValuePtrs.back(); }
00116   void pop_back()             { MDValuePtrs.pop_back(); }
00117   bool empty() const          { return MDValuePtrs.empty(); }
00118 
00119   Metadata *operator[](unsigned i) const {
00120     assert(i < MDValuePtrs.size());
00121     return MDValuePtrs[i];
00122   }
00123 
00124   void shrinkTo(unsigned N) {
00125     assert(N <= size() && "Invalid shrinkTo request!");
00126     MDValuePtrs.resize(N);
00127   }
00128 
00129   Metadata *getValueFwdRef(unsigned Idx);
00130   void AssignValue(Metadata *MD, unsigned Idx);
00131   void tryToResolveCycles();
00132 };
00133 
00134 class BitcodeReader : public GVMaterializer {
00135   LLVMContext &Context;
00136   DiagnosticHandlerFunction DiagnosticHandler;
00137   Module *TheModule;
00138   std::unique_ptr<MemoryBuffer> Buffer;
00139   std::unique_ptr<BitstreamReader> StreamFile;
00140   BitstreamCursor Stream;
00141   DataStreamer *LazyStreamer;
00142   uint64_t NextUnreadBit;
00143   bool SeenValueSymbolTable;
00144 
00145   std::vector<Type*> TypeList;
00146   BitcodeReaderValueList ValueList;
00147   BitcodeReaderMDValueList MDValueList;
00148   std::vector<Comdat *> ComdatList;
00149   SmallVector<Instruction *, 64> InstructionList;
00150 
00151   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
00152   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
00153   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
00154   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
00155 
00156   SmallVector<Instruction*, 64> InstsWithTBAATag;
00157 
00158   /// MAttributes - The set of attributes by index.  Index zero in the
00159   /// file is for null, and is thus not represented here.  As such all indices
00160   /// are off by one.
00161   std::vector<AttributeSet> MAttributes;
00162 
00163   /// \brief The set of attribute groups.
00164   std::map<unsigned, AttributeSet> MAttributeGroups;
00165 
00166   /// FunctionBBs - While parsing a function body, this is a list of the basic
00167   /// blocks for the function.
00168   std::vector<BasicBlock*> FunctionBBs;
00169 
00170   // When reading the module header, this list is populated with functions that
00171   // have bodies later in the file.
00172   std::vector<Function*> FunctionsWithBodies;
00173 
00174   // When intrinsic functions are encountered which require upgrading they are
00175   // stored here with their replacement function.
00176   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
00177   UpgradedIntrinsicMap UpgradedIntrinsics;
00178 
00179   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
00180   DenseMap<unsigned, unsigned> MDKindMap;
00181 
00182   // Several operations happen after the module header has been read, but
00183   // before function bodies are processed. This keeps track of whether
00184   // we've done this yet.
00185   bool SeenFirstFunctionBody;
00186 
00187   /// DeferredFunctionInfo - When function bodies are initially scanned, this
00188   /// map contains info about where to find deferred function body in the
00189   /// stream.
00190   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
00191 
00192   /// When Metadata block is initially scanned when parsing the module, we may
00193   /// choose to defer parsing of the metadata. This vector contains info about
00194   /// which Metadata blocks are deferred.
00195   std::vector<uint64_t> DeferredMetadataInfo;
00196 
00197   /// These are basic blocks forward-referenced by block addresses.  They are
00198   /// inserted lazily into functions when they're loaded.  The basic block ID is
00199   /// its index into the vector.
00200   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
00201   std::deque<Function *> BasicBlockFwdRefQueue;
00202 
00203   /// UseRelativeIDs - Indicates that we are using a new encoding for
00204   /// instruction operands where most operands in the current
00205   /// FUNCTION_BLOCK are encoded relative to the instruction number,
00206   /// for a more compact encoding.  Some instruction operands are not
00207   /// relative to the instruction ID: basic block numbers, and types.
00208   /// Once the old style function blocks have been phased out, we would
00209   /// not need this flag.
00210   bool UseRelativeIDs;
00211 
00212   /// True if all functions will be materialized, negating the need to process
00213   /// (e.g.) blockaddress forward references.
00214   bool WillMaterializeAllForwardRefs;
00215 
00216   /// Functions that have block addresses taken.  This is usually empty.
00217   SmallPtrSet<const Function *, 4> BlockAddressesTaken;
00218 
00219   /// True if any Metadata block has been materialized.
00220   bool IsMetadataMaterialized;
00221 
00222   bool StripDebugInfo = false;
00223 
00224 public:
00225   std::error_code Error(BitcodeError E, const Twine &Message);
00226   std::error_code Error(BitcodeError E);
00227   std::error_code Error(const Twine &Message);
00228 
00229   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
00230                          DiagnosticHandlerFunction DiagnosticHandler);
00231   explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
00232                          DiagnosticHandlerFunction DiagnosticHandler);
00233   ~BitcodeReader() { FreeState(); }
00234 
00235   std::error_code materializeForwardReferencedFunctions();
00236 
00237   void FreeState();
00238 
00239   void releaseBuffer();
00240 
00241   bool isDematerializable(const GlobalValue *GV) const override;
00242   std::error_code materialize(GlobalValue *GV) override;
00243   std::error_code MaterializeModule(Module *M) override;
00244   std::vector<StructType *> getIdentifiedStructTypes() const override;
00245   void Dematerialize(GlobalValue *GV) override;
00246 
00247   /// @brief Main interface to parsing a bitcode buffer.
00248   /// @returns true if an error occurred.
00249   std::error_code ParseBitcodeInto(Module *M,
00250                                    bool ShouldLazyLoadMetadata = false);
00251 
00252   /// @brief Cheap mechanism to just extract module triple
00253   /// @returns true if an error occurred.
00254   ErrorOr<std::string> parseTriple();
00255 
00256   static uint64_t decodeSignRotatedValue(uint64_t V);
00257 
00258   /// Materialize any deferred Metadata block.
00259   std::error_code materializeMetadata() override;
00260 
00261   void setStripDebugInfo() override;
00262 
00263 private:
00264   std::vector<StructType *> IdentifiedStructTypes;
00265   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
00266   StructType *createIdentifiedStructType(LLVMContext &Context);
00267 
00268   Type *getTypeByID(unsigned ID);
00269   Value *getFnValueByID(unsigned ID, Type *Ty) {
00270     if (Ty && Ty->isMetadataTy())
00271       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
00272     return ValueList.getValueFwdRef(ID, Ty);
00273   }
00274   Metadata *getFnMetadataByID(unsigned ID) {
00275     return MDValueList.getValueFwdRef(ID);
00276   }
00277   BasicBlock *getBasicBlock(unsigned ID) const {
00278     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
00279     return FunctionBBs[ID];
00280   }
00281   AttributeSet getAttributes(unsigned i) const {
00282     if (i-1 < MAttributes.size())
00283       return MAttributes[i-1];
00284     return AttributeSet();
00285   }
00286 
00287   /// getValueTypePair - Read a value/type pair out of the specified record from
00288   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
00289   /// Return true on failure.
00290   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
00291                         unsigned InstNum, Value *&ResVal) {
00292     if (Slot == Record.size()) return true;
00293     unsigned ValNo = (unsigned)Record[Slot++];
00294     // Adjust the ValNo, if it was encoded relative to the InstNum.
00295     if (UseRelativeIDs)
00296       ValNo = InstNum - ValNo;
00297     if (ValNo < InstNum) {
00298       // If this is not a forward reference, just return the value we already
00299       // have.
00300       ResVal = getFnValueByID(ValNo, nullptr);
00301       return ResVal == nullptr;
00302     } else if (Slot == Record.size()) {
00303       return true;
00304     }
00305 
00306     unsigned TypeNo = (unsigned)Record[Slot++];
00307     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
00308     return ResVal == nullptr;
00309   }
00310 
00311   /// popValue - Read a value out of the specified record from slot 'Slot'.
00312   /// Increment Slot past the number of slots used by the value in the record.
00313   /// Return true if there is an error.
00314   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
00315                 unsigned InstNum, Type *Ty, Value *&ResVal) {
00316     if (getValue(Record, Slot, InstNum, Ty, ResVal))
00317       return true;
00318     // All values currently take a single record slot.
00319     ++Slot;
00320     return false;
00321   }
00322 
00323   /// getValue -- Like popValue, but does not increment the Slot number.
00324   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
00325                 unsigned InstNum, Type *Ty, Value *&ResVal) {
00326     ResVal = getValue(Record, Slot, InstNum, Ty);
00327     return ResVal == nullptr;
00328   }
00329 
00330   /// getValue -- Version of getValue that returns ResVal directly,
00331   /// or 0 if there is an error.
00332   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
00333                   unsigned InstNum, Type *Ty) {
00334     if (Slot == Record.size()) return nullptr;
00335     unsigned ValNo = (unsigned)Record[Slot];
00336     // Adjust the ValNo, if it was encoded relative to the InstNum.
00337     if (UseRelativeIDs)
00338       ValNo = InstNum - ValNo;
00339     return getFnValueByID(ValNo, Ty);
00340   }
00341 
00342   /// getValueSigned -- Like getValue, but decodes signed VBRs.
00343   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
00344                         unsigned InstNum, Type *Ty) {
00345     if (Slot == Record.size()) return nullptr;
00346     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
00347     // Adjust the ValNo, if it was encoded relative to the InstNum.
00348     if (UseRelativeIDs)
00349       ValNo = InstNum - ValNo;
00350     return getFnValueByID(ValNo, Ty);
00351   }
00352 
00353   /// Converts alignment exponent (i.e. power of two (or zero)) to the
00354   /// corresponding alignment to use. If alignment is too large, returns
00355   /// a corresponding error code.
00356   std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
00357   std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
00358   std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
00359   std::error_code ParseAttributeBlock();
00360   std::error_code ParseAttributeGroupBlock();
00361   std::error_code ParseTypeTable();
00362   std::error_code ParseTypeTableBody();
00363 
00364   std::error_code ParseValueSymbolTable();
00365   std::error_code ParseConstants();
00366   std::error_code RememberAndSkipFunctionBody();
00367   /// Save the positions of the Metadata blocks and skip parsing the blocks.
00368   std::error_code rememberAndSkipMetadata();
00369   std::error_code ParseFunctionBody(Function *F);
00370   std::error_code GlobalCleanup();
00371   std::error_code ResolveGlobalAndAliasInits();
00372   std::error_code ParseMetadata();
00373   std::error_code ParseMetadataAttachment();
00374   ErrorOr<std::string> parseModuleTriple();
00375   std::error_code ParseUseLists();
00376   std::error_code InitStream();
00377   std::error_code InitStreamFromBuffer();
00378   std::error_code InitLazyStream();
00379   std::error_code FindFunctionInStream(
00380       Function *F,
00381       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
00382 };
00383 } // namespace
00384 
00385 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
00386                                              DiagnosticSeverity Severity,
00387                                              const Twine &Msg)
00388     : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
00389 
00390 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
00391 
00392 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
00393                              std::error_code EC, const Twine &Message) {
00394   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
00395   DiagnosticHandler(DI);
00396   return EC;
00397 }
00398 
00399 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
00400                              std::error_code EC) {
00401   return Error(DiagnosticHandler, EC, EC.message());
00402 }
00403 
00404 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
00405   return ::Error(DiagnosticHandler, make_error_code(E), Message);
00406 }
00407 
00408 std::error_code BitcodeReader::Error(const Twine &Message) {
00409   return ::Error(DiagnosticHandler,
00410                  make_error_code(BitcodeError::CorruptedBitcode), Message);
00411 }
00412 
00413 std::error_code BitcodeReader::Error(BitcodeError E) {
00414   return ::Error(DiagnosticHandler, make_error_code(E));
00415 }
00416 
00417 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
00418                                                 LLVMContext &C) {
00419   if (F)
00420     return F;
00421   return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
00422 }
00423 
00424 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
00425                              DiagnosticHandlerFunction DiagnosticHandler)
00426     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
00427       TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
00428       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
00429       MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
00430       WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
00431 
00432 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
00433                              DiagnosticHandlerFunction DiagnosticHandler)
00434     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
00435       TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
00436       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
00437       MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
00438       WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
00439 
00440 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
00441   if (WillMaterializeAllForwardRefs)
00442     return std::error_code();
00443 
00444   // Prevent recursion.
00445   WillMaterializeAllForwardRefs = true;
00446 
00447   while (!BasicBlockFwdRefQueue.empty()) {
00448     Function *F = BasicBlockFwdRefQueue.front();
00449     BasicBlockFwdRefQueue.pop_front();
00450     assert(F && "Expected valid function");
00451     if (!BasicBlockFwdRefs.count(F))
00452       // Already materialized.
00453       continue;
00454 
00455     // Check for a function that isn't materializable to prevent an infinite
00456     // loop.  When parsing a blockaddress stored in a global variable, there
00457     // isn't a trivial way to check if a function will have a body without a
00458     // linear search through FunctionsWithBodies, so just check it here.
00459     if (!F->isMaterializable())
00460       return Error("Never resolved function from blockaddress");
00461 
00462     // Try to materialize F.
00463     if (std::error_code EC = materialize(F))
00464       return EC;
00465   }
00466   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
00467 
00468   // Reset state.
00469   WillMaterializeAllForwardRefs = false;
00470   return std::error_code();
00471 }
00472 
00473 void BitcodeReader::FreeState() {
00474   Buffer = nullptr;
00475   std::vector<Type*>().swap(TypeList);
00476   ValueList.clear();
00477   MDValueList.clear();
00478   std::vector<Comdat *>().swap(ComdatList);
00479 
00480   std::vector<AttributeSet>().swap(MAttributes);
00481   std::vector<BasicBlock*>().swap(FunctionBBs);
00482   std::vector<Function*>().swap(FunctionsWithBodies);
00483   DeferredFunctionInfo.clear();
00484   DeferredMetadataInfo.clear();
00485   MDKindMap.clear();
00486 
00487   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
00488   BasicBlockFwdRefQueue.clear();
00489 }
00490 
00491 //===----------------------------------------------------------------------===//
00492 //  Helper functions to implement forward reference resolution, etc.
00493 //===----------------------------------------------------------------------===//
00494 
00495 /// ConvertToString - Convert a string from a record into an std::string, return
00496 /// true on failure.
00497 template<typename StrTy>
00498 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
00499                             StrTy &Result) {
00500   if (Idx > Record.size())
00501     return true;
00502 
00503   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
00504     Result += (char)Record[i];
00505   return false;
00506 }
00507 
00508 static bool hasImplicitComdat(size_t Val) {
00509   switch (Val) {
00510   default:
00511     return false;
00512   case 1:  // Old WeakAnyLinkage
00513   case 4:  // Old LinkOnceAnyLinkage
00514   case 10: // Old WeakODRLinkage
00515   case 11: // Old LinkOnceODRLinkage
00516     return true;
00517   }
00518 }
00519 
00520 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
00521   switch (Val) {
00522   default: // Map unknown/new linkages to external
00523   case 0:
00524     return GlobalValue::ExternalLinkage;
00525   case 2:
00526     return GlobalValue::AppendingLinkage;
00527   case 3:
00528     return GlobalValue::InternalLinkage;
00529   case 5:
00530     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
00531   case 6:
00532     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
00533   case 7:
00534     return GlobalValue::ExternalWeakLinkage;
00535   case 8:
00536     return GlobalValue::CommonLinkage;
00537   case 9:
00538     return GlobalValue::PrivateLinkage;
00539   case 12:
00540     return GlobalValue::AvailableExternallyLinkage;
00541   case 13:
00542     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
00543   case 14:
00544     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
00545   case 15:
00546     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
00547   case 1: // Old value with implicit comdat.
00548   case 16:
00549     return GlobalValue::WeakAnyLinkage;
00550   case 10: // Old value with implicit comdat.
00551   case 17:
00552     return GlobalValue::WeakODRLinkage;
00553   case 4: // Old value with implicit comdat.
00554   case 18:
00555     return GlobalValue::LinkOnceAnyLinkage;
00556   case 11: // Old value with implicit comdat.
00557   case 19:
00558     return GlobalValue::LinkOnceODRLinkage;
00559   }
00560 }
00561 
00562 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
00563   switch (Val) {
00564   default: // Map unknown visibilities to default.
00565   case 0: return GlobalValue::DefaultVisibility;
00566   case 1: return GlobalValue::HiddenVisibility;
00567   case 2: return GlobalValue::ProtectedVisibility;
00568   }
00569 }
00570 
00571 static GlobalValue::DLLStorageClassTypes
00572 GetDecodedDLLStorageClass(unsigned Val) {
00573   switch (Val) {
00574   default: // Map unknown values to default.
00575   case 0: return GlobalValue::DefaultStorageClass;
00576   case 1: return GlobalValue::DLLImportStorageClass;
00577   case 2: return GlobalValue::DLLExportStorageClass;
00578   }
00579 }
00580 
00581 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
00582   switch (Val) {
00583     case 0: return GlobalVariable::NotThreadLocal;
00584     default: // Map unknown non-zero value to general dynamic.
00585     case 1: return GlobalVariable::GeneralDynamicTLSModel;
00586     case 2: return GlobalVariable::LocalDynamicTLSModel;
00587     case 3: return GlobalVariable::InitialExecTLSModel;
00588     case 4: return GlobalVariable::LocalExecTLSModel;
00589   }
00590 }
00591 
00592 static int GetDecodedCastOpcode(unsigned Val) {
00593   switch (Val) {
00594   default: return -1;
00595   case bitc::CAST_TRUNC   : return Instruction::Trunc;
00596   case bitc::CAST_ZEXT    : return Instruction::ZExt;
00597   case bitc::CAST_SEXT    : return Instruction::SExt;
00598   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
00599   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
00600   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
00601   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
00602   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
00603   case bitc::CAST_FPEXT   : return Instruction::FPExt;
00604   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
00605   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
00606   case bitc::CAST_BITCAST : return Instruction::BitCast;
00607   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
00608   }
00609 }
00610 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
00611   switch (Val) {
00612   default: return -1;
00613   case bitc::BINOP_ADD:
00614     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
00615   case bitc::BINOP_SUB:
00616     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
00617   case bitc::BINOP_MUL:
00618     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
00619   case bitc::BINOP_UDIV: return Instruction::UDiv;
00620   case bitc::BINOP_SDIV:
00621     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
00622   case bitc::BINOP_UREM: return Instruction::URem;
00623   case bitc::BINOP_SREM:
00624     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
00625   case bitc::BINOP_SHL:  return Instruction::Shl;
00626   case bitc::BINOP_LSHR: return Instruction::LShr;
00627   case bitc::BINOP_ASHR: return Instruction::AShr;
00628   case bitc::BINOP_AND:  return Instruction::And;
00629   case bitc::BINOP_OR:   return Instruction::Or;
00630   case bitc::BINOP_XOR:  return Instruction::Xor;
00631   }
00632 }
00633 
00634 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
00635   switch (Val) {
00636   default: return AtomicRMWInst::BAD_BINOP;
00637   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
00638   case bitc::RMW_ADD: return AtomicRMWInst::Add;
00639   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
00640   case bitc::RMW_AND: return AtomicRMWInst::And;
00641   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
00642   case bitc::RMW_OR: return AtomicRMWInst::Or;
00643   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
00644   case bitc::RMW_MAX: return AtomicRMWInst::Max;
00645   case bitc::RMW_MIN: return AtomicRMWInst::Min;
00646   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
00647   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
00648   }
00649 }
00650 
00651 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
00652   switch (Val) {
00653   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
00654   case bitc::ORDERING_UNORDERED: return Unordered;
00655   case bitc::ORDERING_MONOTONIC: return Monotonic;
00656   case bitc::ORDERING_ACQUIRE: return Acquire;
00657   case bitc::ORDERING_RELEASE: return Release;
00658   case bitc::ORDERING_ACQREL: return AcquireRelease;
00659   default: // Map unknown orderings to sequentially-consistent.
00660   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
00661   }
00662 }
00663 
00664 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
00665   switch (Val) {
00666   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
00667   default: // Map unknown scopes to cross-thread.
00668   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
00669   }
00670 }
00671 
00672 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
00673   switch (Val) {
00674   default: // Map unknown selection kinds to any.
00675   case bitc::COMDAT_SELECTION_KIND_ANY:
00676     return Comdat::Any;
00677   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
00678     return Comdat::ExactMatch;
00679   case bitc::COMDAT_SELECTION_KIND_LARGEST:
00680     return Comdat::Largest;
00681   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
00682     return Comdat::NoDuplicates;
00683   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
00684     return Comdat::SameSize;
00685   }
00686 }
00687 
00688 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
00689   switch (Val) {
00690   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
00691   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
00692   }
00693 }
00694 
00695 namespace llvm {
00696 namespace {
00697   /// @brief A class for maintaining the slot number definition
00698   /// as a placeholder for the actual definition for forward constants defs.
00699   class ConstantPlaceHolder : public ConstantExpr {
00700     void operator=(const ConstantPlaceHolder &) = delete;
00701   public:
00702     // allocate space for exactly one operand
00703     void *operator new(size_t s) {
00704       return User::operator new(s, 1);
00705     }
00706     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
00707       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
00708       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
00709     }
00710 
00711     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
00712     static bool classof(const Value *V) {
00713       return isa<ConstantExpr>(V) &&
00714              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
00715     }
00716 
00717 
00718     /// Provide fast operand accessors
00719     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00720   };
00721 }
00722 
00723 // FIXME: can we inherit this from ConstantExpr?
00724 template <>
00725 struct OperandTraits<ConstantPlaceHolder> :
00726   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
00727 };
00728 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
00729 }
00730 
00731 
00732 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
00733   if (Idx == size()) {
00734     push_back(V);
00735     return;
00736   }
00737 
00738   if (Idx >= size())
00739     resize(Idx+1);
00740 
00741   WeakVH &OldV = ValuePtrs[Idx];
00742   if (!OldV) {
00743     OldV = V;
00744     return;
00745   }
00746 
00747   // Handle constants and non-constants (e.g. instrs) differently for
00748   // efficiency.
00749   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
00750     ResolveConstants.push_back(std::make_pair(PHC, Idx));
00751     OldV = V;
00752   } else {
00753     // If there was a forward reference to this value, replace it.
00754     Value *PrevVal = OldV;
00755     OldV->replaceAllUsesWith(V);
00756     delete PrevVal;
00757   }
00758 }
00759 
00760 
00761 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
00762                                                     Type *Ty) {
00763   if (Idx >= size())
00764     resize(Idx + 1);
00765 
00766   if (Value *V = ValuePtrs[Idx]) {
00767     assert(Ty == V->getType() && "Type mismatch in constant table!");
00768     return cast<Constant>(V);
00769   }
00770 
00771   // Create and return a placeholder, which will later be RAUW'd.
00772   Constant *C = new ConstantPlaceHolder(Ty, Context);
00773   ValuePtrs[Idx] = C;
00774   return C;
00775 }
00776 
00777 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
00778   if (Idx >= size())
00779     resize(Idx + 1);
00780 
00781   if (Value *V = ValuePtrs[Idx]) {
00782     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
00783     return V;
00784   }
00785 
00786   // No type specified, must be invalid reference.
00787   if (!Ty) return nullptr;
00788 
00789   // Create and return a placeholder, which will later be RAUW'd.
00790   Value *V = new Argument(Ty);
00791   ValuePtrs[Idx] = V;
00792   return V;
00793 }
00794 
00795 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
00796 /// resolves any forward references.  The idea behind this is that we sometimes
00797 /// get constants (such as large arrays) which reference *many* forward ref
00798 /// constants.  Replacing each of these causes a lot of thrashing when
00799 /// building/reuniquing the constant.  Instead of doing this, we look at all the
00800 /// uses and rewrite all the place holders at once for any constant that uses
00801 /// a placeholder.
00802 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
00803   // Sort the values by-pointer so that they are efficient to look up with a
00804   // binary search.
00805   std::sort(ResolveConstants.begin(), ResolveConstants.end());
00806 
00807   SmallVector<Constant*, 64> NewOps;
00808 
00809   while (!ResolveConstants.empty()) {
00810     Value *RealVal = operator[](ResolveConstants.back().second);
00811     Constant *Placeholder = ResolveConstants.back().first;
00812     ResolveConstants.pop_back();
00813 
00814     // Loop over all users of the placeholder, updating them to reference the
00815     // new value.  If they reference more than one placeholder, update them all
00816     // at once.
00817     while (!Placeholder->use_empty()) {
00818       auto UI = Placeholder->user_begin();
00819       User *U = *UI;
00820 
00821       // If the using object isn't uniqued, just update the operands.  This
00822       // handles instructions and initializers for global variables.
00823       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
00824         UI.getUse().set(RealVal);
00825         continue;
00826       }
00827 
00828       // Otherwise, we have a constant that uses the placeholder.  Replace that
00829       // constant with a new constant that has *all* placeholder uses updated.
00830       Constant *UserC = cast<Constant>(U);
00831       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
00832            I != E; ++I) {
00833         Value *NewOp;
00834         if (!isa<ConstantPlaceHolder>(*I)) {
00835           // Not a placeholder reference.
00836           NewOp = *I;
00837         } else if (*I == Placeholder) {
00838           // Common case is that it just references this one placeholder.
00839           NewOp = RealVal;
00840         } else {
00841           // Otherwise, look up the placeholder in ResolveConstants.
00842           ResolveConstantsTy::iterator It =
00843             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
00844                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
00845                                                             0));
00846           assert(It != ResolveConstants.end() && It->first == *I);
00847           NewOp = operator[](It->second);
00848         }
00849 
00850         NewOps.push_back(cast<Constant>(NewOp));
00851       }
00852 
00853       // Make the new constant.
00854       Constant *NewC;
00855       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
00856         NewC = ConstantArray::get(UserCA->getType(), NewOps);
00857       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
00858         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
00859       } else if (isa<ConstantVector>(UserC)) {
00860         NewC = ConstantVector::get(NewOps);
00861       } else {
00862         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
00863         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
00864       }
00865 
00866       UserC->replaceAllUsesWith(NewC);
00867       UserC->destroyConstant();
00868       NewOps.clear();
00869     }
00870 
00871     // Update all ValueHandles, they should be the only users at this point.
00872     Placeholder->replaceAllUsesWith(RealVal);
00873     delete Placeholder;
00874   }
00875 }
00876 
00877 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
00878   if (Idx == size()) {
00879     push_back(MD);
00880     return;
00881   }
00882 
00883   if (Idx >= size())
00884     resize(Idx+1);
00885 
00886   TrackingMDRef &OldMD = MDValuePtrs[Idx];
00887   if (!OldMD) {
00888     OldMD.reset(MD);
00889     return;
00890   }
00891 
00892   // If there was a forward reference to this value, replace it.
00893   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
00894   PrevMD->replaceAllUsesWith(MD);
00895   --NumFwdRefs;
00896 }
00897 
00898 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
00899   if (Idx >= size())
00900     resize(Idx + 1);
00901 
00902   if (Metadata *MD = MDValuePtrs[Idx])
00903     return MD;
00904 
00905   // Track forward refs to be resolved later.
00906   if (AnyFwdRefs) {
00907     MinFwdRef = std::min(MinFwdRef, Idx);
00908     MaxFwdRef = std::max(MaxFwdRef, Idx);
00909   } else {
00910     AnyFwdRefs = true;
00911     MinFwdRef = MaxFwdRef = Idx;
00912   }
00913   ++NumFwdRefs;
00914 
00915   // Create and return a placeholder, which will later be RAUW'd.
00916   Metadata *MD = MDNode::getTemporary(Context, None).release();
00917   MDValuePtrs[Idx].reset(MD);
00918   return MD;
00919 }
00920 
00921 void BitcodeReaderMDValueList::tryToResolveCycles() {
00922   if (!AnyFwdRefs)
00923     // Nothing to do.
00924     return;
00925 
00926   if (NumFwdRefs)
00927     // Still forward references... can't resolve cycles.
00928     return;
00929 
00930   // Resolve any cycles.
00931   for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
00932     auto &MD = MDValuePtrs[I];
00933     auto *N = dyn_cast_or_null<MDNode>(MD);
00934     if (!N)
00935       continue;
00936 
00937     assert(!N->isTemporary() && "Unexpected forward reference");
00938     N->resolveCycles();
00939   }
00940 
00941   // Make sure we return early again until there's another forward ref.
00942   AnyFwdRefs = false;
00943 }
00944 
00945 Type *BitcodeReader::getTypeByID(unsigned ID) {
00946   // The type table size is always specified correctly.
00947   if (ID >= TypeList.size())
00948     return nullptr;
00949 
00950   if (Type *Ty = TypeList[ID])
00951     return Ty;
00952 
00953   // If we have a forward reference, the only possible case is when it is to a
00954   // named struct.  Just create a placeholder for now.
00955   return TypeList[ID] = createIdentifiedStructType(Context);
00956 }
00957 
00958 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
00959                                                       StringRef Name) {
00960   auto *Ret = StructType::create(Context, Name);
00961   IdentifiedStructTypes.push_back(Ret);
00962   return Ret;
00963 }
00964 
00965 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
00966   auto *Ret = StructType::create(Context);
00967   IdentifiedStructTypes.push_back(Ret);
00968   return Ret;
00969 }
00970 
00971 
00972 //===----------------------------------------------------------------------===//
00973 //  Functions for parsing blocks from the bitcode file
00974 //===----------------------------------------------------------------------===//
00975 
00976 
00977 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
00978 /// been decoded from the given integer. This function must stay in sync with
00979 /// 'encodeLLVMAttributesForBitcode'.
00980 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
00981                                            uint64_t EncodedAttrs) {
00982   // FIXME: Remove in 4.0.
00983 
00984   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
00985   // the bits above 31 down by 11 bits.
00986   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
00987   assert((!Alignment || isPowerOf2_32(Alignment)) &&
00988          "Alignment must be a power of two.");
00989 
00990   if (Alignment)
00991     B.addAlignmentAttr(Alignment);
00992   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
00993                 (EncodedAttrs & 0xffff));
00994 }
00995 
00996 std::error_code BitcodeReader::ParseAttributeBlock() {
00997   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
00998     return Error("Invalid record");
00999 
01000   if (!MAttributes.empty())
01001     return Error("Invalid multiple blocks");
01002 
01003   SmallVector<uint64_t, 64> Record;
01004 
01005   SmallVector<AttributeSet, 8> Attrs;
01006 
01007   // Read all the records.
01008   while (1) {
01009     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01010 
01011     switch (Entry.Kind) {
01012     case BitstreamEntry::SubBlock: // Handled for us already.
01013     case BitstreamEntry::Error:
01014       return Error("Malformed block");
01015     case BitstreamEntry::EndBlock:
01016       return std::error_code();
01017     case BitstreamEntry::Record:
01018       // The interesting case.
01019       break;
01020     }
01021 
01022     // Read a record.
01023     Record.clear();
01024     switch (Stream.readRecord(Entry.ID, Record)) {
01025     default:  // Default behavior: ignore.
01026       break;
01027     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
01028       // FIXME: Remove in 4.0.
01029       if (Record.size() & 1)
01030         return Error("Invalid record");
01031 
01032       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
01033         AttrBuilder B;
01034         decodeLLVMAttributesForBitcode(B, Record[i+1]);
01035         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
01036       }
01037 
01038       MAttributes.push_back(AttributeSet::get(Context, Attrs));
01039       Attrs.clear();
01040       break;
01041     }
01042     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
01043       for (unsigned i = 0, e = Record.size(); i != e; ++i)
01044         Attrs.push_back(MAttributeGroups[Record[i]]);
01045 
01046       MAttributes.push_back(AttributeSet::get(Context, Attrs));
01047       Attrs.clear();
01048       break;
01049     }
01050     }
01051   }
01052 }
01053 
01054 // Returns Attribute::None on unrecognized codes.
01055 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
01056   switch (Code) {
01057   default:
01058     return Attribute::None;
01059   case bitc::ATTR_KIND_ALIGNMENT:
01060     return Attribute::Alignment;
01061   case bitc::ATTR_KIND_ALWAYS_INLINE:
01062     return Attribute::AlwaysInline;
01063   case bitc::ATTR_KIND_BUILTIN:
01064     return Attribute::Builtin;
01065   case bitc::ATTR_KIND_BY_VAL:
01066     return Attribute::ByVal;
01067   case bitc::ATTR_KIND_IN_ALLOCA:
01068     return Attribute::InAlloca;
01069   case bitc::ATTR_KIND_COLD:
01070     return Attribute::Cold;
01071   case bitc::ATTR_KIND_INLINE_HINT:
01072     return Attribute::InlineHint;
01073   case bitc::ATTR_KIND_IN_REG:
01074     return Attribute::InReg;
01075   case bitc::ATTR_KIND_JUMP_TABLE:
01076     return Attribute::JumpTable;
01077   case bitc::ATTR_KIND_MIN_SIZE:
01078     return Attribute::MinSize;
01079   case bitc::ATTR_KIND_NAKED:
01080     return Attribute::Naked;
01081   case bitc::ATTR_KIND_NEST:
01082     return Attribute::Nest;
01083   case bitc::ATTR_KIND_NO_ALIAS:
01084     return Attribute::NoAlias;
01085   case bitc::ATTR_KIND_NO_BUILTIN:
01086     return Attribute::NoBuiltin;
01087   case bitc::ATTR_KIND_NO_CAPTURE:
01088     return Attribute::NoCapture;
01089   case bitc::ATTR_KIND_NO_DUPLICATE:
01090     return Attribute::NoDuplicate;
01091   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
01092     return Attribute::NoImplicitFloat;
01093   case bitc::ATTR_KIND_NO_INLINE:
01094     return Attribute::NoInline;
01095   case bitc::ATTR_KIND_NON_LAZY_BIND:
01096     return Attribute::NonLazyBind;
01097   case bitc::ATTR_KIND_NON_NULL:
01098     return Attribute::NonNull;
01099   case bitc::ATTR_KIND_DEREFERENCEABLE:
01100     return Attribute::Dereferenceable;
01101   case bitc::ATTR_KIND_NO_RED_ZONE:
01102     return Attribute::NoRedZone;
01103   case bitc::ATTR_KIND_NO_RETURN:
01104     return Attribute::NoReturn;
01105   case bitc::ATTR_KIND_NO_UNWIND:
01106     return Attribute::NoUnwind;
01107   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
01108     return Attribute::OptimizeForSize;
01109   case bitc::ATTR_KIND_OPTIMIZE_NONE:
01110     return Attribute::OptimizeNone;
01111   case bitc::ATTR_KIND_READ_NONE:
01112     return Attribute::ReadNone;
01113   case bitc::ATTR_KIND_READ_ONLY:
01114     return Attribute::ReadOnly;
01115   case bitc::ATTR_KIND_RETURNED:
01116     return Attribute::Returned;
01117   case bitc::ATTR_KIND_RETURNS_TWICE:
01118     return Attribute::ReturnsTwice;
01119   case bitc::ATTR_KIND_S_EXT:
01120     return Attribute::SExt;
01121   case bitc::ATTR_KIND_STACK_ALIGNMENT:
01122     return Attribute::StackAlignment;
01123   case bitc::ATTR_KIND_STACK_PROTECT:
01124     return Attribute::StackProtect;
01125   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
01126     return Attribute::StackProtectReq;
01127   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
01128     return Attribute::StackProtectStrong;
01129   case bitc::ATTR_KIND_STRUCT_RET:
01130     return Attribute::StructRet;
01131   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
01132     return Attribute::SanitizeAddress;
01133   case bitc::ATTR_KIND_SANITIZE_THREAD:
01134     return Attribute::SanitizeThread;
01135   case bitc::ATTR_KIND_SANITIZE_MEMORY:
01136     return Attribute::SanitizeMemory;
01137   case bitc::ATTR_KIND_UW_TABLE:
01138     return Attribute::UWTable;
01139   case bitc::ATTR_KIND_Z_EXT:
01140     return Attribute::ZExt;
01141   }
01142 }
01143 
01144 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
01145                                                    unsigned &Alignment) {
01146   // Note: Alignment in bitcode files is incremented by 1, so that zero
01147   // can be used for default alignment.
01148   if (Exponent > Value::MaxAlignmentExponent + 1)
01149     return Error("Invalid alignment value");
01150   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
01151   return std::error_code();
01152 }
01153 
01154 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
01155                                              Attribute::AttrKind *Kind) {
01156   *Kind = GetAttrFromCode(Code);
01157   if (*Kind == Attribute::None)
01158     return Error(BitcodeError::CorruptedBitcode,
01159                  "Unknown attribute kind (" + Twine(Code) + ")");
01160   return std::error_code();
01161 }
01162 
01163 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
01164   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
01165     return Error("Invalid record");
01166 
01167   if (!MAttributeGroups.empty())
01168     return Error("Invalid multiple blocks");
01169 
01170   SmallVector<uint64_t, 64> Record;
01171 
01172   // Read all the records.
01173   while (1) {
01174     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01175 
01176     switch (Entry.Kind) {
01177     case BitstreamEntry::SubBlock: // Handled for us already.
01178     case BitstreamEntry::Error:
01179       return Error("Malformed block");
01180     case BitstreamEntry::EndBlock:
01181       return std::error_code();
01182     case BitstreamEntry::Record:
01183       // The interesting case.
01184       break;
01185     }
01186 
01187     // Read a record.
01188     Record.clear();
01189     switch (Stream.readRecord(Entry.ID, Record)) {
01190     default:  // Default behavior: ignore.
01191       break;
01192     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
01193       if (Record.size() < 3)
01194         return Error("Invalid record");
01195 
01196       uint64_t GrpID = Record[0];
01197       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
01198 
01199       AttrBuilder B;
01200       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
01201         if (Record[i] == 0) {        // Enum attribute
01202           Attribute::AttrKind Kind;
01203           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
01204             return EC;
01205 
01206           B.addAttribute(Kind);
01207         } else if (Record[i] == 1) { // Integer attribute
01208           Attribute::AttrKind Kind;
01209           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
01210             return EC;
01211           if (Kind == Attribute::Alignment)
01212             B.addAlignmentAttr(Record[++i]);
01213           else if (Kind == Attribute::StackAlignment)
01214             B.addStackAlignmentAttr(Record[++i]);
01215           else if (Kind == Attribute::Dereferenceable)
01216             B.addDereferenceableAttr(Record[++i]);
01217         } else {                     // String attribute
01218           assert((Record[i] == 3 || Record[i] == 4) &&
01219                  "Invalid attribute group entry");
01220           bool HasValue = (Record[i++] == 4);
01221           SmallString<64> KindStr;
01222           SmallString<64> ValStr;
01223 
01224           while (Record[i] != 0 && i != e)
01225             KindStr += Record[i++];
01226           assert(Record[i] == 0 && "Kind string not null terminated");
01227 
01228           if (HasValue) {
01229             // Has a value associated with it.
01230             ++i; // Skip the '0' that terminates the "kind" string.
01231             while (Record[i] != 0 && i != e)
01232               ValStr += Record[i++];
01233             assert(Record[i] == 0 && "Value string not null terminated");
01234           }
01235 
01236           B.addAttribute(KindStr.str(), ValStr.str());
01237         }
01238       }
01239 
01240       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
01241       break;
01242     }
01243     }
01244   }
01245 }
01246 
01247 std::error_code BitcodeReader::ParseTypeTable() {
01248   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
01249     return Error("Invalid record");
01250 
01251   return ParseTypeTableBody();
01252 }
01253 
01254 std::error_code BitcodeReader::ParseTypeTableBody() {
01255   if (!TypeList.empty())
01256     return Error("Invalid multiple blocks");
01257 
01258   SmallVector<uint64_t, 64> Record;
01259   unsigned NumRecords = 0;
01260 
01261   SmallString<64> TypeName;
01262 
01263   // Read all the records for this type table.
01264   while (1) {
01265     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01266 
01267     switch (Entry.Kind) {
01268     case BitstreamEntry::SubBlock: // Handled for us already.
01269     case BitstreamEntry::Error:
01270       return Error("Malformed block");
01271     case BitstreamEntry::EndBlock:
01272       if (NumRecords != TypeList.size())
01273         return Error("Malformed block");
01274       return std::error_code();
01275     case BitstreamEntry::Record:
01276       // The interesting case.
01277       break;
01278     }
01279 
01280     // Read a record.
01281     Record.clear();
01282     Type *ResultTy = nullptr;
01283     switch (Stream.readRecord(Entry.ID, Record)) {
01284     default:
01285       return Error("Invalid value");
01286     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
01287       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
01288       // type list.  This allows us to reserve space.
01289       if (Record.size() < 1)
01290         return Error("Invalid record");
01291       TypeList.resize(Record[0]);
01292       continue;
01293     case bitc::TYPE_CODE_VOID:      // VOID
01294       ResultTy = Type::getVoidTy(Context);
01295       break;
01296     case bitc::TYPE_CODE_HALF:     // HALF
01297       ResultTy = Type::getHalfTy(Context);
01298       break;
01299     case bitc::TYPE_CODE_FLOAT:     // FLOAT
01300       ResultTy = Type::getFloatTy(Context);
01301       break;
01302     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
01303       ResultTy = Type::getDoubleTy(Context);
01304       break;
01305     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
01306       ResultTy = Type::getX86_FP80Ty(Context);
01307       break;
01308     case bitc::TYPE_CODE_FP128:     // FP128
01309       ResultTy = Type::getFP128Ty(Context);
01310       break;
01311     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
01312       ResultTy = Type::getPPC_FP128Ty(Context);
01313       break;
01314     case bitc::TYPE_CODE_LABEL:     // LABEL
01315       ResultTy = Type::getLabelTy(Context);
01316       break;
01317     case bitc::TYPE_CODE_METADATA:  // METADATA
01318       ResultTy = Type::getMetadataTy(Context);
01319       break;
01320     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
01321       ResultTy = Type::getX86_MMXTy(Context);
01322       break;
01323     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
01324       if (Record.size() < 1)
01325         return Error("Invalid record");
01326 
01327       uint64_t NumBits = Record[0];
01328       if (NumBits < IntegerType::MIN_INT_BITS ||
01329           NumBits > IntegerType::MAX_INT_BITS)
01330         return Error("Bitwidth for integer type out of range");
01331       ResultTy = IntegerType::get(Context, NumBits);
01332       break;
01333     }
01334     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
01335                                     //          [pointee type, address space]
01336       if (Record.size() < 1)
01337         return Error("Invalid record");
01338       unsigned AddressSpace = 0;
01339       if (Record.size() == 2)
01340         AddressSpace = Record[1];
01341       ResultTy = getTypeByID(Record[0]);
01342       if (!ResultTy)
01343         return Error("Invalid type");
01344       ResultTy = PointerType::get(ResultTy, AddressSpace);
01345       break;
01346     }
01347     case bitc::TYPE_CODE_FUNCTION_OLD: {
01348       // FIXME: attrid is dead, remove it in LLVM 4.0
01349       // FUNCTION: [vararg, attrid, retty, paramty x N]
01350       if (Record.size() < 3)
01351         return Error("Invalid record");
01352       SmallVector<Type*, 8> ArgTys;
01353       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
01354         if (Type *T = getTypeByID(Record[i]))
01355           ArgTys.push_back(T);
01356         else
01357           break;
01358       }
01359 
01360       ResultTy = getTypeByID(Record[2]);
01361       if (!ResultTy || ArgTys.size() < Record.size()-3)
01362         return Error("Invalid type");
01363 
01364       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
01365       break;
01366     }
01367     case bitc::TYPE_CODE_FUNCTION: {
01368       // FUNCTION: [vararg, retty, paramty x N]
01369       if (Record.size() < 2)
01370         return Error("Invalid record");
01371       SmallVector<Type*, 8> ArgTys;
01372       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
01373         if (Type *T = getTypeByID(Record[i]))
01374           ArgTys.push_back(T);
01375         else
01376           break;
01377       }
01378 
01379       ResultTy = getTypeByID(Record[1]);
01380       if (!ResultTy || ArgTys.size() < Record.size()-2)
01381         return Error("Invalid type");
01382 
01383       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
01384       break;
01385     }
01386     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
01387       if (Record.size() < 1)
01388         return Error("Invalid record");
01389       SmallVector<Type*, 8> EltTys;
01390       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
01391         if (Type *T = getTypeByID(Record[i]))
01392           EltTys.push_back(T);
01393         else
01394           break;
01395       }
01396       if (EltTys.size() != Record.size()-1)
01397         return Error("Invalid type");
01398       ResultTy = StructType::get(Context, EltTys, Record[0]);
01399       break;
01400     }
01401     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
01402       if (ConvertToString(Record, 0, TypeName))
01403         return Error("Invalid record");
01404       continue;
01405 
01406     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
01407       if (Record.size() < 1)
01408         return Error("Invalid record");
01409 
01410       if (NumRecords >= TypeList.size())
01411         return Error("Invalid TYPE table");
01412 
01413       // Check to see if this was forward referenced, if so fill in the temp.
01414       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
01415       if (Res) {
01416         Res->setName(TypeName);
01417         TypeList[NumRecords] = nullptr;
01418       } else  // Otherwise, create a new struct.
01419         Res = createIdentifiedStructType(Context, TypeName);
01420       TypeName.clear();
01421 
01422       SmallVector<Type*, 8> EltTys;
01423       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
01424         if (Type *T = getTypeByID(Record[i]))
01425           EltTys.push_back(T);
01426         else
01427           break;
01428       }
01429       if (EltTys.size() != Record.size()-1)
01430         return Error("Invalid record");
01431       Res->setBody(EltTys, Record[0]);
01432       ResultTy = Res;
01433       break;
01434     }
01435     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
01436       if (Record.size() != 1)
01437         return Error("Invalid record");
01438 
01439       if (NumRecords >= TypeList.size())
01440         return Error("Invalid TYPE table");
01441 
01442       // Check to see if this was forward referenced, if so fill in the temp.
01443       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
01444       if (Res) {
01445         Res->setName(TypeName);
01446         TypeList[NumRecords] = nullptr;
01447       } else  // Otherwise, create a new struct with no body.
01448         Res = createIdentifiedStructType(Context, TypeName);
01449       TypeName.clear();
01450       ResultTy = Res;
01451       break;
01452     }
01453     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
01454       if (Record.size() < 2)
01455         return Error("Invalid record");
01456       if ((ResultTy = getTypeByID(Record[1])))
01457         ResultTy = ArrayType::get(ResultTy, Record[0]);
01458       else
01459         return Error("Invalid type");
01460       break;
01461     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
01462       if (Record.size() < 2)
01463         return Error("Invalid record");
01464       if ((ResultTy = getTypeByID(Record[1])))
01465         ResultTy = VectorType::get(ResultTy, Record[0]);
01466       else
01467         return Error("Invalid type");
01468       break;
01469     }
01470 
01471     if (NumRecords >= TypeList.size())
01472       return Error("Invalid TYPE table");
01473     if (TypeList[NumRecords])
01474       return Error(
01475           "Invalid TYPE table: Only named structs can be forward referenced");
01476     assert(ResultTy && "Didn't read a type?");
01477     TypeList[NumRecords++] = ResultTy;
01478   }
01479 }
01480 
01481 std::error_code BitcodeReader::ParseValueSymbolTable() {
01482   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
01483     return Error("Invalid record");
01484 
01485   SmallVector<uint64_t, 64> Record;
01486 
01487   Triple TT(TheModule->getTargetTriple());
01488 
01489   // Read all the records for this value table.
01490   SmallString<128> ValueName;
01491   while (1) {
01492     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01493 
01494     switch (Entry.Kind) {
01495     case BitstreamEntry::SubBlock: // Handled for us already.
01496     case BitstreamEntry::Error:
01497       return Error("Malformed block");
01498     case BitstreamEntry::EndBlock:
01499       return std::error_code();
01500     case BitstreamEntry::Record:
01501       // The interesting case.
01502       break;
01503     }
01504 
01505     // Read a record.
01506     Record.clear();
01507     switch (Stream.readRecord(Entry.ID, Record)) {
01508     default:  // Default behavior: unknown type.
01509       break;
01510     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
01511       if (ConvertToString(Record, 1, ValueName))
01512         return Error("Invalid record");
01513       unsigned ValueID = Record[0];
01514       if (ValueID >= ValueList.size() || !ValueList[ValueID])
01515         return Error("Invalid record");
01516       Value *V = ValueList[ValueID];
01517 
01518       V->setName(StringRef(ValueName.data(), ValueName.size()));
01519       if (auto *GO = dyn_cast<GlobalObject>(V)) {
01520         if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
01521           if (TT.isOSBinFormatMachO())
01522             GO->setComdat(nullptr);
01523           else
01524             GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
01525         }
01526       }
01527       ValueName.clear();
01528       break;
01529     }
01530     case bitc::VST_CODE_BBENTRY: {
01531       if (ConvertToString(Record, 1, ValueName))
01532         return Error("Invalid record");
01533       BasicBlock *BB = getBasicBlock(Record[0]);
01534       if (!BB)
01535         return Error("Invalid record");
01536 
01537       BB->setName(StringRef(ValueName.data(), ValueName.size()));
01538       ValueName.clear();
01539       break;
01540     }
01541     }
01542   }
01543 }
01544 
01545 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
01546 
01547 std::error_code BitcodeReader::ParseMetadata() {
01548   IsMetadataMaterialized = true;
01549   unsigned NextMDValueNo = MDValueList.size();
01550 
01551   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
01552     return Error("Invalid record");
01553 
01554   SmallVector<uint64_t, 64> Record;
01555 
01556   auto getMD =
01557       [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
01558   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
01559     if (ID)
01560       return getMD(ID - 1);
01561     return nullptr;
01562   };
01563   auto getMDString = [&](unsigned ID) -> MDString *{
01564     // This requires that the ID is not really a forward reference.  In
01565     // particular, the MDString must already have been resolved.
01566     return cast_or_null<MDString>(getMDOrNull(ID));
01567   };
01568 
01569 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
01570   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
01571 
01572   // Read all the records.
01573   while (1) {
01574     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01575 
01576     switch (Entry.Kind) {
01577     case BitstreamEntry::SubBlock: // Handled for us already.
01578     case BitstreamEntry::Error:
01579       return Error("Malformed block");
01580     case BitstreamEntry::EndBlock:
01581       MDValueList.tryToResolveCycles();
01582       return std::error_code();
01583     case BitstreamEntry::Record:
01584       // The interesting case.
01585       break;
01586     }
01587 
01588     // Read a record.
01589     Record.clear();
01590     unsigned Code = Stream.readRecord(Entry.ID, Record);
01591     bool IsDistinct = false;
01592     switch (Code) {
01593     default:  // Default behavior: ignore.
01594       break;
01595     case bitc::METADATA_NAME: {
01596       // Read name of the named metadata.
01597       SmallString<8> Name(Record.begin(), Record.end());
01598       Record.clear();
01599       Code = Stream.ReadCode();
01600 
01601       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
01602       unsigned NextBitCode = Stream.readRecord(Code, Record);
01603       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
01604 
01605       // Read named metadata elements.
01606       unsigned Size = Record.size();
01607       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
01608       for (unsigned i = 0; i != Size; ++i) {
01609         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
01610         if (!MD)
01611           return Error("Invalid record");
01612         NMD->addOperand(MD);
01613       }
01614       break;
01615     }
01616     case bitc::METADATA_OLD_FN_NODE: {
01617       // FIXME: Remove in 4.0.
01618       // This is a LocalAsMetadata record, the only type of function-local
01619       // metadata.
01620       if (Record.size() % 2 == 1)
01621         return Error("Invalid record");
01622 
01623       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
01624       // to be legal, but there's no upgrade path.
01625       auto dropRecord = [&] {
01626         MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
01627       };
01628       if (Record.size() != 2) {
01629         dropRecord();
01630         break;
01631       }
01632 
01633       Type *Ty = getTypeByID(Record[0]);
01634       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
01635         dropRecord();
01636         break;
01637       }
01638 
01639       MDValueList.AssignValue(
01640           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
01641           NextMDValueNo++);
01642       break;
01643     }
01644     case bitc::METADATA_OLD_NODE: {
01645       // FIXME: Remove in 4.0.
01646       if (Record.size() % 2 == 1)
01647         return Error("Invalid record");
01648 
01649       unsigned Size = Record.size();
01650       SmallVector<Metadata *, 8> Elts;
01651       for (unsigned i = 0; i != Size; i += 2) {
01652         Type *Ty = getTypeByID(Record[i]);
01653         if (!Ty)
01654           return Error("Invalid record");
01655         if (Ty->isMetadataTy())
01656           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
01657         else if (!Ty->isVoidTy()) {
01658           auto *MD =
01659               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
01660           assert(isa<ConstantAsMetadata>(MD) &&
01661                  "Expected non-function-local metadata");
01662           Elts.push_back(MD);
01663         } else
01664           Elts.push_back(nullptr);
01665       }
01666       MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
01667       break;
01668     }
01669     case bitc::METADATA_VALUE: {
01670       if (Record.size() != 2)
01671         return Error("Invalid record");
01672 
01673       Type *Ty = getTypeByID(Record[0]);
01674       if (Ty->isMetadataTy() || Ty->isVoidTy())
01675         return Error("Invalid record");
01676 
01677       MDValueList.AssignValue(
01678           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
01679           NextMDValueNo++);
01680       break;
01681     }
01682     case bitc::METADATA_DISTINCT_NODE:
01683       IsDistinct = true;
01684       // fallthrough...
01685     case bitc::METADATA_NODE: {
01686       SmallVector<Metadata *, 8> Elts;
01687       Elts.reserve(Record.size());
01688       for (unsigned ID : Record)
01689         Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
01690       MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
01691                                          : MDNode::get(Context, Elts),
01692                               NextMDValueNo++);
01693       break;
01694     }
01695     case bitc::METADATA_LOCATION: {
01696       if (Record.size() != 5)
01697         return Error("Invalid record");
01698 
01699       unsigned Line = Record[1];
01700       unsigned Column = Record[2];
01701       MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
01702       Metadata *InlinedAt =
01703           Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
01704       MDValueList.AssignValue(
01705           GET_OR_DISTINCT(MDLocation, Record[0],
01706                           (Context, Line, Column, Scope, InlinedAt)),
01707           NextMDValueNo++);
01708       break;
01709     }
01710     case bitc::METADATA_GENERIC_DEBUG: {
01711       if (Record.size() < 4)
01712         return Error("Invalid record");
01713 
01714       unsigned Tag = Record[1];
01715       unsigned Version = Record[2];
01716 
01717       if (Tag >= 1u << 16 || Version != 0)
01718         return Error("Invalid record");
01719 
01720       auto *Header = getMDString(Record[3]);
01721       SmallVector<Metadata *, 8> DwarfOps;
01722       for (unsigned I = 4, E = Record.size(); I != E; ++I)
01723         DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
01724                                      : nullptr);
01725       MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
01726                                               (Context, Tag, Header, DwarfOps)),
01727                               NextMDValueNo++);
01728       break;
01729     }
01730     case bitc::METADATA_SUBRANGE: {
01731       if (Record.size() != 3)
01732         return Error("Invalid record");
01733 
01734       MDValueList.AssignValue(
01735           GET_OR_DISTINCT(MDSubrange, Record[0],
01736                           (Context, Record[1], unrotateSign(Record[2]))),
01737           NextMDValueNo++);
01738       break;
01739     }
01740     case bitc::METADATA_ENUMERATOR: {
01741       if (Record.size() != 3)
01742         return Error("Invalid record");
01743 
01744       MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
01745                                               (Context, unrotateSign(Record[1]),
01746                                                getMDString(Record[2]))),
01747                               NextMDValueNo++);
01748       break;
01749     }
01750     case bitc::METADATA_BASIC_TYPE: {
01751       if (Record.size() != 6)
01752         return Error("Invalid record");
01753 
01754       MDValueList.AssignValue(
01755           GET_OR_DISTINCT(MDBasicType, Record[0],
01756                           (Context, Record[1], getMDString(Record[2]),
01757                            Record[3], Record[4], Record[5])),
01758           NextMDValueNo++);
01759       break;
01760     }
01761     case bitc::METADATA_DERIVED_TYPE: {
01762       if (Record.size() != 12)
01763         return Error("Invalid record");
01764 
01765       MDValueList.AssignValue(
01766           GET_OR_DISTINCT(MDDerivedType, Record[0],
01767                           (Context, Record[1], getMDString(Record[2]),
01768                            getMDOrNull(Record[3]), Record[4],
01769                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
01770                            Record[7], Record[8], Record[9], Record[10],
01771                            getMDOrNull(Record[11]))),
01772           NextMDValueNo++);
01773       break;
01774     }
01775     case bitc::METADATA_COMPOSITE_TYPE: {
01776       if (Record.size() != 16)
01777         return Error("Invalid record");
01778 
01779       MDValueList.AssignValue(
01780           GET_OR_DISTINCT(MDCompositeType, Record[0],
01781                           (Context, Record[1], getMDString(Record[2]),
01782                            getMDOrNull(Record[3]), Record[4],
01783                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
01784                            Record[7], Record[8], Record[9], Record[10],
01785                            getMDOrNull(Record[11]), Record[12],
01786                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
01787                            getMDString(Record[15]))),
01788           NextMDValueNo++);
01789       break;
01790     }
01791     case bitc::METADATA_SUBROUTINE_TYPE: {
01792       if (Record.size() != 3)
01793         return Error("Invalid record");
01794 
01795       MDValueList.AssignValue(
01796           GET_OR_DISTINCT(MDSubroutineType, Record[0],
01797                           (Context, Record[1], getMDOrNull(Record[2]))),
01798           NextMDValueNo++);
01799       break;
01800     }
01801     case bitc::METADATA_FILE: {
01802       if (Record.size() != 3)
01803         return Error("Invalid record");
01804 
01805       MDValueList.AssignValue(
01806           GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
01807                                               getMDString(Record[2]))),
01808           NextMDValueNo++);
01809       break;
01810     }
01811     case bitc::METADATA_COMPILE_UNIT: {
01812       if (Record.size() != 14)
01813         return Error("Invalid record");
01814 
01815       MDValueList.AssignValue(
01816           GET_OR_DISTINCT(MDCompileUnit, Record[0],
01817                           (Context, Record[1], getMDOrNull(Record[2]),
01818                            getMDString(Record[3]), Record[4],
01819                            getMDString(Record[5]), Record[6],
01820                            getMDString(Record[7]), Record[8],
01821                            getMDOrNull(Record[9]), getMDOrNull(Record[10]),
01822                            getMDOrNull(Record[11]), getMDOrNull(Record[12]),
01823                            getMDOrNull(Record[13]))),
01824           NextMDValueNo++);
01825       break;
01826     }
01827     case bitc::METADATA_SUBPROGRAM: {
01828       if (Record.size() != 19)
01829         return Error("Invalid record");
01830 
01831       MDValueList.AssignValue(
01832           GET_OR_DISTINCT(
01833               MDSubprogram, Record[0],
01834               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
01835                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
01836                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
01837                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
01838                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
01839                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
01840           NextMDValueNo++);
01841       break;
01842     }
01843     case bitc::METADATA_LEXICAL_BLOCK: {
01844       if (Record.size() != 5)
01845         return Error("Invalid record");
01846 
01847       MDValueList.AssignValue(
01848           GET_OR_DISTINCT(MDLexicalBlock, Record[0],
01849                           (Context, getMDOrNull(Record[1]),
01850                            getMDOrNull(Record[2]), Record[3], Record[4])),
01851           NextMDValueNo++);
01852       break;
01853     }
01854     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
01855       if (Record.size() != 4)
01856         return Error("Invalid record");
01857 
01858       MDValueList.AssignValue(
01859           GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
01860                           (Context, getMDOrNull(Record[1]),
01861                            getMDOrNull(Record[2]), Record[3])),
01862           NextMDValueNo++);
01863       break;
01864     }
01865     case bitc::METADATA_NAMESPACE: {
01866       if (Record.size() != 5)
01867         return Error("Invalid record");
01868 
01869       MDValueList.AssignValue(
01870           GET_OR_DISTINCT(MDNamespace, Record[0],
01871                           (Context, getMDOrNull(Record[1]),
01872                            getMDOrNull(Record[2]), getMDString(Record[3]),
01873                            Record[4])),
01874           NextMDValueNo++);
01875       break;
01876     }
01877     case bitc::METADATA_TEMPLATE_TYPE: {
01878       if (Record.size() != 3)
01879         return Error("Invalid record");
01880 
01881       MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
01882                                               Record[0],
01883                                               (Context, getMDString(Record[1]),
01884                                                getMDOrNull(Record[2]))),
01885                               NextMDValueNo++);
01886       break;
01887     }
01888     case bitc::METADATA_TEMPLATE_VALUE: {
01889       if (Record.size() != 5)
01890         return Error("Invalid record");
01891 
01892       MDValueList.AssignValue(
01893           GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
01894                           (Context, Record[1], getMDString(Record[2]),
01895                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
01896           NextMDValueNo++);
01897       break;
01898     }
01899     case bitc::METADATA_GLOBAL_VAR: {
01900       if (Record.size() != 11)
01901         return Error("Invalid record");
01902 
01903       MDValueList.AssignValue(
01904           GET_OR_DISTINCT(MDGlobalVariable, Record[0],
01905                           (Context, getMDOrNull(Record[1]),
01906                            getMDString(Record[2]), getMDString(Record[3]),
01907                            getMDOrNull(Record[4]), Record[5],
01908                            getMDOrNull(Record[6]), Record[7], Record[8],
01909                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
01910           NextMDValueNo++);
01911       break;
01912     }
01913     case bitc::METADATA_LOCAL_VAR: {
01914       if (Record.size() != 10)
01915         return Error("Invalid record");
01916 
01917       MDValueList.AssignValue(
01918           GET_OR_DISTINCT(MDLocalVariable, Record[0],
01919                           (Context, Record[1], getMDOrNull(Record[2]),
01920                            getMDString(Record[3]), getMDOrNull(Record[4]),
01921                            Record[5], getMDOrNull(Record[6]), Record[7],
01922                            Record[8], getMDOrNull(Record[9]))),
01923           NextMDValueNo++);
01924       break;
01925     }
01926     case bitc::METADATA_EXPRESSION: {
01927       if (Record.size() < 1)
01928         return Error("Invalid record");
01929 
01930       MDValueList.AssignValue(
01931           GET_OR_DISTINCT(MDExpression, Record[0],
01932                           (Context, makeArrayRef(Record).slice(1))),
01933           NextMDValueNo++);
01934       break;
01935     }
01936     case bitc::METADATA_OBJC_PROPERTY: {
01937       if (Record.size() != 8)
01938         return Error("Invalid record");
01939 
01940       MDValueList.AssignValue(
01941           GET_OR_DISTINCT(MDObjCProperty, Record[0],
01942                           (Context, getMDString(Record[1]),
01943                            getMDOrNull(Record[2]), Record[3],
01944                            getMDString(Record[4]), getMDString(Record[5]),
01945                            Record[6], getMDOrNull(Record[7]))),
01946           NextMDValueNo++);
01947       break;
01948     }
01949     case bitc::METADATA_IMPORTED_ENTITY: {
01950       if (Record.size() != 6)
01951         return Error("Invalid record");
01952 
01953       MDValueList.AssignValue(
01954           GET_OR_DISTINCT(MDImportedEntity, Record[0],
01955                           (Context, Record[1], getMDOrNull(Record[2]),
01956                            getMDOrNull(Record[3]), Record[4],
01957                            getMDString(Record[5]))),
01958           NextMDValueNo++);
01959       break;
01960     }
01961     case bitc::METADATA_STRING: {
01962       std::string String(Record.begin(), Record.end());
01963       llvm::UpgradeMDStringConstant(String);
01964       Metadata *MD = MDString::get(Context, String);
01965       MDValueList.AssignValue(MD, NextMDValueNo++);
01966       break;
01967     }
01968     case bitc::METADATA_KIND: {
01969       if (Record.size() < 2)
01970         return Error("Invalid record");
01971 
01972       unsigned Kind = Record[0];
01973       SmallString<8> Name(Record.begin()+1, Record.end());
01974 
01975       unsigned NewKind = TheModule->getMDKindID(Name.str());
01976       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
01977         return Error("Conflicting METADATA_KIND records");
01978       break;
01979     }
01980     }
01981   }
01982 #undef GET_OR_DISTINCT
01983 }
01984 
01985 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
01986 /// the LSB for dense VBR encoding.
01987 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
01988   if ((V & 1) == 0)
01989     return V >> 1;
01990   if (V != 1)
01991     return -(V >> 1);
01992   // There is no such thing as -0 with integers.  "-0" really means MININT.
01993   return 1ULL << 63;
01994 }
01995 
01996 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
01997 /// values and aliases that we can.
01998 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
01999   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
02000   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
02001   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
02002   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
02003 
02004   GlobalInitWorklist.swap(GlobalInits);
02005   AliasInitWorklist.swap(AliasInits);
02006   FunctionPrefixWorklist.swap(FunctionPrefixes);
02007   FunctionPrologueWorklist.swap(FunctionPrologues);
02008 
02009   while (!GlobalInitWorklist.empty()) {
02010     unsigned ValID = GlobalInitWorklist.back().second;
02011     if (ValID >= ValueList.size()) {
02012       // Not ready to resolve this yet, it requires something later in the file.
02013       GlobalInits.push_back(GlobalInitWorklist.back());
02014     } else {
02015       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
02016         GlobalInitWorklist.back().first->setInitializer(C);
02017       else
02018         return Error("Expected a constant");
02019     }
02020     GlobalInitWorklist.pop_back();
02021   }
02022 
02023   while (!AliasInitWorklist.empty()) {
02024     unsigned ValID = AliasInitWorklist.back().second;
02025     if (ValID >= ValueList.size()) {
02026       AliasInits.push_back(AliasInitWorklist.back());
02027     } else {
02028       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
02029         AliasInitWorklist.back().first->setAliasee(C);
02030       else
02031         return Error("Expected a constant");
02032     }
02033     AliasInitWorklist.pop_back();
02034   }
02035 
02036   while (!FunctionPrefixWorklist.empty()) {
02037     unsigned ValID = FunctionPrefixWorklist.back().second;
02038     if (ValID >= ValueList.size()) {
02039       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
02040     } else {
02041       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
02042         FunctionPrefixWorklist.back().first->setPrefixData(C);
02043       else
02044         return Error("Expected a constant");
02045     }
02046     FunctionPrefixWorklist.pop_back();
02047   }
02048 
02049   while (!FunctionPrologueWorklist.empty()) {
02050     unsigned ValID = FunctionPrologueWorklist.back().second;
02051     if (ValID >= ValueList.size()) {
02052       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
02053     } else {
02054       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
02055         FunctionPrologueWorklist.back().first->setPrologueData(C);
02056       else
02057         return Error("Expected a constant");
02058     }
02059     FunctionPrologueWorklist.pop_back();
02060   }
02061 
02062   return std::error_code();
02063 }
02064 
02065 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
02066   SmallVector<uint64_t, 8> Words(Vals.size());
02067   std::transform(Vals.begin(), Vals.end(), Words.begin(),
02068                  BitcodeReader::decodeSignRotatedValue);
02069 
02070   return APInt(TypeBits, Words);
02071 }
02072 
02073 std::error_code BitcodeReader::ParseConstants() {
02074   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
02075     return Error("Invalid record");
02076 
02077   SmallVector<uint64_t, 64> Record;
02078 
02079   // Read all the records for this value table.
02080   Type *CurTy = Type::getInt32Ty(Context);
02081   unsigned NextCstNo = ValueList.size();
02082   while (1) {
02083     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02084 
02085     switch (Entry.Kind) {
02086     case BitstreamEntry::SubBlock: // Handled for us already.
02087     case BitstreamEntry::Error:
02088       return Error("Malformed block");
02089     case BitstreamEntry::EndBlock:
02090       if (NextCstNo != ValueList.size())
02091         return Error("Invalid ronstant reference");
02092 
02093       // Once all the constants have been read, go through and resolve forward
02094       // references.
02095       ValueList.ResolveConstantForwardRefs();
02096       return std::error_code();
02097     case BitstreamEntry::Record:
02098       // The interesting case.
02099       break;
02100     }
02101 
02102     // Read a record.
02103     Record.clear();
02104     Value *V = nullptr;
02105     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
02106     switch (BitCode) {
02107     default:  // Default behavior: unknown constant
02108     case bitc::CST_CODE_UNDEF:     // UNDEF
02109       V = UndefValue::get(CurTy);
02110       break;
02111     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
02112       if (Record.empty())
02113         return Error("Invalid record");
02114       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
02115         return Error("Invalid record");
02116       CurTy = TypeList[Record[0]];
02117       continue;  // Skip the ValueList manipulation.
02118     case bitc::CST_CODE_NULL:      // NULL
02119       V = Constant::getNullValue(CurTy);
02120       break;
02121     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
02122       if (!CurTy->isIntegerTy() || Record.empty())
02123         return Error("Invalid record");
02124       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
02125       break;
02126     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
02127       if (!CurTy->isIntegerTy() || Record.empty())
02128         return Error("Invalid record");
02129 
02130       APInt VInt = ReadWideAPInt(Record,
02131                                  cast<IntegerType>(CurTy)->getBitWidth());
02132       V = ConstantInt::get(Context, VInt);
02133 
02134       break;
02135     }
02136     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
02137       if (Record.empty())
02138         return Error("Invalid record");
02139       if (CurTy->isHalfTy())
02140         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
02141                                              APInt(16, (uint16_t)Record[0])));
02142       else if (CurTy->isFloatTy())
02143         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
02144                                              APInt(32, (uint32_t)Record[0])));
02145       else if (CurTy->isDoubleTy())
02146         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
02147                                              APInt(64, Record[0])));
02148       else if (CurTy->isX86_FP80Ty()) {
02149         // Bits are not stored the same way as a normal i80 APInt, compensate.
02150         uint64_t Rearrange[2];
02151         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
02152         Rearrange[1] = Record[0] >> 48;
02153         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
02154                                              APInt(80, Rearrange)));
02155       } else if (CurTy->isFP128Ty())
02156         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
02157                                              APInt(128, Record)));
02158       else if (CurTy->isPPC_FP128Ty())
02159         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
02160                                              APInt(128, Record)));
02161       else
02162         V = UndefValue::get(CurTy);
02163       break;
02164     }
02165 
02166     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
02167       if (Record.empty())
02168         return Error("Invalid record");
02169 
02170       unsigned Size = Record.size();
02171       SmallVector<Constant*, 16> Elts;
02172 
02173       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
02174         for (unsigned i = 0; i != Size; ++i)
02175           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
02176                                                      STy->getElementType(i)));
02177         V = ConstantStruct::get(STy, Elts);
02178       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
02179         Type *EltTy = ATy->getElementType();
02180         for (unsigned i = 0; i != Size; ++i)
02181           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
02182         V = ConstantArray::get(ATy, Elts);
02183       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
02184         Type *EltTy = VTy->getElementType();
02185         for (unsigned i = 0; i != Size; ++i)
02186           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
02187         V = ConstantVector::get(Elts);
02188       } else {
02189         V = UndefValue::get(CurTy);
02190       }
02191       break;
02192     }
02193     case bitc::CST_CODE_STRING:    // STRING: [values]
02194     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
02195       if (Record.empty())
02196         return Error("Invalid record");
02197 
02198       SmallString<16> Elts(Record.begin(), Record.end());
02199       V = ConstantDataArray::getString(Context, Elts,
02200                                        BitCode == bitc::CST_CODE_CSTRING);
02201       break;
02202     }
02203     case bitc::CST_CODE_DATA: {// DATA: [n x value]
02204       if (Record.empty())
02205         return Error("Invalid record");
02206 
02207       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
02208       unsigned Size = Record.size();
02209 
02210       if (EltTy->isIntegerTy(8)) {
02211         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
02212         if (isa<VectorType>(CurTy))
02213           V = ConstantDataVector::get(Context, Elts);
02214         else
02215           V = ConstantDataArray::get(Context, Elts);
02216       } else if (EltTy->isIntegerTy(16)) {
02217         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
02218         if (isa<VectorType>(CurTy))
02219           V = ConstantDataVector::get(Context, Elts);
02220         else
02221           V = ConstantDataArray::get(Context, Elts);
02222       } else if (EltTy->isIntegerTy(32)) {
02223         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
02224         if (isa<VectorType>(CurTy))
02225           V = ConstantDataVector::get(Context, Elts);
02226         else
02227           V = ConstantDataArray::get(Context, Elts);
02228       } else if (EltTy->isIntegerTy(64)) {
02229         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
02230         if (isa<VectorType>(CurTy))
02231           V = ConstantDataVector::get(Context, Elts);
02232         else
02233           V = ConstantDataArray::get(Context, Elts);
02234       } else if (EltTy->isFloatTy()) {
02235         SmallVector<float, 16> Elts(Size);
02236         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
02237         if (isa<VectorType>(CurTy))
02238           V = ConstantDataVector::get(Context, Elts);
02239         else
02240           V = ConstantDataArray::get(Context, Elts);
02241       } else if (EltTy->isDoubleTy()) {
02242         SmallVector<double, 16> Elts(Size);
02243         std::transform(Record.begin(), Record.end(), Elts.begin(),
02244                        BitsToDouble);
02245         if (isa<VectorType>(CurTy))
02246           V = ConstantDataVector::get(Context, Elts);
02247         else
02248           V = ConstantDataArray::get(Context, Elts);
02249       } else {
02250         return Error("Invalid type for value");
02251       }
02252       break;
02253     }
02254 
02255     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
02256       if (Record.size() < 3)
02257         return Error("Invalid record");
02258       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
02259       if (Opc < 0) {
02260         V = UndefValue::get(CurTy);  // Unknown binop.
02261       } else {
02262         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
02263         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
02264         unsigned Flags = 0;
02265         if (Record.size() >= 4) {
02266           if (Opc == Instruction::Add ||
02267               Opc == Instruction::Sub ||
02268               Opc == Instruction::Mul ||
02269               Opc == Instruction::Shl) {
02270             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
02271               Flags |= OverflowingBinaryOperator::NoSignedWrap;
02272             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
02273               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
02274           } else if (Opc == Instruction::SDiv ||
02275                      Opc == Instruction::UDiv ||
02276                      Opc == Instruction::LShr ||
02277                      Opc == Instruction::AShr) {
02278             if (Record[3] & (1 << bitc::PEO_EXACT))
02279               Flags |= SDivOperator::IsExact;
02280           }
02281         }
02282         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
02283       }
02284       break;
02285     }
02286     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
02287       if (Record.size() < 3)
02288         return Error("Invalid record");
02289       int Opc = GetDecodedCastOpcode(Record[0]);
02290       if (Opc < 0) {
02291         V = UndefValue::get(CurTy);  // Unknown cast.
02292       } else {
02293         Type *OpTy = getTypeByID(Record[1]);
02294         if (!OpTy)
02295           return Error("Invalid record");
02296         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
02297         V = UpgradeBitCastExpr(Opc, Op, CurTy);
02298         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
02299       }
02300       break;
02301     }
02302     case bitc::CST_CODE_CE_INBOUNDS_GEP:
02303     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
02304       unsigned OpNum = 0;
02305       Type *PointeeType = nullptr;
02306       if (Record.size() % 2)
02307         PointeeType = getTypeByID(Record[OpNum++]);
02308       SmallVector<Constant*, 16> Elts;
02309       while (OpNum != Record.size()) {
02310         Type *ElTy = getTypeByID(Record[OpNum++]);
02311         if (!ElTy)
02312           return Error("Invalid record");
02313         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
02314       }
02315 
02316       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
02317       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
02318                                          BitCode ==
02319                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
02320       if (PointeeType &&
02321           PointeeType != cast<GEPOperator>(V)->getSourceElementType())
02322         return Error("Explicit gep operator type does not match pointee type "
02323                      "of pointer operand");
02324       break;
02325     }
02326     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
02327       if (Record.size() < 3)
02328         return Error("Invalid record");
02329 
02330       Type *SelectorTy = Type::getInt1Ty(Context);
02331 
02332       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
02333       // vector. Otherwise, it must be a single bit.
02334       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
02335         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
02336                                      VTy->getNumElements());
02337 
02338       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
02339                                                               SelectorTy),
02340                                   ValueList.getConstantFwdRef(Record[1],CurTy),
02341                                   ValueList.getConstantFwdRef(Record[2],CurTy));
02342       break;
02343     }
02344     case bitc::CST_CODE_CE_EXTRACTELT
02345         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
02346       if (Record.size() < 3)
02347         return Error("Invalid record");
02348       VectorType *OpTy =
02349         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
02350       if (!OpTy)
02351         return Error("Invalid record");
02352       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
02353       Constant *Op1 = nullptr;
02354       if (Record.size() == 4) {
02355         Type *IdxTy = getTypeByID(Record[2]);
02356         if (!IdxTy)
02357           return Error("Invalid record");
02358         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
02359       } else // TODO: Remove with llvm 4.0
02360         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
02361       if (!Op1)
02362         return Error("Invalid record");
02363       V = ConstantExpr::getExtractElement(Op0, Op1);
02364       break;
02365     }
02366     case bitc::CST_CODE_CE_INSERTELT
02367         : { // CE_INSERTELT: [opval, opval, opty, opval]
02368       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
02369       if (Record.size() < 3 || !OpTy)
02370         return Error("Invalid record");
02371       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
02372       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
02373                                                   OpTy->getElementType());
02374       Constant *Op2 = nullptr;
02375       if (Record.size() == 4) {
02376         Type *IdxTy = getTypeByID(Record[2]);
02377         if (!IdxTy)
02378           return Error("Invalid record");
02379         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
02380       } else // TODO: Remove with llvm 4.0
02381         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
02382       if (!Op2)
02383         return Error("Invalid record");
02384       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
02385       break;
02386     }
02387     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
02388       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
02389       if (Record.size() < 3 || !OpTy)
02390         return Error("Invalid record");
02391       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
02392       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
02393       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
02394                                                  OpTy->getNumElements());
02395       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
02396       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
02397       break;
02398     }
02399     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
02400       VectorType *RTy = dyn_cast<VectorType>(CurTy);
02401       VectorType *OpTy =
02402         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
02403       if (Record.size() < 4 || !RTy || !OpTy)
02404         return Error("Invalid record");
02405       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
02406       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
02407       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
02408                                                  RTy->getNumElements());
02409       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
02410       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
02411       break;
02412     }
02413     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
02414       if (Record.size() < 4)
02415         return Error("Invalid record");
02416       Type *OpTy = getTypeByID(Record[0]);
02417       if (!OpTy)
02418         return Error("Invalid record");
02419       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
02420       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
02421 
02422       if (OpTy->isFPOrFPVectorTy())
02423         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
02424       else
02425         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
02426       break;
02427     }
02428     // This maintains backward compatibility, pre-asm dialect keywords.
02429     // FIXME: Remove with the 4.0 release.
02430     case bitc::CST_CODE_INLINEASM_OLD: {
02431       if (Record.size() < 2)
02432         return Error("Invalid record");
02433       std::string AsmStr, ConstrStr;
02434       bool HasSideEffects = Record[0] & 1;
02435       bool IsAlignStack = Record[0] >> 1;
02436       unsigned AsmStrSize = Record[1];
02437       if (2+AsmStrSize >= Record.size())
02438         return Error("Invalid record");
02439       unsigned ConstStrSize = Record[2+AsmStrSize];
02440       if (3+AsmStrSize+ConstStrSize > Record.size())
02441         return Error("Invalid record");
02442 
02443       for (unsigned i = 0; i != AsmStrSize; ++i)
02444         AsmStr += (char)Record[2+i];
02445       for (unsigned i = 0; i != ConstStrSize; ++i)
02446         ConstrStr += (char)Record[3+AsmStrSize+i];
02447       PointerType *PTy = cast<PointerType>(CurTy);
02448       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
02449                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
02450       break;
02451     }
02452     // This version adds support for the asm dialect keywords (e.g.,
02453     // inteldialect).
02454     case bitc::CST_CODE_INLINEASM: {
02455       if (Record.size() < 2)
02456         return Error("Invalid record");
02457       std::string AsmStr, ConstrStr;
02458       bool HasSideEffects = Record[0] & 1;
02459       bool IsAlignStack = (Record[0] >> 1) & 1;
02460       unsigned AsmDialect = Record[0] >> 2;
02461       unsigned AsmStrSize = Record[1];
02462       if (2+AsmStrSize >= Record.size())
02463         return Error("Invalid record");
02464       unsigned ConstStrSize = Record[2+AsmStrSize];
02465       if (3+AsmStrSize+ConstStrSize > Record.size())
02466         return Error("Invalid record");
02467 
02468       for (unsigned i = 0; i != AsmStrSize; ++i)
02469         AsmStr += (char)Record[2+i];
02470       for (unsigned i = 0; i != ConstStrSize; ++i)
02471         ConstrStr += (char)Record[3+AsmStrSize+i];
02472       PointerType *PTy = cast<PointerType>(CurTy);
02473       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
02474                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
02475                          InlineAsm::AsmDialect(AsmDialect));
02476       break;
02477     }
02478     case bitc::CST_CODE_BLOCKADDRESS:{
02479       if (Record.size() < 3)
02480         return Error("Invalid record");
02481       Type *FnTy = getTypeByID(Record[0]);
02482       if (!FnTy)
02483         return Error("Invalid record");
02484       Function *Fn =
02485         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
02486       if (!Fn)
02487         return Error("Invalid record");
02488 
02489       // Don't let Fn get dematerialized.
02490       BlockAddressesTaken.insert(Fn);
02491 
02492       // If the function is already parsed we can insert the block address right
02493       // away.
02494       BasicBlock *BB;
02495       unsigned BBID = Record[2];
02496       if (!BBID)
02497         // Invalid reference to entry block.
02498         return Error("Invalid ID");
02499       if (!Fn->empty()) {
02500         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
02501         for (size_t I = 0, E = BBID; I != E; ++I) {
02502           if (BBI == BBE)
02503             return Error("Invalid ID");
02504           ++BBI;
02505         }
02506         BB = BBI;
02507       } else {
02508         // Otherwise insert a placeholder and remember it so it can be inserted
02509         // when the function is parsed.
02510         auto &FwdBBs = BasicBlockFwdRefs[Fn];
02511         if (FwdBBs.empty())
02512           BasicBlockFwdRefQueue.push_back(Fn);
02513         if (FwdBBs.size() < BBID + 1)
02514           FwdBBs.resize(BBID + 1);
02515         if (!FwdBBs[BBID])
02516           FwdBBs[BBID] = BasicBlock::Create(Context);
02517         BB = FwdBBs[BBID];
02518       }
02519       V = BlockAddress::get(Fn, BB);
02520       break;
02521     }
02522     }
02523 
02524     ValueList.AssignValue(V, NextCstNo);
02525     ++NextCstNo;
02526   }
02527 }
02528 
02529 std::error_code BitcodeReader::ParseUseLists() {
02530   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
02531     return Error("Invalid record");
02532 
02533   // Read all the records.
02534   SmallVector<uint64_t, 64> Record;
02535   while (1) {
02536     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02537 
02538     switch (Entry.Kind) {
02539     case BitstreamEntry::SubBlock: // Handled for us already.
02540     case BitstreamEntry::Error:
02541       return Error("Malformed block");
02542     case BitstreamEntry::EndBlock:
02543       return std::error_code();
02544     case BitstreamEntry::Record:
02545       // The interesting case.
02546       break;
02547     }
02548 
02549     // Read a use list record.
02550     Record.clear();
02551     bool IsBB = false;
02552     switch (Stream.readRecord(Entry.ID, Record)) {
02553     default:  // Default behavior: unknown type.
02554       break;
02555     case bitc::USELIST_CODE_BB:
02556       IsBB = true;
02557       // fallthrough
02558     case bitc::USELIST_CODE_DEFAULT: {
02559       unsigned RecordLength = Record.size();
02560       if (RecordLength < 3)
02561         // Records should have at least an ID and two indexes.
02562         return Error("Invalid record");
02563       unsigned ID = Record.back();
02564       Record.pop_back();
02565 
02566       Value *V;
02567       if (IsBB) {
02568         assert(ID < FunctionBBs.size() && "Basic block not found");
02569         V = FunctionBBs[ID];
02570       } else
02571         V = ValueList[ID];
02572       unsigned NumUses = 0;
02573       SmallDenseMap<const Use *, unsigned, 16> Order;
02574       for (const Use &U : V->uses()) {
02575         if (++NumUses > Record.size())
02576           break;
02577         Order[&U] = Record[NumUses - 1];
02578       }
02579       if (Order.size() != Record.size() || NumUses > Record.size())
02580         // Mismatches can happen if the functions are being materialized lazily
02581         // (out-of-order), or a value has been upgraded.
02582         break;
02583 
02584       V->sortUseList([&](const Use &L, const Use &R) {
02585         return Order.lookup(&L) < Order.lookup(&R);
02586       });
02587       break;
02588     }
02589     }
02590   }
02591 }
02592 
02593 /// When we see the block for metadata, remember where it is and then skip it.
02594 /// This lets us lazily deserialize the metadata.
02595 std::error_code BitcodeReader::rememberAndSkipMetadata() {
02596   // Save the current stream state.
02597   uint64_t CurBit = Stream.GetCurrentBitNo();
02598   DeferredMetadataInfo.push_back(CurBit);
02599 
02600   // Skip over the block for now.
02601   if (Stream.SkipBlock())
02602     return Error("Invalid record");
02603   return std::error_code();
02604 }
02605 
02606 std::error_code BitcodeReader::materializeMetadata() {
02607   for (uint64_t BitPos : DeferredMetadataInfo) {
02608     // Move the bit stream to the saved position.
02609     Stream.JumpToBit(BitPos);
02610     if (std::error_code EC = ParseMetadata())
02611       return EC;
02612   }
02613   DeferredMetadataInfo.clear();
02614   return std::error_code();
02615 }
02616 
02617 void BitcodeReader::setStripDebugInfo() {
02618   StripDebugInfo = true;
02619 }
02620 
02621 /// RememberAndSkipFunctionBody - When we see the block for a function body,
02622 /// remember where it is and then skip it.  This lets us lazily deserialize the
02623 /// functions.
02624 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
02625   // Get the function we are talking about.
02626   if (FunctionsWithBodies.empty())
02627     return Error("Insufficient function protos");
02628 
02629   Function *Fn = FunctionsWithBodies.back();
02630   FunctionsWithBodies.pop_back();
02631 
02632   // Save the current stream state.
02633   uint64_t CurBit = Stream.GetCurrentBitNo();
02634   DeferredFunctionInfo[Fn] = CurBit;
02635 
02636   // Skip over the function block for now.
02637   if (Stream.SkipBlock())
02638     return Error("Invalid record");
02639   return std::error_code();
02640 }
02641 
02642 std::error_code BitcodeReader::GlobalCleanup() {
02643   // Patch the initializers for globals and aliases up.
02644   ResolveGlobalAndAliasInits();
02645   if (!GlobalInits.empty() || !AliasInits.empty())
02646     return Error("Malformed global initializer set");
02647 
02648   // Look for intrinsic functions which need to be upgraded at some point
02649   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
02650        FI != FE; ++FI) {
02651     Function *NewFn;
02652     if (UpgradeIntrinsicFunction(FI, NewFn))
02653       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
02654   }
02655 
02656   // Look for global variables which need to be renamed.
02657   for (Module::global_iterator
02658          GI = TheModule->global_begin(), GE = TheModule->global_end();
02659        GI != GE;) {
02660     GlobalVariable *GV = GI++;
02661     UpgradeGlobalVariable(GV);
02662   }
02663 
02664   // Force deallocation of memory for these vectors to favor the client that
02665   // want lazy deserialization.
02666   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
02667   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
02668   return std::error_code();
02669 }
02670 
02671 std::error_code BitcodeReader::ParseModule(bool Resume,
02672                                            bool ShouldLazyLoadMetadata) {
02673   if (Resume)
02674     Stream.JumpToBit(NextUnreadBit);
02675   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
02676     return Error("Invalid record");
02677 
02678   SmallVector<uint64_t, 64> Record;
02679   std::vector<std::string> SectionTable;
02680   std::vector<std::string> GCTable;
02681 
02682   // Read all the records for this module.
02683   while (1) {
02684     BitstreamEntry Entry = Stream.advance();
02685 
02686     switch (Entry.Kind) {
02687     case BitstreamEntry::Error:
02688       return Error("Malformed block");
02689     case BitstreamEntry::EndBlock:
02690       return GlobalCleanup();
02691 
02692     case BitstreamEntry::SubBlock:
02693       switch (Entry.ID) {
02694       default:  // Skip unknown content.
02695         if (Stream.SkipBlock())
02696           return Error("Invalid record");
02697         break;
02698       case bitc::BLOCKINFO_BLOCK_ID:
02699         if (Stream.ReadBlockInfoBlock())
02700           return Error("Malformed block");
02701         break;
02702       case bitc::PARAMATTR_BLOCK_ID:
02703         if (std::error_code EC = ParseAttributeBlock())
02704           return EC;
02705         break;
02706       case bitc::PARAMATTR_GROUP_BLOCK_ID:
02707         if (std::error_code EC = ParseAttributeGroupBlock())
02708           return EC;
02709         break;
02710       case bitc::TYPE_BLOCK_ID_NEW:
02711         if (std::error_code EC = ParseTypeTable())
02712           return EC;
02713         break;
02714       case bitc::VALUE_SYMTAB_BLOCK_ID:
02715         if (std::error_code EC = ParseValueSymbolTable())
02716           return EC;
02717         SeenValueSymbolTable = true;
02718         break;
02719       case bitc::CONSTANTS_BLOCK_ID:
02720         if (std::error_code EC = ParseConstants())
02721           return EC;
02722         if (std::error_code EC = ResolveGlobalAndAliasInits())
02723           return EC;
02724         break;
02725       case bitc::METADATA_BLOCK_ID:
02726         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
02727           if (std::error_code EC = rememberAndSkipMetadata())
02728             return EC;
02729           break;
02730         }
02731         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
02732         if (std::error_code EC = ParseMetadata())
02733           return EC;
02734         break;
02735       case bitc::FUNCTION_BLOCK_ID:
02736         // If this is the first function body we've seen, reverse the
02737         // FunctionsWithBodies list.
02738         if (!SeenFirstFunctionBody) {
02739           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
02740           if (std::error_code EC = GlobalCleanup())
02741             return EC;
02742           SeenFirstFunctionBody = true;
02743         }
02744 
02745         if (std::error_code EC = RememberAndSkipFunctionBody())
02746           return EC;
02747         // For streaming bitcode, suspend parsing when we reach the function
02748         // bodies. Subsequent materialization calls will resume it when
02749         // necessary. For streaming, the function bodies must be at the end of
02750         // the bitcode. If the bitcode file is old, the symbol table will be
02751         // at the end instead and will not have been seen yet. In this case,
02752         // just finish the parse now.
02753         if (LazyStreamer && SeenValueSymbolTable) {
02754           NextUnreadBit = Stream.GetCurrentBitNo();
02755           return std::error_code();
02756         }
02757         break;
02758       case bitc::USELIST_BLOCK_ID:
02759         if (std::error_code EC = ParseUseLists())
02760           return EC;
02761         break;
02762       }
02763       continue;
02764 
02765     case BitstreamEntry::Record:
02766       // The interesting case.
02767       break;
02768     }
02769 
02770 
02771     // Read a record.
02772     switch (Stream.readRecord(Entry.ID, Record)) {
02773     default: break;  // Default behavior, ignore unknown content.
02774     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
02775       if (Record.size() < 1)
02776         return Error("Invalid record");
02777       // Only version #0 and #1 are supported so far.
02778       unsigned module_version = Record[0];
02779       switch (module_version) {
02780         default:
02781           return Error("Invalid value");
02782         case 0:
02783           UseRelativeIDs = false;
02784           break;
02785         case 1:
02786           UseRelativeIDs = true;
02787           break;
02788       }
02789       break;
02790     }
02791     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
02792       std::string S;
02793       if (ConvertToString(Record, 0, S))
02794         return Error("Invalid record");
02795       TheModule->setTargetTriple(S);
02796       break;
02797     }
02798     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
02799       std::string S;
02800       if (ConvertToString(Record, 0, S))
02801         return Error("Invalid record");
02802       TheModule->setDataLayout(S);
02803       break;
02804     }
02805     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
02806       std::string S;
02807       if (ConvertToString(Record, 0, S))
02808         return Error("Invalid record");
02809       TheModule->setModuleInlineAsm(S);
02810       break;
02811     }
02812     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
02813       // FIXME: Remove in 4.0.
02814       std::string S;
02815       if (ConvertToString(Record, 0, S))
02816         return Error("Invalid record");
02817       // Ignore value.
02818       break;
02819     }
02820     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
02821       std::string S;
02822       if (ConvertToString(Record, 0, S))
02823         return Error("Invalid record");
02824       SectionTable.push_back(S);
02825       break;
02826     }
02827     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
02828       std::string S;
02829       if (ConvertToString(Record, 0, S))
02830         return Error("Invalid record");
02831       GCTable.push_back(S);
02832       break;
02833     }
02834     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
02835       if (Record.size() < 2)
02836         return Error("Invalid record");
02837       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
02838       unsigned ComdatNameSize = Record[1];
02839       std::string ComdatName;
02840       ComdatName.reserve(ComdatNameSize);
02841       for (unsigned i = 0; i != ComdatNameSize; ++i)
02842         ComdatName += (char)Record[2 + i];
02843       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
02844       C->setSelectionKind(SK);
02845       ComdatList.push_back(C);
02846       break;
02847     }
02848     // GLOBALVAR: [pointer type, isconst, initid,
02849     //             linkage, alignment, section, visibility, threadlocal,
02850     //             unnamed_addr, externally_initialized, dllstorageclass,
02851     //             comdat]
02852     case bitc::MODULE_CODE_GLOBALVAR: {
02853       if (Record.size() < 6)
02854         return Error("Invalid record");
02855       Type *Ty = getTypeByID(Record[0]);
02856       if (!Ty)
02857         return Error("Invalid record");
02858       if (!Ty->isPointerTy())
02859         return Error("Invalid type for value");
02860       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
02861       Ty = cast<PointerType>(Ty)->getElementType();
02862 
02863       bool isConstant = Record[1];
02864       uint64_t RawLinkage = Record[3];
02865       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
02866       unsigned Alignment;
02867       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
02868         return EC;
02869       std::string Section;
02870       if (Record[5]) {
02871         if (Record[5]-1 >= SectionTable.size())
02872           return Error("Invalid ID");
02873         Section = SectionTable[Record[5]-1];
02874       }
02875       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
02876       // Local linkage must have default visibility.
02877       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
02878         // FIXME: Change to an error if non-default in 4.0.
02879         Visibility = GetDecodedVisibility(Record[6]);
02880 
02881       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
02882       if (Record.size() > 7)
02883         TLM = GetDecodedThreadLocalMode(Record[7]);
02884 
02885       bool UnnamedAddr = false;
02886       if (Record.size() > 8)
02887         UnnamedAddr = Record[8];
02888 
02889       bool ExternallyInitialized = false;
02890       if (Record.size() > 9)
02891         ExternallyInitialized = Record[9];
02892 
02893       GlobalVariable *NewGV =
02894         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
02895                            TLM, AddressSpace, ExternallyInitialized);
02896       NewGV->setAlignment(Alignment);
02897       if (!Section.empty())
02898         NewGV->setSection(Section);
02899       NewGV->setVisibility(Visibility);
02900       NewGV->setUnnamedAddr(UnnamedAddr);
02901 
02902       if (Record.size() > 10)
02903         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
02904       else
02905         UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
02906 
02907       ValueList.push_back(NewGV);
02908 
02909       // Remember which value to use for the global initializer.
02910       if (unsigned InitID = Record[2])
02911         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
02912 
02913       if (Record.size() > 11) {
02914         if (unsigned ComdatID = Record[11]) {
02915           assert(ComdatID <= ComdatList.size());
02916           NewGV->setComdat(ComdatList[ComdatID - 1]);
02917         }
02918       } else if (hasImplicitComdat(RawLinkage)) {
02919         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
02920       }
02921       break;
02922     }
02923     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
02924     //             alignment, section, visibility, gc, unnamed_addr,
02925     //             prologuedata, dllstorageclass, comdat, prefixdata]
02926     case bitc::MODULE_CODE_FUNCTION: {
02927       if (Record.size() < 8)
02928         return Error("Invalid record");
02929       Type *Ty = getTypeByID(Record[0]);
02930       if (!Ty)
02931         return Error("Invalid record");
02932       if (!Ty->isPointerTy())
02933         return Error("Invalid type for value");
02934       FunctionType *FTy =
02935         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
02936       if (!FTy)
02937         return Error("Invalid type for value");
02938 
02939       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
02940                                         "", TheModule);
02941 
02942       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
02943       bool isProto = Record[2];
02944       uint64_t RawLinkage = Record[3];
02945       Func->setLinkage(getDecodedLinkage(RawLinkage));
02946       Func->setAttributes(getAttributes(Record[4]));
02947 
02948       unsigned Alignment;
02949       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
02950         return EC;
02951       Func->setAlignment(Alignment);
02952       if (Record[6]) {
02953         if (Record[6]-1 >= SectionTable.size())
02954           return Error("Invalid ID");
02955         Func->setSection(SectionTable[Record[6]-1]);
02956       }
02957       // Local linkage must have default visibility.
02958       if (!Func->hasLocalLinkage())
02959         // FIXME: Change to an error if non-default in 4.0.
02960         Func->setVisibility(GetDecodedVisibility(Record[7]));
02961       if (Record.size() > 8 && Record[8]) {
02962         if (Record[8]-1 > GCTable.size())
02963           return Error("Invalid ID");
02964         Func->setGC(GCTable[Record[8]-1].c_str());
02965       }
02966       bool UnnamedAddr = false;
02967       if (Record.size() > 9)
02968         UnnamedAddr = Record[9];
02969       Func->setUnnamedAddr(UnnamedAddr);
02970       if (Record.size() > 10 && Record[10] != 0)
02971         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
02972 
02973       if (Record.size() > 11)
02974         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
02975       else
02976         UpgradeDLLImportExportLinkage(Func, RawLinkage);
02977 
02978       if (Record.size() > 12) {
02979         if (unsigned ComdatID = Record[12]) {
02980           assert(ComdatID <= ComdatList.size());
02981           Func->setComdat(ComdatList[ComdatID - 1]);
02982         }
02983       } else if (hasImplicitComdat(RawLinkage)) {
02984         Func->setComdat(reinterpret_cast<Comdat *>(1));
02985       }
02986 
02987       if (Record.size() > 13 && Record[13] != 0)
02988         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
02989 
02990       ValueList.push_back(Func);
02991 
02992       // If this is a function with a body, remember the prototype we are
02993       // creating now, so that we can match up the body with them later.
02994       if (!isProto) {
02995         Func->setIsMaterializable(true);
02996         FunctionsWithBodies.push_back(Func);
02997         if (LazyStreamer)
02998           DeferredFunctionInfo[Func] = 0;
02999       }
03000       break;
03001     }
03002     // ALIAS: [alias type, aliasee val#, linkage]
03003     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
03004     case bitc::MODULE_CODE_ALIAS: {
03005       if (Record.size() < 3)
03006         return Error("Invalid record");
03007       Type *Ty = getTypeByID(Record[0]);
03008       if (!Ty)
03009         return Error("Invalid record");
03010       auto *PTy = dyn_cast<PointerType>(Ty);
03011       if (!PTy)
03012         return Error("Invalid type for value");
03013 
03014       auto *NewGA =
03015           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
03016                               getDecodedLinkage(Record[2]), "", TheModule);
03017       // Old bitcode files didn't have visibility field.
03018       // Local linkage must have default visibility.
03019       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
03020         // FIXME: Change to an error if non-default in 4.0.
03021         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
03022       if (Record.size() > 4)
03023         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
03024       else
03025         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
03026       if (Record.size() > 5)
03027         NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
03028       if (Record.size() > 6)
03029         NewGA->setUnnamedAddr(Record[6]);
03030       ValueList.push_back(NewGA);
03031       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
03032       break;
03033     }
03034     /// MODULE_CODE_PURGEVALS: [numvals]
03035     case bitc::MODULE_CODE_PURGEVALS:
03036       // Trim down the value list to the specified size.
03037       if (Record.size() < 1 || Record[0] > ValueList.size())
03038         return Error("Invalid record");
03039       ValueList.shrinkTo(Record[0]);
03040       break;
03041     }
03042     Record.clear();
03043   }
03044 }
03045 
03046 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
03047                                                 bool ShouldLazyLoadMetadata) {
03048   TheModule = nullptr;
03049 
03050   if (std::error_code EC = InitStream())
03051     return EC;
03052 
03053   // Sniff for the signature.
03054   if (Stream.Read(8) != 'B' ||
03055       Stream.Read(8) != 'C' ||
03056       Stream.Read(4) != 0x0 ||
03057       Stream.Read(4) != 0xC ||
03058       Stream.Read(4) != 0xE ||
03059       Stream.Read(4) != 0xD)
03060     return Error("Invalid bitcode signature");
03061 
03062   // We expect a number of well-defined blocks, though we don't necessarily
03063   // need to understand them all.
03064   while (1) {
03065     if (Stream.AtEndOfStream())
03066       return std::error_code();
03067 
03068     BitstreamEntry Entry =
03069       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
03070 
03071     switch (Entry.Kind) {
03072     case BitstreamEntry::Error:
03073       return Error("Malformed block");
03074     case BitstreamEntry::EndBlock:
03075       return std::error_code();
03076 
03077     case BitstreamEntry::SubBlock:
03078       switch (Entry.ID) {
03079       case bitc::BLOCKINFO_BLOCK_ID:
03080         if (Stream.ReadBlockInfoBlock())
03081           return Error("Malformed block");
03082         break;
03083       case bitc::MODULE_BLOCK_ID:
03084         // Reject multiple MODULE_BLOCK's in a single bitstream.
03085         if (TheModule)
03086           return Error("Invalid multiple blocks");
03087         TheModule = M;
03088         if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
03089           return EC;
03090         if (LazyStreamer)
03091           return std::error_code();
03092         break;
03093       default:
03094         if (Stream.SkipBlock())
03095           return Error("Invalid record");
03096         break;
03097       }
03098       continue;
03099     case BitstreamEntry::Record:
03100       // There should be no records in the top-level of blocks.
03101 
03102       // The ranlib in Xcode 4 will align archive members by appending newlines
03103       // to the end of them. If this file size is a multiple of 4 but not 8, we
03104       // have to read and ignore these final 4 bytes :-(
03105       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
03106           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
03107           Stream.AtEndOfStream())
03108         return std::error_code();
03109 
03110       return Error("Invalid record");
03111     }
03112   }
03113 }
03114 
03115 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
03116   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
03117     return Error("Invalid record");
03118 
03119   SmallVector<uint64_t, 64> Record;
03120 
03121   std::string Triple;
03122   // Read all the records for this module.
03123   while (1) {
03124     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
03125 
03126     switch (Entry.Kind) {
03127     case BitstreamEntry::SubBlock: // Handled for us already.
03128     case BitstreamEntry::Error:
03129       return Error("Malformed block");
03130     case BitstreamEntry::EndBlock:
03131       return Triple;
03132     case BitstreamEntry::Record:
03133       // The interesting case.
03134       break;
03135     }
03136 
03137     // Read a record.
03138     switch (Stream.readRecord(Entry.ID, Record)) {
03139     default: break;  // Default behavior, ignore unknown content.
03140     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
03141       std::string S;
03142       if (ConvertToString(Record, 0, S))
03143         return Error("Invalid record");
03144       Triple = S;
03145       break;
03146     }
03147     }
03148     Record.clear();
03149   }
03150   llvm_unreachable("Exit infinite loop");
03151 }
03152 
03153 ErrorOr<std::string> BitcodeReader::parseTriple() {
03154   if (std::error_code EC = InitStream())
03155     return EC;
03156 
03157   // Sniff for the signature.
03158   if (Stream.Read(8) != 'B' ||
03159       Stream.Read(8) != 'C' ||
03160       Stream.Read(4) != 0x0 ||
03161       Stream.Read(4) != 0xC ||
03162       Stream.Read(4) != 0xE ||
03163       Stream.Read(4) != 0xD)
03164     return Error("Invalid bitcode signature");
03165 
03166   // We expect a number of well-defined blocks, though we don't necessarily
03167   // need to understand them all.
03168   while (1) {
03169     BitstreamEntry Entry = Stream.advance();
03170 
03171     switch (Entry.Kind) {
03172     case BitstreamEntry::Error:
03173       return Error("Malformed block");
03174     case BitstreamEntry::EndBlock:
03175       return std::error_code();
03176 
03177     case BitstreamEntry::SubBlock:
03178       if (Entry.ID == bitc::MODULE_BLOCK_ID)
03179         return parseModuleTriple();
03180 
03181       // Ignore other sub-blocks.
03182       if (Stream.SkipBlock())
03183         return Error("Malformed block");
03184       continue;
03185 
03186     case BitstreamEntry::Record:
03187       Stream.skipRecord(Entry.ID);
03188       continue;
03189     }
03190   }
03191 }
03192 
03193 /// ParseMetadataAttachment - Parse metadata attachments.
03194 std::error_code BitcodeReader::ParseMetadataAttachment() {
03195   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
03196     return Error("Invalid record");
03197 
03198   SmallVector<uint64_t, 64> Record;
03199   while (1) {
03200     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
03201 
03202     switch (Entry.Kind) {
03203     case BitstreamEntry::SubBlock: // Handled for us already.
03204     case BitstreamEntry::Error:
03205       return Error("Malformed block");
03206     case BitstreamEntry::EndBlock:
03207       return std::error_code();
03208     case BitstreamEntry::Record:
03209       // The interesting case.
03210       break;
03211     }
03212 
03213     // Read a metadata attachment record.
03214     Record.clear();
03215     switch (Stream.readRecord(Entry.ID, Record)) {
03216     default:  // Default behavior: ignore.
03217       break;
03218     case bitc::METADATA_ATTACHMENT: {
03219       unsigned RecordLength = Record.size();
03220       if (Record.empty() || (RecordLength - 1) % 2 == 1)
03221         return Error("Invalid record");
03222       Instruction *Inst = InstructionList[Record[0]];
03223       for (unsigned i = 1; i != RecordLength; i = i+2) {
03224         unsigned Kind = Record[i];
03225         DenseMap<unsigned, unsigned>::iterator I =
03226           MDKindMap.find(Kind);
03227         if (I == MDKindMap.end())
03228           return Error("Invalid ID");
03229         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
03230         if (isa<LocalAsMetadata>(Node))
03231           // Drop the attachment.  This used to be legal, but there's no
03232           // upgrade path.
03233           break;
03234         Inst->setMetadata(I->second, cast<MDNode>(Node));
03235         if (I->second == LLVMContext::MD_tbaa)
03236           InstsWithTBAATag.push_back(Inst);
03237       }
03238       break;
03239     }
03240     }
03241   }
03242 }
03243 
03244 /// ParseFunctionBody - Lazily parse the specified function body block.
03245 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
03246   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
03247     return Error("Invalid record");
03248 
03249   InstructionList.clear();
03250   unsigned ModuleValueListSize = ValueList.size();
03251   unsigned ModuleMDValueListSize = MDValueList.size();
03252 
03253   // Add all the function arguments to the value table.
03254   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
03255     ValueList.push_back(I);
03256 
03257   unsigned NextValueNo = ValueList.size();
03258   BasicBlock *CurBB = nullptr;
03259   unsigned CurBBNo = 0;
03260 
03261   DebugLoc LastLoc;
03262   auto getLastInstruction = [&]() -> Instruction * {
03263     if (CurBB && !CurBB->empty())
03264       return &CurBB->back();
03265     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
03266              !FunctionBBs[CurBBNo - 1]->empty())
03267       return &FunctionBBs[CurBBNo - 1]->back();
03268     return nullptr;
03269   };
03270 
03271   // Read all the records.
03272   SmallVector<uint64_t, 64> Record;
03273   while (1) {
03274     BitstreamEntry Entry = Stream.advance();
03275 
03276     switch (Entry.Kind) {
03277     case BitstreamEntry::Error:
03278       return Error("Malformed block");
03279     case BitstreamEntry::EndBlock:
03280       goto OutOfRecordLoop;
03281 
03282     case BitstreamEntry::SubBlock:
03283       switch (Entry.ID) {
03284       default:  // Skip unknown content.
03285         if (Stream.SkipBlock())
03286           return Error("Invalid record");
03287         break;
03288       case bitc::CONSTANTS_BLOCK_ID:
03289         if (std::error_code EC = ParseConstants())
03290           return EC;
03291         NextValueNo = ValueList.size();
03292         break;
03293       case bitc::VALUE_SYMTAB_BLOCK_ID:
03294         if (std::error_code EC = ParseValueSymbolTable())
03295           return EC;
03296         break;
03297       case bitc::METADATA_ATTACHMENT_ID:
03298         if (std::error_code EC = ParseMetadataAttachment())
03299           return EC;
03300         break;
03301       case bitc::METADATA_BLOCK_ID:
03302         if (std::error_code EC = ParseMetadata())
03303           return EC;
03304         break;
03305       case bitc::USELIST_BLOCK_ID:
03306         if (std::error_code EC = ParseUseLists())
03307           return EC;
03308         break;
03309       }
03310       continue;
03311 
03312     case BitstreamEntry::Record:
03313       // The interesting case.
03314       break;
03315     }
03316 
03317     // Read a record.
03318     Record.clear();
03319     Instruction *I = nullptr;
03320     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
03321     switch (BitCode) {
03322     default: // Default behavior: reject
03323       return Error("Invalid value");
03324     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
03325       if (Record.size() < 1 || Record[0] == 0)
03326         return Error("Invalid record");
03327       // Create all the basic blocks for the function.
03328       FunctionBBs.resize(Record[0]);
03329 
03330       // See if anything took the address of blocks in this function.
03331       auto BBFRI = BasicBlockFwdRefs.find(F);
03332       if (BBFRI == BasicBlockFwdRefs.end()) {
03333         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
03334           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
03335       } else {
03336         auto &BBRefs = BBFRI->second;
03337         // Check for invalid basic block references.
03338         if (BBRefs.size() > FunctionBBs.size())
03339           return Error("Invalid ID");
03340         assert(!BBRefs.empty() && "Unexpected empty array");
03341         assert(!BBRefs.front() && "Invalid reference to entry block");
03342         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
03343              ++I)
03344           if (I < RE && BBRefs[I]) {
03345             BBRefs[I]->insertInto(F);
03346             FunctionBBs[I] = BBRefs[I];
03347           } else {
03348             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
03349           }
03350 
03351         // Erase from the table.
03352         BasicBlockFwdRefs.erase(BBFRI);
03353       }
03354 
03355       CurBB = FunctionBBs[0];
03356       continue;
03357     }
03358 
03359     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
03360       // This record indicates that the last instruction is at the same
03361       // location as the previous instruction with a location.
03362       I = getLastInstruction();
03363 
03364       if (!I)
03365         return Error("Invalid record");
03366       I->setDebugLoc(LastLoc);
03367       I = nullptr;
03368       continue;
03369 
03370     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
03371       I = getLastInstruction();
03372       if (!I || Record.size() < 4)
03373         return Error("Invalid record");
03374 
03375       unsigned Line = Record[0], Col = Record[1];
03376       unsigned ScopeID = Record[2], IAID = Record[3];
03377 
03378       MDNode *Scope = nullptr, *IA = nullptr;
03379       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
03380       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
03381       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
03382       I->setDebugLoc(LastLoc);
03383       I = nullptr;
03384       continue;
03385     }
03386 
03387     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
03388       unsigned OpNum = 0;
03389       Value *LHS, *RHS;
03390       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
03391           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
03392           OpNum+1 > Record.size())
03393         return Error("Invalid record");
03394 
03395       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
03396       if (Opc == -1)
03397         return Error("Invalid record");
03398       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
03399       InstructionList.push_back(I);
03400       if (OpNum < Record.size()) {
03401         if (Opc == Instruction::Add ||
03402             Opc == Instruction::Sub ||
03403             Opc == Instruction::Mul ||
03404             Opc == Instruction::Shl) {
03405           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
03406             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
03407           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
03408             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
03409         } else if (Opc == Instruction::SDiv ||
03410                    Opc == Instruction::UDiv ||
03411                    Opc == Instruction::LShr ||
03412                    Opc == Instruction::AShr) {
03413           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
03414             cast<BinaryOperator>(I)->setIsExact(true);
03415         } else if (isa<FPMathOperator>(I)) {
03416           FastMathFlags FMF;
03417           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
03418             FMF.setUnsafeAlgebra();
03419           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
03420             FMF.setNoNaNs();
03421           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
03422             FMF.setNoInfs();
03423           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
03424             FMF.setNoSignedZeros();
03425           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
03426             FMF.setAllowReciprocal();
03427           if (FMF.any())
03428             I->setFastMathFlags(FMF);
03429         }
03430 
03431       }
03432       break;
03433     }
03434     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
03435       unsigned OpNum = 0;
03436       Value *Op;
03437       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03438           OpNum+2 != Record.size())
03439         return Error("Invalid record");
03440 
03441       Type *ResTy = getTypeByID(Record[OpNum]);
03442       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
03443       if (Opc == -1 || !ResTy)
03444         return Error("Invalid record");
03445       Instruction *Temp = nullptr;
03446       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
03447         if (Temp) {
03448           InstructionList.push_back(Temp);
03449           CurBB->getInstList().push_back(Temp);
03450         }
03451       } else {
03452         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
03453       }
03454       InstructionList.push_back(I);
03455       break;
03456     }
03457     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
03458     case bitc::FUNC_CODE_INST_GEP_OLD:
03459     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
03460       unsigned OpNum = 0;
03461 
03462       Type *Ty;
03463       bool InBounds;
03464 
03465       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
03466         InBounds = Record[OpNum++];
03467         Ty = getTypeByID(Record[OpNum++]);
03468       } else {
03469         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
03470         Ty = nullptr;
03471       }
03472 
03473       Value *BasePtr;
03474       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
03475         return Error("Invalid record");
03476 
03477       if (Ty &&
03478           Ty !=
03479               cast<SequentialType>(BasePtr->getType()->getScalarType())
03480                   ->getElementType())
03481         return Error(
03482             "Explicit gep type does not match pointee type of pointer operand");
03483 
03484       SmallVector<Value*, 16> GEPIdx;
03485       while (OpNum != Record.size()) {
03486         Value *Op;
03487         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
03488           return Error("Invalid record");
03489         GEPIdx.push_back(Op);
03490       }
03491 
03492       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
03493 
03494       InstructionList.push_back(I);
03495       if (InBounds)
03496         cast<GetElementPtrInst>(I)->setIsInBounds(true);
03497       break;
03498     }
03499 
03500     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
03501                                        // EXTRACTVAL: [opty, opval, n x indices]
03502       unsigned OpNum = 0;
03503       Value *Agg;
03504       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
03505         return Error("Invalid record");
03506 
03507       SmallVector<unsigned, 4> EXTRACTVALIdx;
03508       Type *CurTy = Agg->getType();
03509       for (unsigned RecSize = Record.size();
03510            OpNum != RecSize; ++OpNum) {
03511         bool IsArray = CurTy->isArrayTy();
03512         bool IsStruct = CurTy->isStructTy();
03513         uint64_t Index = Record[OpNum];
03514 
03515         if (!IsStruct && !IsArray)
03516           return Error("EXTRACTVAL: Invalid type");
03517         if ((unsigned)Index != Index)
03518           return Error("Invalid value");
03519         if (IsStruct && Index >= CurTy->subtypes().size())
03520           return Error("EXTRACTVAL: Invalid struct index");
03521         if (IsArray && Index >= CurTy->getArrayNumElements())
03522           return Error("EXTRACTVAL: Invalid array index");
03523         EXTRACTVALIdx.push_back((unsigned)Index);
03524 
03525         if (IsStruct)
03526           CurTy = CurTy->subtypes()[Index];
03527         else
03528           CurTy = CurTy->subtypes()[0];
03529       }
03530 
03531       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
03532       InstructionList.push_back(I);
03533       break;
03534     }
03535 
03536     case bitc::FUNC_CODE_INST_INSERTVAL: {
03537                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
03538       unsigned OpNum = 0;
03539       Value *Agg;
03540       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
03541         return Error("Invalid record");
03542       Value *Val;
03543       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
03544         return Error("Invalid record");
03545 
03546       SmallVector<unsigned, 4> INSERTVALIdx;
03547       Type *CurTy = Agg->getType();
03548       for (unsigned RecSize = Record.size();
03549            OpNum != RecSize; ++OpNum) {
03550         bool IsArray = CurTy->isArrayTy();
03551         bool IsStruct = CurTy->isStructTy();
03552         uint64_t Index = Record[OpNum];
03553 
03554         if (!IsStruct && !IsArray)
03555           return Error("INSERTVAL: Invalid type");
03556         if (!CurTy->isStructTy() && !CurTy->isArrayTy())
03557           return Error("Invalid type");
03558         if ((unsigned)Index != Index)
03559           return Error("Invalid value");
03560         if (IsStruct && Index >= CurTy->subtypes().size())
03561           return Error("INSERTVAL: Invalid struct index");
03562         if (IsArray && Index >= CurTy->getArrayNumElements())
03563           return Error("INSERTVAL: Invalid array index");
03564 
03565         INSERTVALIdx.push_back((unsigned)Index);
03566         if (IsStruct)
03567           CurTy = CurTy->subtypes()[Index];
03568         else
03569           CurTy = CurTy->subtypes()[0];
03570       }
03571 
03572       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
03573       InstructionList.push_back(I);
03574       break;
03575     }
03576 
03577     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
03578       // obsolete form of select
03579       // handles select i1 ... in old bitcode
03580       unsigned OpNum = 0;
03581       Value *TrueVal, *FalseVal, *Cond;
03582       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
03583           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
03584           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
03585         return Error("Invalid record");
03586 
03587       I = SelectInst::Create(Cond, TrueVal, FalseVal);
03588       InstructionList.push_back(I);
03589       break;
03590     }
03591 
03592     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
03593       // new form of select
03594       // handles select i1 or select [N x i1]
03595       unsigned OpNum = 0;
03596       Value *TrueVal, *FalseVal, *Cond;
03597       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
03598           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
03599           getValueTypePair(Record, OpNum, NextValueNo, Cond))
03600         return Error("Invalid record");
03601 
03602       // select condition can be either i1 or [N x i1]
03603       if (VectorType* vector_type =
03604           dyn_cast<VectorType>(Cond->getType())) {
03605         // expect <n x i1>
03606         if (vector_type->getElementType() != Type::getInt1Ty(Context))
03607           return Error("Invalid type for value");
03608       } else {
03609         // expect i1
03610         if (Cond->getType() != Type::getInt1Ty(Context))
03611           return Error("Invalid type for value");
03612       }
03613 
03614       I = SelectInst::Create(Cond, TrueVal, FalseVal);
03615       InstructionList.push_back(I);
03616       break;
03617     }
03618 
03619     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
03620       unsigned OpNum = 0;
03621       Value *Vec, *Idx;
03622       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
03623           getValueTypePair(Record, OpNum, NextValueNo, Idx))
03624         return Error("Invalid record");
03625       I = ExtractElementInst::Create(Vec, Idx);
03626       InstructionList.push_back(I);
03627       break;
03628     }
03629 
03630     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
03631       unsigned OpNum = 0;
03632       Value *Vec, *Elt, *Idx;
03633       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
03634           popValue(Record, OpNum, NextValueNo,
03635                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
03636           getValueTypePair(Record, OpNum, NextValueNo, Idx))
03637         return Error("Invalid record");
03638       I = InsertElementInst::Create(Vec, Elt, Idx);
03639       InstructionList.push_back(I);
03640       break;
03641     }
03642 
03643     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
03644       unsigned OpNum = 0;
03645       Value *Vec1, *Vec2, *Mask;
03646       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
03647           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
03648         return Error("Invalid record");
03649 
03650       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
03651         return Error("Invalid record");
03652       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
03653       InstructionList.push_back(I);
03654       break;
03655     }
03656 
03657     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
03658       // Old form of ICmp/FCmp returning bool
03659       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
03660       // both legal on vectors but had different behaviour.
03661     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
03662       // FCmp/ICmp returning bool or vector of bool
03663 
03664       unsigned OpNum = 0;
03665       Value *LHS, *RHS;
03666       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
03667           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
03668           OpNum+1 != Record.size())
03669         return Error("Invalid record");
03670 
03671       if (LHS->getType()->isFPOrFPVectorTy())
03672         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
03673       else
03674         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
03675       InstructionList.push_back(I);
03676       break;
03677     }
03678 
03679     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
03680       {
03681         unsigned Size = Record.size();
03682         if (Size == 0) {
03683           I = ReturnInst::Create(Context);
03684           InstructionList.push_back(I);
03685           break;
03686         }
03687 
03688         unsigned OpNum = 0;
03689         Value *Op = nullptr;
03690         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
03691           return Error("Invalid record");
03692         if (OpNum != Record.size())
03693           return Error("Invalid record");
03694 
03695         I = ReturnInst::Create(Context, Op);
03696         InstructionList.push_back(I);
03697         break;
03698       }
03699     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
03700       if (Record.size() != 1 && Record.size() != 3)
03701         return Error("Invalid record");
03702       BasicBlock *TrueDest = getBasicBlock(Record[0]);
03703       if (!TrueDest)
03704         return Error("Invalid record");
03705 
03706       if (Record.size() == 1) {
03707         I = BranchInst::Create(TrueDest);
03708         InstructionList.push_back(I);
03709       }
03710       else {
03711         BasicBlock *FalseDest = getBasicBlock(Record[1]);
03712         Value *Cond = getValue(Record, 2, NextValueNo,
03713                                Type::getInt1Ty(Context));
03714         if (!FalseDest || !Cond)
03715           return Error("Invalid record");
03716         I = BranchInst::Create(TrueDest, FalseDest, Cond);
03717         InstructionList.push_back(I);
03718       }
03719       break;
03720     }
03721     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
03722       // Check magic
03723       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
03724         // "New" SwitchInst format with case ranges. The changes to write this
03725         // format were reverted but we still recognize bitcode that uses it.
03726         // Hopefully someday we will have support for case ranges and can use
03727         // this format again.
03728 
03729         Type *OpTy = getTypeByID(Record[1]);
03730         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
03731 
03732         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
03733         BasicBlock *Default = getBasicBlock(Record[3]);
03734         if (!OpTy || !Cond || !Default)
03735           return Error("Invalid record");
03736 
03737         unsigned NumCases = Record[4];
03738 
03739         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
03740         InstructionList.push_back(SI);
03741 
03742         unsigned CurIdx = 5;
03743         for (unsigned i = 0; i != NumCases; ++i) {
03744           SmallVector<ConstantInt*, 1> CaseVals;
03745           unsigned NumItems = Record[CurIdx++];
03746           for (unsigned ci = 0; ci != NumItems; ++ci) {
03747             bool isSingleNumber = Record[CurIdx++];
03748 
03749             APInt Low;
03750             unsigned ActiveWords = 1;
03751             if (ValueBitWidth > 64)
03752               ActiveWords = Record[CurIdx++];
03753             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
03754                                 ValueBitWidth);
03755             CurIdx += ActiveWords;
03756 
03757             if (!isSingleNumber) {
03758               ActiveWords = 1;
03759               if (ValueBitWidth > 64)
03760                 ActiveWords = Record[CurIdx++];
03761               APInt High =
03762                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
03763                                 ValueBitWidth);
03764               CurIdx += ActiveWords;
03765 
03766               // FIXME: It is not clear whether values in the range should be
03767               // compared as signed or unsigned values. The partially
03768               // implemented changes that used this format in the past used
03769               // unsigned comparisons.
03770               for ( ; Low.ule(High); ++Low)
03771                 CaseVals.push_back(ConstantInt::get(Context, Low));
03772             } else
03773               CaseVals.push_back(ConstantInt::get(Context, Low));
03774           }
03775           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
03776           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
03777                  cve = CaseVals.end(); cvi != cve; ++cvi)
03778             SI->addCase(*cvi, DestBB);
03779         }
03780         I = SI;
03781         break;
03782       }
03783 
03784       // Old SwitchInst format without case ranges.
03785 
03786       if (Record.size() < 3 || (Record.size() & 1) == 0)
03787         return Error("Invalid record");
03788       Type *OpTy = getTypeByID(Record[0]);
03789       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
03790       BasicBlock *Default = getBasicBlock(Record[2]);
03791       if (!OpTy || !Cond || !Default)
03792         return Error("Invalid record");
03793       unsigned NumCases = (Record.size()-3)/2;
03794       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
03795       InstructionList.push_back(SI);
03796       for (unsigned i = 0, e = NumCases; i != e; ++i) {
03797         ConstantInt *CaseVal =
03798           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
03799         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
03800         if (!CaseVal || !DestBB) {
03801           delete SI;
03802           return Error("Invalid record");
03803         }
03804         SI->addCase(CaseVal, DestBB);
03805       }
03806       I = SI;
03807       break;
03808     }
03809     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
03810       if (Record.size() < 2)
03811         return Error("Invalid record");
03812       Type *OpTy = getTypeByID(Record[0]);
03813       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
03814       if (!OpTy || !Address)
03815         return Error("Invalid record");
03816       unsigned NumDests = Record.size()-2;
03817       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
03818       InstructionList.push_back(IBI);
03819       for (unsigned i = 0, e = NumDests; i != e; ++i) {
03820         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
03821           IBI->addDestination(DestBB);
03822         } else {
03823           delete IBI;
03824           return Error("Invalid record");
03825         }
03826       }
03827       I = IBI;
03828       break;
03829     }
03830 
03831     case bitc::FUNC_CODE_INST_INVOKE: {
03832       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
03833       if (Record.size() < 4)
03834         return Error("Invalid record");
03835       AttributeSet PAL = getAttributes(Record[0]);
03836       unsigned CCInfo = Record[1];
03837       BasicBlock *NormalBB = getBasicBlock(Record[2]);
03838       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
03839 
03840       unsigned OpNum = 4;
03841       Value *Callee;
03842       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
03843         return Error("Invalid record");
03844 
03845       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
03846       FunctionType *FTy = !CalleeTy ? nullptr :
03847         dyn_cast<FunctionType>(CalleeTy->getElementType());
03848 
03849       // Check that the right number of fixed parameters are here.
03850       if (!FTy || !NormalBB || !UnwindBB ||
03851           Record.size() < OpNum+FTy->getNumParams())
03852         return Error("Invalid record");
03853 
03854       SmallVector<Value*, 16> Ops;
03855       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
03856         Ops.push_back(getValue(Record, OpNum, NextValueNo,
03857                                FTy->getParamType(i)));
03858         if (!Ops.back())
03859           return Error("Invalid record");
03860       }
03861 
03862       if (!FTy->isVarArg()) {
03863         if (Record.size() != OpNum)
03864           return Error("Invalid record");
03865       } else {
03866         // Read type/value pairs for varargs params.
03867         while (OpNum != Record.size()) {
03868           Value *Op;
03869           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
03870             return Error("Invalid record");
03871           Ops.push_back(Op);
03872         }
03873       }
03874 
03875       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
03876       InstructionList.push_back(I);
03877       cast<InvokeInst>(I)->setCallingConv(
03878         static_cast<CallingConv::ID>(CCInfo));
03879       cast<InvokeInst>(I)->setAttributes(PAL);
03880       break;
03881     }
03882     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
03883       unsigned Idx = 0;
03884       Value *Val = nullptr;
03885       if (getValueTypePair(Record, Idx, NextValueNo, Val))
03886         return Error("Invalid record");
03887       I = ResumeInst::Create(Val);
03888       InstructionList.push_back(I);
03889       break;
03890     }
03891     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
03892       I = new UnreachableInst(Context);
03893       InstructionList.push_back(I);
03894       break;
03895     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
03896       if (Record.size() < 1 || ((Record.size()-1)&1))
03897         return Error("Invalid record");
03898       Type *Ty = getTypeByID(Record[0]);
03899       if (!Ty)
03900         return Error("Invalid record");
03901 
03902       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
03903       InstructionList.push_back(PN);
03904 
03905       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
03906         Value *V;
03907         // With the new function encoding, it is possible that operands have
03908         // negative IDs (for forward references).  Use a signed VBR
03909         // representation to keep the encoding small.
03910         if (UseRelativeIDs)
03911           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
03912         else
03913           V = getValue(Record, 1+i, NextValueNo, Ty);
03914         BasicBlock *BB = getBasicBlock(Record[2+i]);
03915         if (!V || !BB)
03916           return Error("Invalid record");
03917         PN->addIncoming(V, BB);
03918       }
03919       I = PN;
03920       break;
03921     }
03922 
03923     case bitc::FUNC_CODE_INST_LANDINGPAD: {
03924       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
03925       unsigned Idx = 0;
03926       if (Record.size() < 4)
03927         return Error("Invalid record");
03928       Type *Ty = getTypeByID(Record[Idx++]);
03929       if (!Ty)
03930         return Error("Invalid record");
03931       Value *PersFn = nullptr;
03932       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
03933         return Error("Invalid record");
03934 
03935       bool IsCleanup = !!Record[Idx++];
03936       unsigned NumClauses = Record[Idx++];
03937       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
03938       LP->setCleanup(IsCleanup);
03939       for (unsigned J = 0; J != NumClauses; ++J) {
03940         LandingPadInst::ClauseType CT =
03941           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
03942         Value *Val;
03943 
03944         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
03945           delete LP;
03946           return Error("Invalid record");
03947         }
03948 
03949         assert((CT != LandingPadInst::Catch ||
03950                 !isa<ArrayType>(Val->getType())) &&
03951                "Catch clause has a invalid type!");
03952         assert((CT != LandingPadInst::Filter ||
03953                 isa<ArrayType>(Val->getType())) &&
03954                "Filter clause has invalid type!");
03955         LP->addClause(cast<Constant>(Val));
03956       }
03957 
03958       I = LP;
03959       InstructionList.push_back(I);
03960       break;
03961     }
03962 
03963     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
03964       if (Record.size() != 4)
03965         return Error("Invalid record");
03966       PointerType *Ty =
03967         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
03968       Type *OpTy = getTypeByID(Record[1]);
03969       Value *Size = getFnValueByID(Record[2], OpTy);
03970       uint64_t AlignRecord = Record[3];
03971       const uint64_t InAllocaMask = uint64_t(1) << 5;
03972       bool InAlloca = AlignRecord & InAllocaMask;
03973       unsigned Align;
03974       if (std::error_code EC =
03975           parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
03976         return EC;
03977       }
03978       if (!Ty || !Size)
03979         return Error("Invalid record");
03980       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
03981       AI->setUsedWithInAlloca(InAlloca);
03982       I = AI;
03983       InstructionList.push_back(I);
03984       break;
03985     }
03986     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
03987       unsigned OpNum = 0;
03988       Value *Op;
03989       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03990           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
03991         return Error("Invalid record");
03992 
03993       Type *Ty = nullptr;
03994       if (OpNum + 3 == Record.size())
03995         Ty = getTypeByID(Record[OpNum++]);
03996 
03997       unsigned Align;
03998       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
03999         return EC;
04000       I = new LoadInst(Op, "", Record[OpNum+1], Align);
04001 
04002       if (Ty && Ty != I->getType())
04003         return Error("Explicit load type does not match pointee type of "
04004                      "pointer operand");
04005 
04006       InstructionList.push_back(I);
04007       break;
04008     }
04009     case bitc::FUNC_CODE_INST_LOADATOMIC: {
04010        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
04011       unsigned OpNum = 0;
04012       Value *Op;
04013       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
04014           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
04015         return Error("Invalid record");
04016 
04017       Type *Ty = nullptr;
04018       if (OpNum + 5 == Record.size())
04019         Ty = getTypeByID(Record[OpNum++]);
04020 
04021       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
04022       if (Ordering == NotAtomic || Ordering == Release ||
04023           Ordering == AcquireRelease)
04024         return Error("Invalid record");
04025       if (Ordering != NotAtomic && Record[OpNum] == 0)
04026         return Error("Invalid record");
04027       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
04028 
04029       unsigned Align;
04030       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
04031         return EC;
04032       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
04033 
04034       (void)Ty;
04035       assert((!Ty || Ty == I->getType()) &&
04036              "Explicit type doesn't match pointee type of the first operand");
04037 
04038       InstructionList.push_back(I);
04039       break;
04040     }
04041     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
04042       unsigned OpNum = 0;
04043       Value *Val, *Ptr;
04044       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
04045           popValue(Record, OpNum, NextValueNo,
04046                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
04047           OpNum+2 != Record.size())
04048         return Error("Invalid record");
04049       unsigned Align;
04050       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
04051         return EC;
04052       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
04053       InstructionList.push_back(I);
04054       break;
04055     }
04056     case bitc::FUNC_CODE_INST_STOREATOMIC: {
04057       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
04058       unsigned OpNum = 0;
04059       Value *Val, *Ptr;
04060       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
04061           popValue(Record, OpNum, NextValueNo,
04062                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
04063           OpNum+4 != Record.size())
04064         return Error("Invalid record");
04065 
04066       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
04067       if (Ordering == NotAtomic || Ordering == Acquire ||
04068           Ordering == AcquireRelease)
04069         return Error("Invalid record");
04070       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
04071       if (Ordering != NotAtomic && Record[OpNum] == 0)
04072         return Error("Invalid record");
04073 
04074       unsigned Align;
04075       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
04076         return EC;
04077       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
04078       InstructionList.push_back(I);
04079       break;
04080     }
04081     case bitc::FUNC_CODE_INST_CMPXCHG: {
04082       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
04083       //          failureordering?, isweak?]
04084       unsigned OpNum = 0;
04085       Value *Ptr, *Cmp, *New;
04086       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
04087           popValue(Record, OpNum, NextValueNo,
04088                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
04089           popValue(Record, OpNum, NextValueNo,
04090                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
04091           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
04092         return Error("Invalid record");
04093       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
04094       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
04095         return Error("Invalid record");
04096       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
04097 
04098       AtomicOrdering FailureOrdering;
04099       if (Record.size() < 7)
04100         FailureOrdering =
04101             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
04102       else
04103         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
04104 
04105       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
04106                                 SynchScope);
04107       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
04108 
04109       if (Record.size() < 8) {
04110         // Before weak cmpxchgs existed, the instruction simply returned the
04111         // value loaded from memory, so bitcode files from that era will be
04112         // expecting the first component of a modern cmpxchg.
04113         CurBB->getInstList().push_back(I);
04114         I = ExtractValueInst::Create(I, 0);
04115       } else {
04116         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
04117       }
04118 
04119       InstructionList.push_back(I);
04120       break;
04121     }
04122     case bitc::FUNC_CODE_INST_ATOMICRMW: {
04123       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
04124       unsigned OpNum = 0;
04125       Value *Ptr, *Val;
04126       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
04127           popValue(Record, OpNum, NextValueNo,
04128                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
04129           OpNum+4 != Record.size())
04130         return Error("Invalid record");
04131       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
04132       if (Operation < AtomicRMWInst::FIRST_BINOP ||
04133           Operation > AtomicRMWInst::LAST_BINOP)
04134         return Error("Invalid record");
04135       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
04136       if (Ordering == NotAtomic || Ordering == Unordered)
04137         return Error("Invalid record");
04138       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
04139       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
04140       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
04141       InstructionList.push_back(I);
04142       break;
04143     }
04144     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
04145       if (2 != Record.size())
04146         return Error("Invalid record");
04147       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
04148       if (Ordering == NotAtomic || Ordering == Unordered ||
04149           Ordering == Monotonic)
04150         return Error("Invalid record");
04151       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
04152       I = new FenceInst(Context, Ordering, SynchScope);
04153       InstructionList.push_back(I);
04154       break;
04155     }
04156     case bitc::FUNC_CODE_INST_CALL: {
04157       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
04158       if (Record.size() < 3)
04159         return Error("Invalid record");
04160 
04161       AttributeSet PAL = getAttributes(Record[0]);
04162       unsigned CCInfo = Record[1];
04163 
04164       unsigned OpNum = 2;
04165       Value *Callee;
04166       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
04167         return Error("Invalid record");
04168 
04169       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
04170       FunctionType *FTy = nullptr;
04171       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
04172       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
04173         return Error("Invalid record");
04174 
04175       SmallVector<Value*, 16> Args;
04176       // Read the fixed params.
04177       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
04178         if (FTy->getParamType(i)->isLabelTy())
04179           Args.push_back(getBasicBlock(Record[OpNum]));
04180         else
04181           Args.push_back(getValue(Record, OpNum, NextValueNo,
04182                                   FTy->getParamType(i)));
04183         if (!Args.back())
04184           return Error("Invalid record");
04185       }
04186 
04187       // Read type/value pairs for varargs params.
04188       if (!FTy->isVarArg()) {
04189         if (OpNum != Record.size())
04190           return Error("Invalid record");
04191       } else {
04192         while (OpNum != Record.size()) {
04193           Value *Op;
04194           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
04195             return Error("Invalid record");
04196           Args.push_back(Op);
04197         }
04198       }
04199 
04200       I = CallInst::Create(Callee, Args);
04201       InstructionList.push_back(I);
04202       cast<CallInst>(I)->setCallingConv(
04203           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
04204       CallInst::TailCallKind TCK = CallInst::TCK_None;
04205       if (CCInfo & 1)
04206         TCK = CallInst::TCK_Tail;
04207       if (CCInfo & (1 << 14))
04208         TCK = CallInst::TCK_MustTail;
04209       cast<CallInst>(I)->setTailCallKind(TCK);
04210       cast<CallInst>(I)->setAttributes(PAL);
04211       break;
04212     }
04213     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
04214       if (Record.size() < 3)
04215         return Error("Invalid record");
04216       Type *OpTy = getTypeByID(Record[0]);
04217       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
04218       Type *ResTy = getTypeByID(Record[2]);
04219       if (!OpTy || !Op || !ResTy)
04220         return Error("Invalid record");
04221       I = new VAArgInst(Op, ResTy);
04222       InstructionList.push_back(I);
04223       break;
04224     }
04225     }
04226 
04227     // Add instruction to end of current BB.  If there is no current BB, reject
04228     // this file.
04229     if (!CurBB) {
04230       delete I;
04231       return Error("Invalid instruction with no BB");
04232     }
04233     CurBB->getInstList().push_back(I);
04234 
04235     // If this was a terminator instruction, move to the next block.
04236     if (isa<TerminatorInst>(I)) {
04237       ++CurBBNo;
04238       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
04239     }
04240 
04241     // Non-void values get registered in the value table for future use.
04242     if (I && !I->getType()->isVoidTy())
04243       ValueList.AssignValue(I, NextValueNo++);
04244   }
04245 
04246 OutOfRecordLoop:
04247 
04248   // Check the function list for unresolved values.
04249   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
04250     if (!A->getParent()) {
04251       // We found at least one unresolved value.  Nuke them all to avoid leaks.
04252       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
04253         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
04254           A->replaceAllUsesWith(UndefValue::get(A->getType()));
04255           delete A;
04256         }
04257       }
04258       return Error("Never resolved value found in function");
04259     }
04260   }
04261 
04262   // FIXME: Check for unresolved forward-declared metadata references
04263   // and clean up leaks.
04264 
04265   // Trim the value list down to the size it was before we parsed this function.
04266   ValueList.shrinkTo(ModuleValueListSize);
04267   MDValueList.shrinkTo(ModuleMDValueListSize);
04268   std::vector<BasicBlock*>().swap(FunctionBBs);
04269   return std::error_code();
04270 }
04271 
04272 /// Find the function body in the bitcode stream
04273 std::error_code BitcodeReader::FindFunctionInStream(
04274     Function *F,
04275     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
04276   while (DeferredFunctionInfoIterator->second == 0) {
04277     if (Stream.AtEndOfStream())
04278       return Error("Could not find function in stream");
04279     // ParseModule will parse the next body in the stream and set its
04280     // position in the DeferredFunctionInfo map.
04281     if (std::error_code EC = ParseModule(true))
04282       return EC;
04283   }
04284   return std::error_code();
04285 }
04286 
04287 //===----------------------------------------------------------------------===//
04288 // GVMaterializer implementation
04289 //===----------------------------------------------------------------------===//
04290 
04291 void BitcodeReader::releaseBuffer() { Buffer.release(); }
04292 
04293 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
04294   if (std::error_code EC = materializeMetadata())
04295     return EC;
04296 
04297   Function *F = dyn_cast<Function>(GV);
04298   // If it's not a function or is already material, ignore the request.
04299   if (!F || !F->isMaterializable())
04300     return std::error_code();
04301 
04302   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
04303   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
04304   // If its position is recorded as 0, its body is somewhere in the stream
04305   // but we haven't seen it yet.
04306   if (DFII->second == 0 && LazyStreamer)
04307     if (std::error_code EC = FindFunctionInStream(F, DFII))
04308       return EC;
04309 
04310   // Move the bit stream to the saved position of the deferred function body.
04311   Stream.JumpToBit(DFII->second);
04312 
04313   if (std::error_code EC = ParseFunctionBody(F))
04314     return EC;
04315   F->setIsMaterializable(false);
04316 
04317   if (StripDebugInfo)
04318     stripDebugInfo(*F);
04319 
04320   // Upgrade any old intrinsic calls in the function.
04321   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
04322        E = UpgradedIntrinsics.end(); I != E; ++I) {
04323     if (I->first != I->second) {
04324       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
04325            UI != UE;) {
04326         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
04327           UpgradeIntrinsicCall(CI, I->second);
04328       }
04329     }
04330   }
04331 
04332   // Bring in any functions that this function forward-referenced via
04333   // blockaddresses.
04334   return materializeForwardReferencedFunctions();
04335 }
04336 
04337 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
04338   const Function *F = dyn_cast<Function>(GV);
04339   if (!F || F->isDeclaration())
04340     return false;
04341 
04342   // Dematerializing F would leave dangling references that wouldn't be
04343   // reconnected on re-materialization.
04344   if (BlockAddressesTaken.count(F))
04345     return false;
04346 
04347   return DeferredFunctionInfo.count(const_cast<Function*>(F));
04348 }
04349 
04350 void BitcodeReader::Dematerialize(GlobalValue *GV) {
04351   Function *F = dyn_cast<Function>(GV);
04352   // If this function isn't dematerializable, this is a noop.
04353   if (!F || !isDematerializable(F))
04354     return;
04355 
04356   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
04357 
04358   // Just forget the function body, we can remat it later.
04359   F->dropAllReferences();
04360   F->setIsMaterializable(true);
04361 }
04362 
04363 std::error_code BitcodeReader::MaterializeModule(Module *M) {
04364   assert(M == TheModule &&
04365          "Can only Materialize the Module this BitcodeReader is attached to.");
04366 
04367   if (std::error_code EC = materializeMetadata())
04368     return EC;
04369 
04370   // Promise to materialize all forward references.
04371   WillMaterializeAllForwardRefs = true;
04372 
04373   // Iterate over the module, deserializing any functions that are still on
04374   // disk.
04375   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
04376        F != E; ++F) {
04377     if (std::error_code EC = materialize(F))
04378       return EC;
04379   }
04380   // At this point, if there are any function bodies, the current bit is
04381   // pointing to the END_BLOCK record after them. Now make sure the rest
04382   // of the bits in the module have been read.
04383   if (NextUnreadBit)
04384     ParseModule(true);
04385 
04386   // Check that all block address forward references got resolved (as we
04387   // promised above).
04388   if (!BasicBlockFwdRefs.empty())
04389     return Error("Never resolved function from blockaddress");
04390 
04391   // Upgrade any intrinsic calls that slipped through (should not happen!) and
04392   // delete the old functions to clean up. We can't do this unless the entire
04393   // module is materialized because there could always be another function body
04394   // with calls to the old function.
04395   for (std::vector<std::pair<Function*, Function*> >::iterator I =
04396        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
04397     if (I->first != I->second) {
04398       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
04399            UI != UE;) {
04400         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
04401           UpgradeIntrinsicCall(CI, I->second);
04402       }
04403       if (!I->first->use_empty())
04404         I->first->replaceAllUsesWith(I->second);
04405       I->first->eraseFromParent();
04406     }
04407   }
04408   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
04409 
04410   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
04411     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
04412 
04413   UpgradeDebugInfo(*M);
04414   return std::error_code();
04415 }
04416 
04417 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
04418   return IdentifiedStructTypes;
04419 }
04420 
04421 std::error_code BitcodeReader::InitStream() {
04422   if (LazyStreamer)
04423     return InitLazyStream();
04424   return InitStreamFromBuffer();
04425 }
04426 
04427 std::error_code BitcodeReader::InitStreamFromBuffer() {
04428   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
04429   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
04430 
04431   if (Buffer->getBufferSize() & 3)
04432     return Error("Invalid bitcode signature");
04433 
04434   // If we have a wrapper header, parse it and ignore the non-bc file contents.
04435   // The magic number is 0x0B17C0DE stored in little endian.
04436   if (isBitcodeWrapper(BufPtr, BufEnd))
04437     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
04438       return Error("Invalid bitcode wrapper header");
04439 
04440   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
04441   Stream.init(&*StreamFile);
04442 
04443   return std::error_code();
04444 }
04445 
04446 std::error_code BitcodeReader::InitLazyStream() {
04447   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
04448   // see it.
04449   auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
04450   StreamingMemoryObject &Bytes = *OwnedBytes;
04451   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
04452   Stream.init(&*StreamFile);
04453 
04454   unsigned char buf[16];
04455   if (Bytes.readBytes(buf, 16, 0) != 16)
04456     return Error("Invalid bitcode signature");
04457 
04458   if (!isBitcode(buf, buf + 16))
04459     return Error("Invalid bitcode signature");
04460 
04461   if (isBitcodeWrapper(buf, buf + 4)) {
04462     const unsigned char *bitcodeStart = buf;
04463     const unsigned char *bitcodeEnd = buf + 16;
04464     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
04465     Bytes.dropLeadingBytes(bitcodeStart - buf);
04466     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
04467   }
04468   return std::error_code();
04469 }
04470 
04471 namespace {
04472 class BitcodeErrorCategoryType : public std::error_category {
04473   const char *name() const LLVM_NOEXCEPT override {
04474     return "llvm.bitcode";
04475   }
04476   std::string message(int IE) const override {
04477     BitcodeError E = static_cast<BitcodeError>(IE);
04478     switch (E) {
04479     case BitcodeError::InvalidBitcodeSignature:
04480       return "Invalid bitcode signature";
04481     case BitcodeError::CorruptedBitcode:
04482       return "Corrupted bitcode";
04483     }
04484     llvm_unreachable("Unknown error type!");
04485   }
04486 };
04487 }
04488 
04489 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
04490 
04491 const std::error_category &llvm::BitcodeErrorCategory() {
04492   return *ErrorCategory;
04493 }
04494 
04495 //===----------------------------------------------------------------------===//
04496 // External interface
04497 //===----------------------------------------------------------------------===//
04498 
04499 /// \brief Get a lazy one-at-time loading module from bitcode.
04500 ///
04501 /// This isn't always used in a lazy context.  In particular, it's also used by
04502 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
04503 /// in forward-referenced functions from block address references.
04504 ///
04505 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
04506 /// materialize everything -- in particular, if this isn't truly lazy.
04507 static ErrorOr<Module *>
04508 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
04509                          LLVMContext &Context, bool WillMaterializeAll,
04510                          DiagnosticHandlerFunction DiagnosticHandler,
04511                          bool ShouldLazyLoadMetadata = false) {
04512   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
04513   BitcodeReader *R =
04514       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
04515   M->setMaterializer(R);
04516 
04517   auto cleanupOnError = [&](std::error_code EC) {
04518     R->releaseBuffer(); // Never take ownership on error.
04519     delete M;  // Also deletes R.
04520     return EC;
04521   };
04522 
04523   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
04524   if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
04525     return cleanupOnError(EC);
04526 
04527   if (!WillMaterializeAll)
04528     // Resolve forward references from blockaddresses.
04529     if (std::error_code EC = R->materializeForwardReferencedFunctions())
04530       return cleanupOnError(EC);
04531 
04532   Buffer.release(); // The BitcodeReader owns it now.
04533   return M;
04534 }
04535 
04536 ErrorOr<Module *>
04537 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
04538                            LLVMContext &Context,
04539                            DiagnosticHandlerFunction DiagnosticHandler,
04540                            bool ShouldLazyLoadMetadata) {
04541   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
04542                                   DiagnosticHandler, ShouldLazyLoadMetadata);
04543 }
04544 
04545 ErrorOr<std::unique_ptr<Module>>
04546 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
04547                                LLVMContext &Context,
04548                                DiagnosticHandlerFunction DiagnosticHandler) {
04549   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
04550   BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
04551   M->setMaterializer(R);
04552   if (std::error_code EC = R->ParseBitcodeInto(M.get()))
04553     return EC;
04554   return std::move(M);
04555 }
04556 
04557 ErrorOr<Module *>
04558 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
04559                        DiagnosticHandlerFunction DiagnosticHandler) {
04560   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
04561   ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
04562       std::move(Buf), Context, true, DiagnosticHandler);
04563   if (!ModuleOrErr)
04564     return ModuleOrErr;
04565   Module *M = ModuleOrErr.get();
04566   // Read in the entire module, and destroy the BitcodeReader.
04567   if (std::error_code EC = M->materializeAllPermanently()) {
04568     delete M;
04569     return EC;
04570   }
04571 
04572   // TODO: Restore the use-lists to the in-memory state when the bitcode was
04573   // written.  We must defer until the Module has been fully materialized.
04574 
04575   return M;
04576 }
04577 
04578 std::string
04579 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
04580                              DiagnosticHandlerFunction DiagnosticHandler) {
04581   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
04582   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
04583                                             DiagnosticHandler);
04584   ErrorOr<std::string> Triple = R->parseTriple();
04585   if (Triple.getError())
04586     return "";
04587   return Triple.get();
04588 }