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