1f22ef01cSRoman Divacky //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky 10f22ef01cSRoman Divacky #include "llvm/Bitcode/ReaderWriter.h" 11ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h" 12f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h" 13f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h" 14ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h" 15ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h" 16f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h" 1791bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h" 18139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 19ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h" 20ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 21139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 2239d628a0SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h" 23ff0cc061SDimitry Andric #include "llvm/IR/GVMaterializer.h" 24139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h" 25139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h" 26f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h" 27139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 28139f7f9bSDimitry Andric #include "llvm/IR/OperandTraits.h" 29139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 307d523365SDimitry Andric #include "llvm/IR/FunctionInfo.h" 31ff0cc061SDimitry Andric #include "llvm/IR/ValueHandle.h" 32dff0c46cSDimitry Andric #include "llvm/Support/DataStream.h" 3339d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h" 34f22ef01cSRoman Divacky #include "llvm/Support/MathExtras.h" 35f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h" 36f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h" 37ff0cc061SDimitry Andric #include <deque> 38f22ef01cSRoman Divacky using namespace llvm; 39f22ef01cSRoman Divacky 40ff0cc061SDimitry Andric namespace { 417ae0e2c9SDimitry Andric enum { 427ae0e2c9SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 437ae0e2c9SDimitry Andric }; 447ae0e2c9SDimitry Andric 45ff0cc061SDimitry Andric class BitcodeReaderValueList { 46ff0cc061SDimitry Andric std::vector<WeakVH> ValuePtrs; 47ff0cc061SDimitry Andric 488f0fd8f6SDimitry Andric /// As we resolve forward-referenced constants, we add information about them 498f0fd8f6SDimitry Andric /// to this vector. This allows us to resolve them in bulk instead of 508f0fd8f6SDimitry Andric /// resolving each reference at a time. See the code in 51ff0cc061SDimitry Andric /// ResolveConstantForwardRefs for more information about this. 52ff0cc061SDimitry Andric /// 53ff0cc061SDimitry Andric /// The key of this vector is the placeholder constant, the value is the slot 54ff0cc061SDimitry Andric /// number that holds the resolved value. 55ff0cc061SDimitry Andric typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy; 56ff0cc061SDimitry Andric ResolveConstantsTy ResolveConstants; 57ff0cc061SDimitry Andric LLVMContext &Context; 58ff0cc061SDimitry Andric public: 59ff0cc061SDimitry Andric BitcodeReaderValueList(LLVMContext &C) : Context(C) {} 60ff0cc061SDimitry Andric ~BitcodeReaderValueList() { 61ff0cc061SDimitry Andric assert(ResolveConstants.empty() && "Constants not resolved?"); 62ff0cc061SDimitry Andric } 63ff0cc061SDimitry Andric 64ff0cc061SDimitry Andric // vector compatibility methods 65ff0cc061SDimitry Andric unsigned size() const { return ValuePtrs.size(); } 66ff0cc061SDimitry Andric void resize(unsigned N) { ValuePtrs.resize(N); } 6797bc6c73SDimitry Andric void push_back(Value *V) { ValuePtrs.emplace_back(V); } 68ff0cc061SDimitry Andric 69ff0cc061SDimitry Andric void clear() { 70ff0cc061SDimitry Andric assert(ResolveConstants.empty() && "Constants not resolved?"); 71ff0cc061SDimitry Andric ValuePtrs.clear(); 72ff0cc061SDimitry Andric } 73ff0cc061SDimitry Andric 74ff0cc061SDimitry Andric Value *operator[](unsigned i) const { 75ff0cc061SDimitry Andric assert(i < ValuePtrs.size()); 76ff0cc061SDimitry Andric return ValuePtrs[i]; 77ff0cc061SDimitry Andric } 78ff0cc061SDimitry Andric 79ff0cc061SDimitry Andric Value *back() const { return ValuePtrs.back(); } 80ff0cc061SDimitry Andric void pop_back() { ValuePtrs.pop_back(); } 81ff0cc061SDimitry Andric bool empty() const { return ValuePtrs.empty(); } 82ff0cc061SDimitry Andric void shrinkTo(unsigned N) { 83ff0cc061SDimitry Andric assert(N <= size() && "Invalid shrinkTo request!"); 84ff0cc061SDimitry Andric ValuePtrs.resize(N); 85ff0cc061SDimitry Andric } 86ff0cc061SDimitry Andric 87ff0cc061SDimitry Andric Constant *getConstantFwdRef(unsigned Idx, Type *Ty); 88ff0cc061SDimitry Andric Value *getValueFwdRef(unsigned Idx, Type *Ty); 89ff0cc061SDimitry Andric 908f0fd8f6SDimitry Andric void assignValue(Value *V, unsigned Idx); 91ff0cc061SDimitry Andric 928f0fd8f6SDimitry Andric /// Once all constants are read, this method bulk resolves any forward 938f0fd8f6SDimitry Andric /// references. 948f0fd8f6SDimitry Andric void resolveConstantForwardRefs(); 95ff0cc061SDimitry Andric }; 96ff0cc061SDimitry Andric 977d523365SDimitry Andric class BitcodeReaderMetadataList { 98ff0cc061SDimitry Andric unsigned NumFwdRefs; 99ff0cc061SDimitry Andric bool AnyFwdRefs; 100ff0cc061SDimitry Andric unsigned MinFwdRef; 101ff0cc061SDimitry Andric unsigned MaxFwdRef; 1027d523365SDimitry Andric std::vector<TrackingMDRef> MetadataPtrs; 103ff0cc061SDimitry Andric 104ff0cc061SDimitry Andric LLVMContext &Context; 105ff0cc061SDimitry Andric public: 1067d523365SDimitry Andric BitcodeReaderMetadataList(LLVMContext &C) 107ff0cc061SDimitry Andric : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {} 108ff0cc061SDimitry Andric 109ff0cc061SDimitry Andric // vector compatibility methods 1107d523365SDimitry Andric unsigned size() const { return MetadataPtrs.size(); } 1117d523365SDimitry Andric void resize(unsigned N) { MetadataPtrs.resize(N); } 1127d523365SDimitry Andric void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); } 1137d523365SDimitry Andric void clear() { MetadataPtrs.clear(); } 1147d523365SDimitry Andric Metadata *back() const { return MetadataPtrs.back(); } 1157d523365SDimitry Andric void pop_back() { MetadataPtrs.pop_back(); } 1167d523365SDimitry Andric bool empty() const { return MetadataPtrs.empty(); } 117ff0cc061SDimitry Andric 118ff0cc061SDimitry Andric Metadata *operator[](unsigned i) const { 1197d523365SDimitry Andric assert(i < MetadataPtrs.size()); 1207d523365SDimitry Andric return MetadataPtrs[i]; 121ff0cc061SDimitry Andric } 122ff0cc061SDimitry Andric 123ff0cc061SDimitry Andric void shrinkTo(unsigned N) { 124ff0cc061SDimitry Andric assert(N <= size() && "Invalid shrinkTo request!"); 1257d523365SDimitry Andric MetadataPtrs.resize(N); 126ff0cc061SDimitry Andric } 127ff0cc061SDimitry Andric 128ff0cc061SDimitry Andric Metadata *getValueFwdRef(unsigned Idx); 1298f0fd8f6SDimitry Andric void assignValue(Metadata *MD, unsigned Idx); 130ff0cc061SDimitry Andric void tryToResolveCycles(); 131ff0cc061SDimitry Andric }; 132ff0cc061SDimitry Andric 133ff0cc061SDimitry Andric class BitcodeReader : public GVMaterializer { 134ff0cc061SDimitry Andric LLVMContext &Context; 1358f0fd8f6SDimitry Andric Module *TheModule = nullptr; 136ff0cc061SDimitry Andric std::unique_ptr<MemoryBuffer> Buffer; 137ff0cc061SDimitry Andric std::unique_ptr<BitstreamReader> StreamFile; 138ff0cc061SDimitry Andric BitstreamCursor Stream; 1397d523365SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies. 1408f0fd8f6SDimitry Andric uint64_t NextUnreadBit = 0; 1417d523365SDimitry Andric // Last function offset found in the VST. 1427d523365SDimitry Andric uint64_t LastFunctionBlockBit = 0; 1438f0fd8f6SDimitry Andric bool SeenValueSymbolTable = false; 1447d523365SDimitry Andric uint64_t VSTOffset = 0; 1457d523365SDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer 1467d523365SDimitry Andric std::string ProducerIdentification; 1477d523365SDimitry Andric // Number of module level metadata records specified by the 1487d523365SDimitry Andric // MODULE_CODE_METADATA_VALUES record. 1497d523365SDimitry Andric unsigned NumModuleMDs = 0; 1507d523365SDimitry Andric // Support older bitcode without the MODULE_CODE_METADATA_VALUES record. 1517d523365SDimitry Andric bool SeenModuleValuesRecord = false; 152ff0cc061SDimitry Andric 153ff0cc061SDimitry Andric std::vector<Type*> TypeList; 154ff0cc061SDimitry Andric BitcodeReaderValueList ValueList; 1557d523365SDimitry Andric BitcodeReaderMetadataList MetadataList; 156ff0cc061SDimitry Andric std::vector<Comdat *> ComdatList; 157ff0cc061SDimitry Andric SmallVector<Instruction *, 64> InstructionList; 158ff0cc061SDimitry Andric 159ff0cc061SDimitry Andric std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits; 160ff0cc061SDimitry Andric std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits; 161ff0cc061SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrefixes; 162ff0cc061SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrologues; 1638f0fd8f6SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns; 164ff0cc061SDimitry Andric 165ff0cc061SDimitry Andric SmallVector<Instruction*, 64> InstsWithTBAATag; 166ff0cc061SDimitry Andric 1678f0fd8f6SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and 1688f0fd8f6SDimitry Andric /// is thus not represented here. As such all indices are off by one. 169ff0cc061SDimitry Andric std::vector<AttributeSet> MAttributes; 170ff0cc061SDimitry Andric 1717d523365SDimitry Andric /// The set of attribute groups. 172ff0cc061SDimitry Andric std::map<unsigned, AttributeSet> MAttributeGroups; 173ff0cc061SDimitry Andric 1748f0fd8f6SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the 1758f0fd8f6SDimitry Andric /// function. 176ff0cc061SDimitry Andric std::vector<BasicBlock*> FunctionBBs; 177ff0cc061SDimitry Andric 178ff0cc061SDimitry Andric // When reading the module header, this list is populated with functions that 179ff0cc061SDimitry Andric // have bodies later in the file. 180ff0cc061SDimitry Andric std::vector<Function*> FunctionsWithBodies; 181ff0cc061SDimitry Andric 182ff0cc061SDimitry Andric // When intrinsic functions are encountered which require upgrading they are 183ff0cc061SDimitry Andric // stored here with their replacement function. 1843dac3a9bSDimitry Andric typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap; 185ff0cc061SDimitry Andric UpgradedIntrinsicMap UpgradedIntrinsics; 186ff0cc061SDimitry Andric 187ff0cc061SDimitry Andric // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 188ff0cc061SDimitry Andric DenseMap<unsigned, unsigned> MDKindMap; 189ff0cc061SDimitry Andric 190ff0cc061SDimitry Andric // Several operations happen after the module header has been read, but 191ff0cc061SDimitry Andric // before function bodies are processed. This keeps track of whether 192ff0cc061SDimitry Andric // we've done this yet. 1938f0fd8f6SDimitry Andric bool SeenFirstFunctionBody = false; 194ff0cc061SDimitry Andric 1958f0fd8f6SDimitry Andric /// When function bodies are initially scanned, this map contains info about 1968f0fd8f6SDimitry Andric /// where to find deferred function body in the stream. 197ff0cc061SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo; 198ff0cc061SDimitry Andric 199ff0cc061SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may 200ff0cc061SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about 201ff0cc061SDimitry Andric /// which Metadata blocks are deferred. 202ff0cc061SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo; 203ff0cc061SDimitry Andric 204ff0cc061SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are 205ff0cc061SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is 206ff0cc061SDimitry Andric /// its index into the vector. 207ff0cc061SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 208ff0cc061SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue; 209ff0cc061SDimitry Andric 2108f0fd8f6SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where 2118f0fd8f6SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the 2128f0fd8f6SDimitry Andric /// instruction number, for a more compact encoding. Some instruction 2138f0fd8f6SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and 2148f0fd8f6SDimitry Andric /// types. Once the old style function blocks have been phased out, we would 215ff0cc061SDimitry Andric /// not need this flag. 2168f0fd8f6SDimitry Andric bool UseRelativeIDs = false; 217ff0cc061SDimitry Andric 218ff0cc061SDimitry Andric /// True if all functions will be materialized, negating the need to process 219ff0cc061SDimitry Andric /// (e.g.) blockaddress forward references. 2208f0fd8f6SDimitry Andric bool WillMaterializeAllForwardRefs = false; 221ff0cc061SDimitry Andric 222ff0cc061SDimitry Andric /// True if any Metadata block has been materialized. 2238f0fd8f6SDimitry Andric bool IsMetadataMaterialized = false; 224ff0cc061SDimitry Andric 225ff0cc061SDimitry Andric bool StripDebugInfo = false; 226ff0cc061SDimitry Andric 2277d523365SDimitry Andric /// Functions that need to be matched with subprograms when upgrading old 2287d523365SDimitry Andric /// metadata. 2297d523365SDimitry Andric SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 2307d523365SDimitry Andric 2317d523365SDimitry Andric std::vector<std::string> BundleTags; 2327d523365SDimitry Andric 233ff0cc061SDimitry Andric public: 2348f0fd8f6SDimitry Andric std::error_code error(BitcodeError E, const Twine &Message); 2358f0fd8f6SDimitry Andric std::error_code error(BitcodeError E); 2368f0fd8f6SDimitry Andric std::error_code error(const Twine &Message); 237ff0cc061SDimitry Andric 2387d523365SDimitry Andric BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context); 2397d523365SDimitry Andric BitcodeReader(LLVMContext &Context); 2408f0fd8f6SDimitry Andric ~BitcodeReader() override { freeState(); } 241ff0cc061SDimitry Andric 242ff0cc061SDimitry Andric std::error_code materializeForwardReferencedFunctions(); 243ff0cc061SDimitry Andric 2448f0fd8f6SDimitry Andric void freeState(); 245ff0cc061SDimitry Andric 246ff0cc061SDimitry Andric void releaseBuffer(); 247ff0cc061SDimitry Andric 248ff0cc061SDimitry Andric std::error_code materialize(GlobalValue *GV) override; 2497d523365SDimitry Andric std::error_code materializeModule() override; 250ff0cc061SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override; 251ff0cc061SDimitry Andric 2528f0fd8f6SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 2538f0fd8f6SDimitry Andric /// \returns true if an error occurred. 2548f0fd8f6SDimitry Andric std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 2558f0fd8f6SDimitry Andric Module *M, 256ff0cc061SDimitry Andric bool ShouldLazyLoadMetadata = false); 257ff0cc061SDimitry Andric 2588f0fd8f6SDimitry Andric /// \brief Cheap mechanism to just extract module triple 2598f0fd8f6SDimitry Andric /// \returns true if an error occurred. 260ff0cc061SDimitry Andric ErrorOr<std::string> parseTriple(); 261ff0cc061SDimitry Andric 2627d523365SDimitry Andric /// Cheap mechanism to just extract the identification block out of bitcode. 2637d523365SDimitry Andric ErrorOr<std::string> parseIdentificationBlock(); 2647d523365SDimitry Andric 265ff0cc061SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V); 266ff0cc061SDimitry Andric 267ff0cc061SDimitry Andric /// Materialize any deferred Metadata block. 268ff0cc061SDimitry Andric std::error_code materializeMetadata() override; 269ff0cc061SDimitry Andric 270ff0cc061SDimitry Andric void setStripDebugInfo() override; 271ff0cc061SDimitry Andric 2727d523365SDimitry Andric /// Save the mapping between the metadata values and the corresponding 2737d523365SDimitry Andric /// value id that were recorded in the MetadataList during parsing. If 2747d523365SDimitry Andric /// OnlyTempMD is true, then only record those entries that are still 2757d523365SDimitry Andric /// temporary metadata. This interface is used when metadata linking is 2767d523365SDimitry Andric /// performed as a postpass, such as during function importing. 2777d523365SDimitry Andric void saveMetadataList(DenseMap<const Metadata *, unsigned> &MetadataToIDs, 2787d523365SDimitry Andric bool OnlyTempMD) override; 2797d523365SDimitry Andric 280ff0cc061SDimitry Andric private: 2817d523365SDimitry Andric /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the 2827d523365SDimitry Andric // ProducerIdentification data member, and do some basic enforcement on the 2837d523365SDimitry Andric // "epoch" encoded in the bitcode. 2847d523365SDimitry Andric std::error_code parseBitcodeVersion(); 2857d523365SDimitry Andric 286ff0cc061SDimitry Andric std::vector<StructType *> IdentifiedStructTypes; 287ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 288ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context); 289ff0cc061SDimitry Andric 290ff0cc061SDimitry Andric Type *getTypeByID(unsigned ID); 291ff0cc061SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty) { 292ff0cc061SDimitry Andric if (Ty && Ty->isMetadataTy()) 293ff0cc061SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 294ff0cc061SDimitry Andric return ValueList.getValueFwdRef(ID, Ty); 295ff0cc061SDimitry Andric } 296ff0cc061SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) { 2977d523365SDimitry Andric return MetadataList.getValueFwdRef(ID); 298ff0cc061SDimitry Andric } 299ff0cc061SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const { 300ff0cc061SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 301ff0cc061SDimitry Andric return FunctionBBs[ID]; 302ff0cc061SDimitry Andric } 303ff0cc061SDimitry Andric AttributeSet getAttributes(unsigned i) const { 304ff0cc061SDimitry Andric if (i-1 < MAttributes.size()) 305ff0cc061SDimitry Andric return MAttributes[i-1]; 306ff0cc061SDimitry Andric return AttributeSet(); 307ff0cc061SDimitry Andric } 308ff0cc061SDimitry Andric 3098f0fd8f6SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'. 3108f0fd8f6SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on 3118f0fd8f6SDimitry Andric /// failure. 312ff0cc061SDimitry Andric bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 313ff0cc061SDimitry Andric unsigned InstNum, Value *&ResVal) { 314ff0cc061SDimitry Andric if (Slot == Record.size()) return true; 315ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++]; 316ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 317ff0cc061SDimitry Andric if (UseRelativeIDs) 318ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 319ff0cc061SDimitry Andric if (ValNo < InstNum) { 320ff0cc061SDimitry Andric // If this is not a forward reference, just return the value we already 321ff0cc061SDimitry Andric // have. 322ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr); 323ff0cc061SDimitry Andric return ResVal == nullptr; 324ff0cc061SDimitry Andric } 325ff0cc061SDimitry Andric if (Slot == Record.size()) 326ff0cc061SDimitry Andric return true; 327ff0cc061SDimitry Andric 328ff0cc061SDimitry Andric unsigned TypeNo = (unsigned)Record[Slot++]; 329ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 330ff0cc061SDimitry Andric return ResVal == nullptr; 331ff0cc061SDimitry Andric } 332ff0cc061SDimitry Andric 3338f0fd8f6SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot 3348f0fd8f6SDimitry Andric /// past the number of slots used by the value in the record. Return true if 3358f0fd8f6SDimitry Andric /// there is an error. 336ff0cc061SDimitry Andric bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 337ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 338ff0cc061SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, ResVal)) 339ff0cc061SDimitry Andric return true; 340ff0cc061SDimitry Andric // All values currently take a single record slot. 341ff0cc061SDimitry Andric ++Slot; 342ff0cc061SDimitry Andric return false; 343ff0cc061SDimitry Andric } 344ff0cc061SDimitry Andric 3458f0fd8f6SDimitry Andric /// Like popValue, but does not increment the Slot number. 346ff0cc061SDimitry Andric bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 347ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 348ff0cc061SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty); 349ff0cc061SDimitry Andric return ResVal == nullptr; 350ff0cc061SDimitry Andric } 351ff0cc061SDimitry Andric 3528f0fd8f6SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an 3538f0fd8f6SDimitry Andric /// error. 354ff0cc061SDimitry Andric Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 355ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 356ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 357ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot]; 358ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 359ff0cc061SDimitry Andric if (UseRelativeIDs) 360ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 361ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 362ff0cc061SDimitry Andric } 363ff0cc061SDimitry Andric 3648f0fd8f6SDimitry Andric /// Like getValue, but decodes signed VBRs. 365ff0cc061SDimitry Andric Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 366ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 367ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 368ff0cc061SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 369ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 370ff0cc061SDimitry Andric if (UseRelativeIDs) 371ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 372ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 373ff0cc061SDimitry Andric } 374ff0cc061SDimitry Andric 375ff0cc061SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the 376ff0cc061SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns 377ff0cc061SDimitry Andric /// a corresponding error code. 378ff0cc061SDimitry Andric std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 3798f0fd8f6SDimitry Andric std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 3807d523365SDimitry Andric std::error_code parseModule(uint64_t ResumeBit, 3817d523365SDimitry Andric bool ShouldLazyLoadMetadata = false); 3828f0fd8f6SDimitry Andric std::error_code parseAttributeBlock(); 3838f0fd8f6SDimitry Andric std::error_code parseAttributeGroupBlock(); 3848f0fd8f6SDimitry Andric std::error_code parseTypeTable(); 3858f0fd8f6SDimitry Andric std::error_code parseTypeTableBody(); 3867d523365SDimitry Andric std::error_code parseOperandBundleTags(); 387ff0cc061SDimitry Andric 3887d523365SDimitry Andric ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 3897d523365SDimitry Andric unsigned NameIndex, Triple &TT); 3907d523365SDimitry Andric std::error_code parseValueSymbolTable(uint64_t Offset = 0); 3918f0fd8f6SDimitry Andric std::error_code parseConstants(); 3927d523365SDimitry Andric std::error_code rememberAndSkipFunctionBodies(); 3938f0fd8f6SDimitry Andric std::error_code rememberAndSkipFunctionBody(); 394ff0cc061SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks. 395ff0cc061SDimitry Andric std::error_code rememberAndSkipMetadata(); 3968f0fd8f6SDimitry Andric std::error_code parseFunctionBody(Function *F); 3978f0fd8f6SDimitry Andric std::error_code globalCleanup(); 3988f0fd8f6SDimitry Andric std::error_code resolveGlobalAndAliasInits(); 3997d523365SDimitry Andric std::error_code parseMetadata(bool ModuleLevel = false); 4007d523365SDimitry Andric std::error_code parseMetadataKinds(); 4017d523365SDimitry Andric std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 4028f0fd8f6SDimitry Andric std::error_code parseMetadataAttachment(Function &F); 403ff0cc061SDimitry Andric ErrorOr<std::string> parseModuleTriple(); 4048f0fd8f6SDimitry Andric std::error_code parseUseLists(); 4058f0fd8f6SDimitry Andric std::error_code initStream(std::unique_ptr<DataStreamer> Streamer); 4068f0fd8f6SDimitry Andric std::error_code initStreamFromBuffer(); 4078f0fd8f6SDimitry Andric std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer); 4088f0fd8f6SDimitry Andric std::error_code findFunctionInStream( 409ff0cc061SDimitry Andric Function *F, 410ff0cc061SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 411ff0cc061SDimitry Andric }; 4127d523365SDimitry Andric 4137d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode 4147d523365SDimitry Andric /// files/sections. 4157d523365SDimitry Andric class FunctionIndexBitcodeReader { 4167d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler; 4177d523365SDimitry Andric 4187d523365SDimitry Andric /// Eventually points to the function index built during parsing. 4197d523365SDimitry Andric FunctionInfoIndex *TheIndex = nullptr; 4207d523365SDimitry Andric 4217d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buffer; 4227d523365SDimitry Andric std::unique_ptr<BitstreamReader> StreamFile; 4237d523365SDimitry Andric BitstreamCursor Stream; 4247d523365SDimitry Andric 4257d523365SDimitry Andric /// \brief Used to indicate whether we are doing lazy parsing of summary data. 4267d523365SDimitry Andric /// 4277d523365SDimitry Andric /// If false, the summary section is fully parsed into the index during 4287d523365SDimitry Andric /// the initial parse. Otherwise, if true, the caller is expected to 4297d523365SDimitry Andric /// invoke \a readFunctionSummary for each summary needed, and the summary 4307d523365SDimitry Andric /// section is thus parsed lazily. 4317d523365SDimitry Andric bool IsLazy = false; 4327d523365SDimitry Andric 4337d523365SDimitry Andric /// Used to indicate whether caller only wants to check for the presence 4347d523365SDimitry Andric /// of the function summary bitcode section. All blocks are skipped, 4357d523365SDimitry Andric /// but the SeenFuncSummary boolean is set. 4367d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly = false; 4377d523365SDimitry Andric 4387d523365SDimitry Andric /// Indicates whether we have encountered a function summary section 4397d523365SDimitry Andric /// yet during parsing, used when checking if file contains function 4407d523365SDimitry Andric /// summary section. 4417d523365SDimitry Andric bool SeenFuncSummary = false; 4427d523365SDimitry Andric 4437d523365SDimitry Andric /// \brief Map populated during function summary section parsing, and 4447d523365SDimitry Andric /// consumed during ValueSymbolTable parsing. 4457d523365SDimitry Andric /// 4467d523365SDimitry Andric /// Used to correlate summary records with VST entries. For the per-module 4477d523365SDimitry Andric /// index this maps the ValueID to the parsed function summary, and 4487d523365SDimitry Andric /// for the combined index this maps the summary record's bitcode 4497d523365SDimitry Andric /// offset to the function summary (since in the combined index the 4507d523365SDimitry Andric /// VST records do not hold value IDs but rather hold the function 4517d523365SDimitry Andric /// summary record offset). 4527d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap; 4537d523365SDimitry Andric 4547d523365SDimitry Andric /// Map populated during module path string table parsing, from the 4557d523365SDimitry Andric /// module ID to a string reference owned by the index's module 4567d523365SDimitry Andric /// path string table, used to correlate with combined index function 4577d523365SDimitry Andric /// summary records. 4587d523365SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap; 4597d523365SDimitry Andric 4607d523365SDimitry Andric public: 4617d523365SDimitry Andric std::error_code error(BitcodeError E, const Twine &Message); 4627d523365SDimitry Andric std::error_code error(BitcodeError E); 4637d523365SDimitry Andric std::error_code error(const Twine &Message); 4647d523365SDimitry Andric 4657d523365SDimitry Andric FunctionIndexBitcodeReader(MemoryBuffer *Buffer, 4667d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, 4677d523365SDimitry Andric bool IsLazy = false, 4687d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly = false); 4697d523365SDimitry Andric FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler, 4707d523365SDimitry Andric bool IsLazy = false, 4717d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly = false); 4727d523365SDimitry Andric ~FunctionIndexBitcodeReader() { freeState(); } 4737d523365SDimitry Andric 4747d523365SDimitry Andric void freeState(); 4757d523365SDimitry Andric 4767d523365SDimitry Andric void releaseBuffer(); 4777d523365SDimitry Andric 4787d523365SDimitry Andric /// Check if the parser has encountered a function summary section. 4797d523365SDimitry Andric bool foundFuncSummary() { return SeenFuncSummary; } 4807d523365SDimitry Andric 4817d523365SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 4827d523365SDimitry Andric /// \returns true if an error occurred. 4837d523365SDimitry Andric std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer, 4847d523365SDimitry Andric FunctionInfoIndex *I); 4857d523365SDimitry Andric 4867d523365SDimitry Andric /// \brief Interface for parsing a function summary lazily. 4877d523365SDimitry Andric std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer, 4887d523365SDimitry Andric FunctionInfoIndex *I, 4897d523365SDimitry Andric size_t FunctionSummaryOffset); 4907d523365SDimitry Andric 4917d523365SDimitry Andric private: 4927d523365SDimitry Andric std::error_code parseModule(); 4937d523365SDimitry Andric std::error_code parseValueSymbolTable(); 4947d523365SDimitry Andric std::error_code parseEntireSummary(); 4957d523365SDimitry Andric std::error_code parseModuleStringTable(); 4967d523365SDimitry Andric std::error_code initStream(std::unique_ptr<DataStreamer> Streamer); 4977d523365SDimitry Andric std::error_code initStreamFromBuffer(); 4987d523365SDimitry Andric std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer); 4997d523365SDimitry Andric }; 500ff0cc061SDimitry Andric } // namespace 501ff0cc061SDimitry Andric 50239d628a0SDimitry Andric BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC, 50339d628a0SDimitry Andric DiagnosticSeverity Severity, 50439d628a0SDimitry Andric const Twine &Msg) 50539d628a0SDimitry Andric : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {} 50639d628a0SDimitry Andric 50739d628a0SDimitry Andric void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 50839d628a0SDimitry Andric 5098f0fd8f6SDimitry Andric static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, 51039d628a0SDimitry Andric std::error_code EC, const Twine &Message) { 51139d628a0SDimitry Andric BitcodeDiagnosticInfo DI(EC, DS_Error, Message); 51239d628a0SDimitry Andric DiagnosticHandler(DI); 51339d628a0SDimitry Andric return EC; 514dff0c46cSDimitry Andric } 51539d628a0SDimitry Andric 5168f0fd8f6SDimitry Andric static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, 51739d628a0SDimitry Andric std::error_code EC) { 5188f0fd8f6SDimitry Andric return error(DiagnosticHandler, EC, EC.message()); 51939d628a0SDimitry Andric } 52039d628a0SDimitry Andric 5217d523365SDimitry Andric static std::error_code error(LLVMContext &Context, std::error_code EC, 522ff0cc061SDimitry Andric const Twine &Message) { 5237d523365SDimitry Andric return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC, 5247d523365SDimitry Andric Message); 5257d523365SDimitry Andric } 5267d523365SDimitry Andric 5277d523365SDimitry Andric static std::error_code error(LLVMContext &Context, std::error_code EC) { 5287d523365SDimitry Andric return error(Context, EC, EC.message()); 5297d523365SDimitry Andric } 5307d523365SDimitry Andric 5317d523365SDimitry Andric static std::error_code error(LLVMContext &Context, const Twine &Message) { 5327d523365SDimitry Andric return error(Context, make_error_code(BitcodeError::CorruptedBitcode), 5337d523365SDimitry Andric Message); 534ff0cc061SDimitry Andric } 535ff0cc061SDimitry Andric 5368f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) { 5377d523365SDimitry Andric if (!ProducerIdentification.empty()) { 5387d523365SDimitry Andric return ::error(Context, make_error_code(E), 5397d523365SDimitry Andric Message + " (Producer: '" + ProducerIdentification + 5407d523365SDimitry Andric "' Reader: 'LLVM " + LLVM_VERSION_STRING "')"); 5417d523365SDimitry Andric } 5427d523365SDimitry Andric return ::error(Context, make_error_code(E), Message); 54339d628a0SDimitry Andric } 54439d628a0SDimitry Andric 5458f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(const Twine &Message) { 5467d523365SDimitry Andric if (!ProducerIdentification.empty()) { 5477d523365SDimitry Andric return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode), 5487d523365SDimitry Andric Message + " (Producer: '" + ProducerIdentification + 5497d523365SDimitry Andric "' Reader: 'LLVM " + LLVM_VERSION_STRING "')"); 5507d523365SDimitry Andric } 5517d523365SDimitry Andric return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode), 5527d523365SDimitry Andric Message); 55339d628a0SDimitry Andric } 55439d628a0SDimitry Andric 5558f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(BitcodeError E) { 5567d523365SDimitry Andric return ::error(Context, make_error_code(E)); 55739d628a0SDimitry Andric } 55839d628a0SDimitry Andric 5597d523365SDimitry Andric BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context) 5607d523365SDimitry Andric : Context(Context), Buffer(Buffer), ValueList(Context), 5617d523365SDimitry Andric MetadataList(Context) {} 56239d628a0SDimitry Andric 5637d523365SDimitry Andric BitcodeReader::BitcodeReader(LLVMContext &Context) 5647d523365SDimitry Andric : Context(Context), Buffer(nullptr), ValueList(Context), 5657d523365SDimitry Andric MetadataList(Context) {} 56639d628a0SDimitry Andric 56739d628a0SDimitry Andric std::error_code BitcodeReader::materializeForwardReferencedFunctions() { 56839d628a0SDimitry Andric if (WillMaterializeAllForwardRefs) 56939d628a0SDimitry Andric return std::error_code(); 57039d628a0SDimitry Andric 57139d628a0SDimitry Andric // Prevent recursion. 57239d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 57339d628a0SDimitry Andric 57439d628a0SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) { 57539d628a0SDimitry Andric Function *F = BasicBlockFwdRefQueue.front(); 57639d628a0SDimitry Andric BasicBlockFwdRefQueue.pop_front(); 57739d628a0SDimitry Andric assert(F && "Expected valid function"); 57839d628a0SDimitry Andric if (!BasicBlockFwdRefs.count(F)) 57939d628a0SDimitry Andric // Already materialized. 58039d628a0SDimitry Andric continue; 58139d628a0SDimitry Andric 58239d628a0SDimitry Andric // Check for a function that isn't materializable to prevent an infinite 58339d628a0SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there 58439d628a0SDimitry Andric // isn't a trivial way to check if a function will have a body without a 58539d628a0SDimitry Andric // linear search through FunctionsWithBodies, so just check it here. 58639d628a0SDimitry Andric if (!F->isMaterializable()) 5878f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 58839d628a0SDimitry Andric 58939d628a0SDimitry Andric // Try to materialize F. 59039d628a0SDimitry Andric if (std::error_code EC = materialize(F)) 59139d628a0SDimitry Andric return EC; 59239d628a0SDimitry Andric } 59339d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 59439d628a0SDimitry Andric 59539d628a0SDimitry Andric // Reset state. 59639d628a0SDimitry Andric WillMaterializeAllForwardRefs = false; 59739d628a0SDimitry Andric return std::error_code(); 598dff0c46cSDimitry Andric } 599dff0c46cSDimitry Andric 6008f0fd8f6SDimitry Andric void BitcodeReader::freeState() { 60191bc56edSDimitry Andric Buffer = nullptr; 60217a519f9SDimitry Andric std::vector<Type*>().swap(TypeList); 603f22ef01cSRoman Divacky ValueList.clear(); 6047d523365SDimitry Andric MetadataList.clear(); 60591bc56edSDimitry Andric std::vector<Comdat *>().swap(ComdatList); 606f22ef01cSRoman Divacky 607139f7f9bSDimitry Andric std::vector<AttributeSet>().swap(MAttributes); 608f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 609f22ef01cSRoman Divacky std::vector<Function*>().swap(FunctionsWithBodies); 610f22ef01cSRoman Divacky DeferredFunctionInfo.clear(); 611ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 612e580952dSDimitry Andric MDKindMap.clear(); 6133861d79fSDimitry Andric 61439d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references"); 61539d628a0SDimitry Andric BasicBlockFwdRefQueue.clear(); 616f22ef01cSRoman Divacky } 617f22ef01cSRoman Divacky 618f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 619f22ef01cSRoman Divacky // Helper functions to implement forward reference resolution, etc. 620f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 621f22ef01cSRoman Divacky 6228f0fd8f6SDimitry Andric /// Convert a string from a record into an std::string, return true on failure. 623f22ef01cSRoman Divacky template <typename StrTy> 6248f0fd8f6SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 625f22ef01cSRoman Divacky StrTy &Result) { 626f22ef01cSRoman Divacky if (Idx > Record.size()) 627f22ef01cSRoman Divacky return true; 628f22ef01cSRoman Divacky 629f22ef01cSRoman Divacky for (unsigned i = Idx, e = Record.size(); i != e; ++i) 630f22ef01cSRoman Divacky Result += (char)Record[i]; 631f22ef01cSRoman Divacky return false; 632f22ef01cSRoman Divacky } 633f22ef01cSRoman Divacky 634ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) { 635ff0cc061SDimitry Andric switch (Val) { 636ff0cc061SDimitry Andric default: 637ff0cc061SDimitry Andric return false; 638ff0cc061SDimitry Andric case 1: // Old WeakAnyLinkage 639ff0cc061SDimitry Andric case 4: // Old LinkOnceAnyLinkage 640ff0cc061SDimitry Andric case 10: // Old WeakODRLinkage 641ff0cc061SDimitry Andric case 11: // Old LinkOnceODRLinkage 642ff0cc061SDimitry Andric return true; 643ff0cc061SDimitry Andric } 644ff0cc061SDimitry Andric } 645ff0cc061SDimitry Andric 64639d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 647f22ef01cSRoman Divacky switch (Val) { 648f22ef01cSRoman Divacky default: // Map unknown/new linkages to external 64939d628a0SDimitry Andric case 0: 65039d628a0SDimitry Andric return GlobalValue::ExternalLinkage; 65139d628a0SDimitry Andric case 2: 65239d628a0SDimitry Andric return GlobalValue::AppendingLinkage; 65339d628a0SDimitry Andric case 3: 65439d628a0SDimitry Andric return GlobalValue::InternalLinkage; 65539d628a0SDimitry Andric case 5: 65639d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 65739d628a0SDimitry Andric case 6: 65839d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 65939d628a0SDimitry Andric case 7: 66039d628a0SDimitry Andric return GlobalValue::ExternalWeakLinkage; 66139d628a0SDimitry Andric case 8: 66239d628a0SDimitry Andric return GlobalValue::CommonLinkage; 66339d628a0SDimitry Andric case 9: 66439d628a0SDimitry Andric return GlobalValue::PrivateLinkage; 66539d628a0SDimitry Andric case 12: 66639d628a0SDimitry Andric return GlobalValue::AvailableExternallyLinkage; 66791bc56edSDimitry Andric case 13: 66891bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 66991bc56edSDimitry Andric case 14: 67091bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 67139d628a0SDimitry Andric case 15: 67239d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 673ff0cc061SDimitry Andric case 1: // Old value with implicit comdat. 674ff0cc061SDimitry Andric case 16: 675ff0cc061SDimitry Andric return GlobalValue::WeakAnyLinkage; 676ff0cc061SDimitry Andric case 10: // Old value with implicit comdat. 677ff0cc061SDimitry Andric case 17: 678ff0cc061SDimitry Andric return GlobalValue::WeakODRLinkage; 679ff0cc061SDimitry Andric case 4: // Old value with implicit comdat. 680ff0cc061SDimitry Andric case 18: 681ff0cc061SDimitry Andric return GlobalValue::LinkOnceAnyLinkage; 682ff0cc061SDimitry Andric case 11: // Old value with implicit comdat. 683ff0cc061SDimitry Andric case 19: 684ff0cc061SDimitry Andric return GlobalValue::LinkOnceODRLinkage; 685f22ef01cSRoman Divacky } 686f22ef01cSRoman Divacky } 687f22ef01cSRoman Divacky 6888f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 689f22ef01cSRoman Divacky switch (Val) { 690f22ef01cSRoman Divacky default: // Map unknown visibilities to default. 691f22ef01cSRoman Divacky case 0: return GlobalValue::DefaultVisibility; 692f22ef01cSRoman Divacky case 1: return GlobalValue::HiddenVisibility; 693f22ef01cSRoman Divacky case 2: return GlobalValue::ProtectedVisibility; 694f22ef01cSRoman Divacky } 695f22ef01cSRoman Divacky } 696f22ef01cSRoman Divacky 69791bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes 6988f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) { 69991bc56edSDimitry Andric switch (Val) { 70091bc56edSDimitry Andric default: // Map unknown values to default. 70191bc56edSDimitry Andric case 0: return GlobalValue::DefaultStorageClass; 70291bc56edSDimitry Andric case 1: return GlobalValue::DLLImportStorageClass; 70391bc56edSDimitry Andric case 2: return GlobalValue::DLLExportStorageClass; 70491bc56edSDimitry Andric } 70591bc56edSDimitry Andric } 70691bc56edSDimitry Andric 7078f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 7087ae0e2c9SDimitry Andric switch (Val) { 7097ae0e2c9SDimitry Andric case 0: return GlobalVariable::NotThreadLocal; 7107ae0e2c9SDimitry Andric default: // Map unknown non-zero value to general dynamic. 7117ae0e2c9SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel; 7127ae0e2c9SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel; 7137ae0e2c9SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel; 7147ae0e2c9SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel; 7157ae0e2c9SDimitry Andric } 7167ae0e2c9SDimitry Andric } 7177ae0e2c9SDimitry Andric 7188f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) { 719f22ef01cSRoman Divacky switch (Val) { 720f22ef01cSRoman Divacky default: return -1; 721f22ef01cSRoman Divacky case bitc::CAST_TRUNC : return Instruction::Trunc; 722f22ef01cSRoman Divacky case bitc::CAST_ZEXT : return Instruction::ZExt; 723f22ef01cSRoman Divacky case bitc::CAST_SEXT : return Instruction::SExt; 724f22ef01cSRoman Divacky case bitc::CAST_FPTOUI : return Instruction::FPToUI; 725f22ef01cSRoman Divacky case bitc::CAST_FPTOSI : return Instruction::FPToSI; 726f22ef01cSRoman Divacky case bitc::CAST_UITOFP : return Instruction::UIToFP; 727f22ef01cSRoman Divacky case bitc::CAST_SITOFP : return Instruction::SIToFP; 728f22ef01cSRoman Divacky case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 729f22ef01cSRoman Divacky case bitc::CAST_FPEXT : return Instruction::FPExt; 730f22ef01cSRoman Divacky case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 731f22ef01cSRoman Divacky case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 732f22ef01cSRoman Divacky case bitc::CAST_BITCAST : return Instruction::BitCast; 733f785676fSDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 734f22ef01cSRoman Divacky } 735f22ef01cSRoman Divacky } 736ff0cc061SDimitry Andric 7378f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 738ff0cc061SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 739ff0cc061SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types 740ff0cc061SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 741ff0cc061SDimitry Andric return -1; 742ff0cc061SDimitry Andric 743f22ef01cSRoman Divacky switch (Val) { 744ff0cc061SDimitry Andric default: 745ff0cc061SDimitry Andric return -1; 746f22ef01cSRoman Divacky case bitc::BINOP_ADD: 747ff0cc061SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add; 748f22ef01cSRoman Divacky case bitc::BINOP_SUB: 749ff0cc061SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub; 750f22ef01cSRoman Divacky case bitc::BINOP_MUL: 751ff0cc061SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul; 752ff0cc061SDimitry Andric case bitc::BINOP_UDIV: 753ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::UDiv; 754f22ef01cSRoman Divacky case bitc::BINOP_SDIV: 755ff0cc061SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv; 756ff0cc061SDimitry Andric case bitc::BINOP_UREM: 757ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::URem; 758f22ef01cSRoman Divacky case bitc::BINOP_SREM: 759ff0cc061SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem; 760ff0cc061SDimitry Andric case bitc::BINOP_SHL: 761ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Shl; 762ff0cc061SDimitry Andric case bitc::BINOP_LSHR: 763ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::LShr; 764ff0cc061SDimitry Andric case bitc::BINOP_ASHR: 765ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::AShr; 766ff0cc061SDimitry Andric case bitc::BINOP_AND: 767ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::And; 768ff0cc061SDimitry Andric case bitc::BINOP_OR: 769ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Or; 770ff0cc061SDimitry Andric case bitc::BINOP_XOR: 771ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Xor; 772f22ef01cSRoman Divacky } 773f22ef01cSRoman Divacky } 774f22ef01cSRoman Divacky 7758f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 7766122f3e6SDimitry Andric switch (Val) { 7776122f3e6SDimitry Andric default: return AtomicRMWInst::BAD_BINOP; 7786122f3e6SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 7796122f3e6SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add; 7806122f3e6SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub; 7816122f3e6SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And; 7826122f3e6SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand; 7836122f3e6SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or; 7846122f3e6SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor; 7856122f3e6SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max; 7866122f3e6SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min; 7876122f3e6SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 7886122f3e6SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 7896122f3e6SDimitry Andric } 7906122f3e6SDimitry Andric } 7916122f3e6SDimitry Andric 7928f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) { 7936122f3e6SDimitry Andric switch (Val) { 7946122f3e6SDimitry Andric case bitc::ORDERING_NOTATOMIC: return NotAtomic; 7956122f3e6SDimitry Andric case bitc::ORDERING_UNORDERED: return Unordered; 7966122f3e6SDimitry Andric case bitc::ORDERING_MONOTONIC: return Monotonic; 7976122f3e6SDimitry Andric case bitc::ORDERING_ACQUIRE: return Acquire; 7986122f3e6SDimitry Andric case bitc::ORDERING_RELEASE: return Release; 7996122f3e6SDimitry Andric case bitc::ORDERING_ACQREL: return AcquireRelease; 8006122f3e6SDimitry Andric default: // Map unknown orderings to sequentially-consistent. 8016122f3e6SDimitry Andric case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 8026122f3e6SDimitry Andric } 8036122f3e6SDimitry Andric } 8046122f3e6SDimitry Andric 8058f0fd8f6SDimitry Andric static SynchronizationScope getDecodedSynchScope(unsigned Val) { 8066122f3e6SDimitry Andric switch (Val) { 8076122f3e6SDimitry Andric case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 8086122f3e6SDimitry Andric default: // Map unknown scopes to cross-thread. 8096122f3e6SDimitry Andric case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 8106122f3e6SDimitry Andric } 8116122f3e6SDimitry Andric } 8126122f3e6SDimitry Andric 81391bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 81491bc56edSDimitry Andric switch (Val) { 81591bc56edSDimitry Andric default: // Map unknown selection kinds to any. 81691bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY: 81791bc56edSDimitry Andric return Comdat::Any; 81891bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 81991bc56edSDimitry Andric return Comdat::ExactMatch; 82091bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST: 82191bc56edSDimitry Andric return Comdat::Largest; 82291bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 82391bc56edSDimitry Andric return Comdat::NoDuplicates; 82491bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 82591bc56edSDimitry Andric return Comdat::SameSize; 82691bc56edSDimitry Andric } 82791bc56edSDimitry Andric } 82891bc56edSDimitry Andric 829875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 830875ed548SDimitry Andric FastMathFlags FMF; 831875ed548SDimitry Andric if (0 != (Val & FastMathFlags::UnsafeAlgebra)) 832875ed548SDimitry Andric FMF.setUnsafeAlgebra(); 833875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoNaNs)) 834875ed548SDimitry Andric FMF.setNoNaNs(); 835875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoInfs)) 836875ed548SDimitry Andric FMF.setNoInfs(); 837875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoSignedZeros)) 838875ed548SDimitry Andric FMF.setNoSignedZeros(); 839875ed548SDimitry Andric if (0 != (Val & FastMathFlags::AllowReciprocal)) 840875ed548SDimitry Andric FMF.setAllowReciprocal(); 841875ed548SDimitry Andric return FMF; 842875ed548SDimitry Andric } 843875ed548SDimitry Andric 8448f0fd8f6SDimitry Andric static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) { 84591bc56edSDimitry Andric switch (Val) { 84691bc56edSDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 84791bc56edSDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 84891bc56edSDimitry Andric } 84991bc56edSDimitry Andric } 85091bc56edSDimitry Andric 851f22ef01cSRoman Divacky namespace llvm { 852f22ef01cSRoman Divacky namespace { 8538f0fd8f6SDimitry Andric /// \brief A class for maintaining the slot number definition 854f22ef01cSRoman Divacky /// as a placeholder for the actual definition for forward constants defs. 855f22ef01cSRoman Divacky class ConstantPlaceHolder : public ConstantExpr { 856ff0cc061SDimitry Andric void operator=(const ConstantPlaceHolder &) = delete; 8578f0fd8f6SDimitry Andric 858f22ef01cSRoman Divacky public: 859f22ef01cSRoman Divacky // allocate space for exactly one operand 8608f0fd8f6SDimitry Andric void *operator new(size_t s) { return User::operator new(s, 1); } 8616122f3e6SDimitry Andric explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context) 862f22ef01cSRoman Divacky : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 863f22ef01cSRoman Divacky Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 864f22ef01cSRoman Divacky } 865f22ef01cSRoman Divacky 8668f0fd8f6SDimitry Andric /// \brief Methods to support type inquiry through isa, cast, and dyn_cast. 867f22ef01cSRoman Divacky static bool classof(const Value *V) { 868f22ef01cSRoman Divacky return isa<ConstantExpr>(V) && 869f22ef01cSRoman Divacky cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 870f22ef01cSRoman Divacky } 871f22ef01cSRoman Divacky 872f22ef01cSRoman Divacky /// Provide fast operand accessors 87339d628a0SDimitry Andric DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 874f22ef01cSRoman Divacky }; 8753dac3a9bSDimitry Andric } 876f22ef01cSRoman Divacky 877f22ef01cSRoman Divacky // FIXME: can we inherit this from ConstantExpr? 878f22ef01cSRoman Divacky template <> 8792754fe60SDimitry Andric struct OperandTraits<ConstantPlaceHolder> : 8802754fe60SDimitry Andric public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 881f22ef01cSRoman Divacky }; 88239d628a0SDimitry Andric DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 8833dac3a9bSDimitry Andric } 884f22ef01cSRoman Divacky 8858f0fd8f6SDimitry Andric void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) { 886f22ef01cSRoman Divacky if (Idx == size()) { 887f22ef01cSRoman Divacky push_back(V); 888f22ef01cSRoman Divacky return; 889f22ef01cSRoman Divacky } 890f22ef01cSRoman Divacky 891f22ef01cSRoman Divacky if (Idx >= size()) 892f22ef01cSRoman Divacky resize(Idx+1); 893f22ef01cSRoman Divacky 894f22ef01cSRoman Divacky WeakVH &OldV = ValuePtrs[Idx]; 89591bc56edSDimitry Andric if (!OldV) { 896f22ef01cSRoman Divacky OldV = V; 897f22ef01cSRoman Divacky return; 898f22ef01cSRoman Divacky } 899f22ef01cSRoman Divacky 900f22ef01cSRoman Divacky // Handle constants and non-constants (e.g. instrs) differently for 901f22ef01cSRoman Divacky // efficiency. 902f22ef01cSRoman Divacky if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 903f22ef01cSRoman Divacky ResolveConstants.push_back(std::make_pair(PHC, Idx)); 904f22ef01cSRoman Divacky OldV = V; 905f22ef01cSRoman Divacky } else { 906f22ef01cSRoman Divacky // If there was a forward reference to this value, replace it. 907f22ef01cSRoman Divacky Value *PrevVal = OldV; 908f22ef01cSRoman Divacky OldV->replaceAllUsesWith(V); 909f22ef01cSRoman Divacky delete PrevVal; 910f22ef01cSRoman Divacky } 9117d523365SDimitry Andric 9127d523365SDimitry Andric return; 913f22ef01cSRoman Divacky } 914f22ef01cSRoman Divacky 915f22ef01cSRoman Divacky 916f22ef01cSRoman Divacky Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 9176122f3e6SDimitry Andric Type *Ty) { 918f22ef01cSRoman Divacky if (Idx >= size()) 919f22ef01cSRoman Divacky resize(Idx + 1); 920f22ef01cSRoman Divacky 921f22ef01cSRoman Divacky if (Value *V = ValuePtrs[Idx]) { 922ff0cc061SDimitry Andric if (Ty != V->getType()) 923ff0cc061SDimitry Andric report_fatal_error("Type mismatch in constant table!"); 924f22ef01cSRoman Divacky return cast<Constant>(V); 925f22ef01cSRoman Divacky } 926f22ef01cSRoman Divacky 927f22ef01cSRoman Divacky // Create and return a placeholder, which will later be RAUW'd. 928f22ef01cSRoman Divacky Constant *C = new ConstantPlaceHolder(Ty, Context); 929f22ef01cSRoman Divacky ValuePtrs[Idx] = C; 930f22ef01cSRoman Divacky return C; 931f22ef01cSRoman Divacky } 932f22ef01cSRoman Divacky 9336122f3e6SDimitry Andric Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 934ff0cc061SDimitry Andric // Bail out for a clearly invalid value. This would make us call resize(0) 935ff0cc061SDimitry Andric if (Idx == UINT_MAX) 936ff0cc061SDimitry Andric return nullptr; 937ff0cc061SDimitry Andric 938f22ef01cSRoman Divacky if (Idx >= size()) 939f22ef01cSRoman Divacky resize(Idx + 1); 940f22ef01cSRoman Divacky 941f22ef01cSRoman Divacky if (Value *V = ValuePtrs[Idx]) { 942ff0cc061SDimitry Andric // If the types don't match, it's invalid. 943ff0cc061SDimitry Andric if (Ty && Ty != V->getType()) 944ff0cc061SDimitry Andric return nullptr; 945f22ef01cSRoman Divacky return V; 946f22ef01cSRoman Divacky } 947f22ef01cSRoman Divacky 948f22ef01cSRoman Divacky // No type specified, must be invalid reference. 94991bc56edSDimitry Andric if (!Ty) return nullptr; 950f22ef01cSRoman Divacky 951f22ef01cSRoman Divacky // Create and return a placeholder, which will later be RAUW'd. 952f22ef01cSRoman Divacky Value *V = new Argument(Ty); 953f22ef01cSRoman Divacky ValuePtrs[Idx] = V; 954f22ef01cSRoman Divacky return V; 955f22ef01cSRoman Divacky } 956f22ef01cSRoman Divacky 9578f0fd8f6SDimitry Andric /// Once all constants are read, this method bulk resolves any forward 9588f0fd8f6SDimitry Andric /// references. The idea behind this is that we sometimes get constants (such 9598f0fd8f6SDimitry Andric /// as large arrays) which reference *many* forward ref constants. Replacing 9608f0fd8f6SDimitry Andric /// each of these causes a lot of thrashing when building/reuniquing the 9618f0fd8f6SDimitry Andric /// constant. Instead of doing this, we look at all the uses and rewrite all 9628f0fd8f6SDimitry Andric /// the place holders at once for any constant that uses a placeholder. 9638f0fd8f6SDimitry Andric void BitcodeReaderValueList::resolveConstantForwardRefs() { 964f22ef01cSRoman Divacky // Sort the values by-pointer so that they are efficient to look up with a 965f22ef01cSRoman Divacky // binary search. 966f22ef01cSRoman Divacky std::sort(ResolveConstants.begin(), ResolveConstants.end()); 967f22ef01cSRoman Divacky 968f22ef01cSRoman Divacky SmallVector<Constant*, 64> NewOps; 969f22ef01cSRoman Divacky 970f22ef01cSRoman Divacky while (!ResolveConstants.empty()) { 971f22ef01cSRoman Divacky Value *RealVal = operator[](ResolveConstants.back().second); 972f22ef01cSRoman Divacky Constant *Placeholder = ResolveConstants.back().first; 973f22ef01cSRoman Divacky ResolveConstants.pop_back(); 974f22ef01cSRoman Divacky 975f22ef01cSRoman Divacky // Loop over all users of the placeholder, updating them to reference the 976f22ef01cSRoman Divacky // new value. If they reference more than one placeholder, update them all 977f22ef01cSRoman Divacky // at once. 978f22ef01cSRoman Divacky while (!Placeholder->use_empty()) { 97991bc56edSDimitry Andric auto UI = Placeholder->user_begin(); 980ffd1746dSEd Schouten User *U = *UI; 981f22ef01cSRoman Divacky 982f22ef01cSRoman Divacky // If the using object isn't uniqued, just update the operands. This 983f22ef01cSRoman Divacky // handles instructions and initializers for global variables. 984ffd1746dSEd Schouten if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 985f22ef01cSRoman Divacky UI.getUse().set(RealVal); 986f22ef01cSRoman Divacky continue; 987f22ef01cSRoman Divacky } 988f22ef01cSRoman Divacky 989f22ef01cSRoman Divacky // Otherwise, we have a constant that uses the placeholder. Replace that 990f22ef01cSRoman Divacky // constant with a new constant that has *all* placeholder uses updated. 991ffd1746dSEd Schouten Constant *UserC = cast<Constant>(U); 992f22ef01cSRoman Divacky for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 993f22ef01cSRoman Divacky I != E; ++I) { 994f22ef01cSRoman Divacky Value *NewOp; 995f22ef01cSRoman Divacky if (!isa<ConstantPlaceHolder>(*I)) { 996f22ef01cSRoman Divacky // Not a placeholder reference. 997f22ef01cSRoman Divacky NewOp = *I; 998f22ef01cSRoman Divacky } else if (*I == Placeholder) { 999f22ef01cSRoman Divacky // Common case is that it just references this one placeholder. 1000f22ef01cSRoman Divacky NewOp = RealVal; 1001f22ef01cSRoman Divacky } else { 1002f22ef01cSRoman Divacky // Otherwise, look up the placeholder in ResolveConstants. 1003f22ef01cSRoman Divacky ResolveConstantsTy::iterator It = 1004f22ef01cSRoman Divacky std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 1005f22ef01cSRoman Divacky std::pair<Constant*, unsigned>(cast<Constant>(*I), 1006f22ef01cSRoman Divacky 0)); 1007f22ef01cSRoman Divacky assert(It != ResolveConstants.end() && It->first == *I); 1008f22ef01cSRoman Divacky NewOp = operator[](It->second); 1009f22ef01cSRoman Divacky } 1010f22ef01cSRoman Divacky 1011f22ef01cSRoman Divacky NewOps.push_back(cast<Constant>(NewOp)); 1012f22ef01cSRoman Divacky } 1013f22ef01cSRoman Divacky 1014f22ef01cSRoman Divacky // Make the new constant. 1015f22ef01cSRoman Divacky Constant *NewC; 1016f22ef01cSRoman Divacky if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 101717a519f9SDimitry Andric NewC = ConstantArray::get(UserCA->getType(), NewOps); 1018f22ef01cSRoman Divacky } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 101917a519f9SDimitry Andric NewC = ConstantStruct::get(UserCS->getType(), NewOps); 1020f22ef01cSRoman Divacky } else if (isa<ConstantVector>(UserC)) { 10212754fe60SDimitry Andric NewC = ConstantVector::get(NewOps); 1022f22ef01cSRoman Divacky } else { 1023f22ef01cSRoman Divacky assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 10243b0f4066SDimitry Andric NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 1025f22ef01cSRoman Divacky } 1026f22ef01cSRoman Divacky 1027f22ef01cSRoman Divacky UserC->replaceAllUsesWith(NewC); 1028f22ef01cSRoman Divacky UserC->destroyConstant(); 1029f22ef01cSRoman Divacky NewOps.clear(); 1030f22ef01cSRoman Divacky } 1031f22ef01cSRoman Divacky 1032f22ef01cSRoman Divacky // Update all ValueHandles, they should be the only users at this point. 1033f22ef01cSRoman Divacky Placeholder->replaceAllUsesWith(RealVal); 1034f22ef01cSRoman Divacky delete Placeholder; 1035f22ef01cSRoman Divacky } 1036f22ef01cSRoman Divacky } 1037f22ef01cSRoman Divacky 10387d523365SDimitry Andric void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) { 1039f22ef01cSRoman Divacky if (Idx == size()) { 104039d628a0SDimitry Andric push_back(MD); 1041f22ef01cSRoman Divacky return; 1042f22ef01cSRoman Divacky } 1043f22ef01cSRoman Divacky 1044f22ef01cSRoman Divacky if (Idx >= size()) 1045f22ef01cSRoman Divacky resize(Idx+1); 1046f22ef01cSRoman Divacky 10477d523365SDimitry Andric TrackingMDRef &OldMD = MetadataPtrs[Idx]; 104839d628a0SDimitry Andric if (!OldMD) { 104939d628a0SDimitry Andric OldMD.reset(MD); 1050f22ef01cSRoman Divacky return; 1051f22ef01cSRoman Divacky } 1052f22ef01cSRoman Divacky 1053f22ef01cSRoman Divacky // If there was a forward reference to this value, replace it. 1054ff0cc061SDimitry Andric TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 105539d628a0SDimitry Andric PrevMD->replaceAllUsesWith(MD); 105639d628a0SDimitry Andric --NumFwdRefs; 1057f22ef01cSRoman Divacky } 1058f22ef01cSRoman Divacky 10597d523365SDimitry Andric Metadata *BitcodeReaderMetadataList::getValueFwdRef(unsigned Idx) { 1060f22ef01cSRoman Divacky if (Idx >= size()) 1061f22ef01cSRoman Divacky resize(Idx + 1); 1062f22ef01cSRoman Divacky 10637d523365SDimitry Andric if (Metadata *MD = MetadataPtrs[Idx]) 106439d628a0SDimitry Andric return MD; 1065f22ef01cSRoman Divacky 1066b09980d1SDimitry Andric // Track forward refs to be resolved later. 1067b09980d1SDimitry Andric if (AnyFwdRefs) { 1068b09980d1SDimitry Andric MinFwdRef = std::min(MinFwdRef, Idx); 1069b09980d1SDimitry Andric MaxFwdRef = std::max(MaxFwdRef, Idx); 1070b09980d1SDimitry Andric } else { 107139d628a0SDimitry Andric AnyFwdRefs = true; 1072b09980d1SDimitry Andric MinFwdRef = MaxFwdRef = Idx; 1073b09980d1SDimitry Andric } 107439d628a0SDimitry Andric ++NumFwdRefs; 1075b09980d1SDimitry Andric 1076b09980d1SDimitry Andric // Create and return a placeholder, which will later be RAUW'd. 1077ff0cc061SDimitry Andric Metadata *MD = MDNode::getTemporary(Context, None).release(); 10787d523365SDimitry Andric MetadataPtrs[Idx].reset(MD); 107939d628a0SDimitry Andric return MD; 108039d628a0SDimitry Andric } 108139d628a0SDimitry Andric 10827d523365SDimitry Andric void BitcodeReaderMetadataList::tryToResolveCycles() { 108339d628a0SDimitry Andric if (!AnyFwdRefs) 108439d628a0SDimitry Andric // Nothing to do. 108539d628a0SDimitry Andric return; 108639d628a0SDimitry Andric 108739d628a0SDimitry Andric if (NumFwdRefs) 108839d628a0SDimitry Andric // Still forward references... can't resolve cycles. 108939d628a0SDimitry Andric return; 109039d628a0SDimitry Andric 109139d628a0SDimitry Andric // Resolve any cycles. 1092b09980d1SDimitry Andric for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) { 10937d523365SDimitry Andric auto &MD = MetadataPtrs[I]; 1094ff0cc061SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD); 1095ff0cc061SDimitry Andric if (!N) 1096ff0cc061SDimitry Andric continue; 1097ff0cc061SDimitry Andric 1098ff0cc061SDimitry Andric assert(!N->isTemporary() && "Unexpected forward reference"); 109939d628a0SDimitry Andric N->resolveCycles(); 110039d628a0SDimitry Andric } 1101b09980d1SDimitry Andric 1102b09980d1SDimitry Andric // Make sure we return early again until there's another forward ref. 1103b09980d1SDimitry Andric AnyFwdRefs = false; 1104f22ef01cSRoman Divacky } 1105f22ef01cSRoman Divacky 110617a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) { 110717a519f9SDimitry Andric // The type table size is always specified correctly. 110817a519f9SDimitry Andric if (ID >= TypeList.size()) 110991bc56edSDimitry Andric return nullptr; 1110f22ef01cSRoman Divacky 111117a519f9SDimitry Andric if (Type *Ty = TypeList[ID]) 111217a519f9SDimitry Andric return Ty; 111317a519f9SDimitry Andric 111417a519f9SDimitry Andric // If we have a forward reference, the only possible case is when it is to a 111517a519f9SDimitry Andric // named struct. Just create a placeholder for now. 111639d628a0SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context); 111739d628a0SDimitry Andric } 111839d628a0SDimitry Andric 111939d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 112039d628a0SDimitry Andric StringRef Name) { 112139d628a0SDimitry Andric auto *Ret = StructType::create(Context, Name); 112239d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 112339d628a0SDimitry Andric return Ret; 112439d628a0SDimitry Andric } 112539d628a0SDimitry Andric 112639d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 112739d628a0SDimitry Andric auto *Ret = StructType::create(Context); 112839d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 112939d628a0SDimitry Andric return Ret; 1130f22ef01cSRoman Divacky } 1131f22ef01cSRoman Divacky 113217a519f9SDimitry Andric 1133f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1134f22ef01cSRoman Divacky // Functions for parsing blocks from the bitcode file 1135f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1136f22ef01cSRoman Divacky 1137139f7f9bSDimitry Andric 1138139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1139139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with 1140139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'. 1141139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1142139f7f9bSDimitry Andric uint64_t EncodedAttrs) { 1143139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1144139f7f9bSDimitry Andric 1145139f7f9bSDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1146139f7f9bSDimitry Andric // the bits above 31 down by 11 bits. 1147139f7f9bSDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1148139f7f9bSDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) && 1149139f7f9bSDimitry Andric "Alignment must be a power of two."); 1150139f7f9bSDimitry Andric 1151139f7f9bSDimitry Andric if (Alignment) 1152139f7f9bSDimitry Andric B.addAlignmentAttr(Alignment); 1153139f7f9bSDimitry Andric B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1154139f7f9bSDimitry Andric (EncodedAttrs & 0xffff)); 1155139f7f9bSDimitry Andric } 1156139f7f9bSDimitry Andric 11578f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttributeBlock() { 1158f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 11598f0fd8f6SDimitry Andric return error("Invalid record"); 1160f22ef01cSRoman Divacky 1161f22ef01cSRoman Divacky if (!MAttributes.empty()) 11628f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1163f22ef01cSRoman Divacky 1164f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1165f22ef01cSRoman Divacky 1166139f7f9bSDimitry Andric SmallVector<AttributeSet, 8> Attrs; 1167f22ef01cSRoman Divacky 1168f22ef01cSRoman Divacky // Read all the records. 1169f22ef01cSRoman Divacky while (1) { 1170139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1171139f7f9bSDimitry Andric 1172139f7f9bSDimitry Andric switch (Entry.Kind) { 1173139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1174139f7f9bSDimitry Andric case BitstreamEntry::Error: 11758f0fd8f6SDimitry Andric return error("Malformed block"); 1176139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 117791bc56edSDimitry Andric return std::error_code(); 1178139f7f9bSDimitry Andric case BitstreamEntry::Record: 1179139f7f9bSDimitry Andric // The interesting case. 1180139f7f9bSDimitry Andric break; 1181f22ef01cSRoman Divacky } 1182f22ef01cSRoman Divacky 1183f22ef01cSRoman Divacky // Read a record. 1184f22ef01cSRoman Divacky Record.clear(); 1185139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1186f22ef01cSRoman Divacky default: // Default behavior: ignore. 1187f22ef01cSRoman Divacky break; 1188139f7f9bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 1189139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1190f22ef01cSRoman Divacky if (Record.size() & 1) 11918f0fd8f6SDimitry Andric return error("Invalid record"); 1192f22ef01cSRoman Divacky 1193f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1194139f7f9bSDimitry Andric AttrBuilder B; 1195139f7f9bSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1]); 1196139f7f9bSDimitry Andric Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 1197f22ef01cSRoman Divacky } 1198f22ef01cSRoman Divacky 1199139f7f9bSDimitry Andric MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1200f22ef01cSRoman Divacky Attrs.clear(); 1201f22ef01cSRoman Divacky break; 1202f22ef01cSRoman Divacky } 1203139f7f9bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 1204139f7f9bSDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i) 1205139f7f9bSDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]); 1206139f7f9bSDimitry Andric 1207139f7f9bSDimitry Andric MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1208139f7f9bSDimitry Andric Attrs.clear(); 1209139f7f9bSDimitry Andric break; 1210139f7f9bSDimitry Andric } 1211139f7f9bSDimitry Andric } 1212139f7f9bSDimitry Andric } 1213139f7f9bSDimitry Andric } 1214139f7f9bSDimitry Andric 1215f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes. 12168f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1217f785676fSDimitry Andric switch (Code) { 1218f785676fSDimitry Andric default: 1219f785676fSDimitry Andric return Attribute::None; 1220f785676fSDimitry Andric case bitc::ATTR_KIND_ALIGNMENT: 1221f785676fSDimitry Andric return Attribute::Alignment; 1222f785676fSDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE: 1223f785676fSDimitry Andric return Attribute::AlwaysInline; 1224875ed548SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY: 1225875ed548SDimitry Andric return Attribute::ArgMemOnly; 1226f785676fSDimitry Andric case bitc::ATTR_KIND_BUILTIN: 1227f785676fSDimitry Andric return Attribute::Builtin; 1228f785676fSDimitry Andric case bitc::ATTR_KIND_BY_VAL: 1229f785676fSDimitry Andric return Attribute::ByVal; 123091bc56edSDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA: 123191bc56edSDimitry Andric return Attribute::InAlloca; 1232f785676fSDimitry Andric case bitc::ATTR_KIND_COLD: 1233f785676fSDimitry Andric return Attribute::Cold; 1234ff0cc061SDimitry Andric case bitc::ATTR_KIND_CONVERGENT: 1235ff0cc061SDimitry Andric return Attribute::Convergent; 12367d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 12377d523365SDimitry Andric return Attribute::InaccessibleMemOnly; 12387d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 12397d523365SDimitry Andric return Attribute::InaccessibleMemOrArgMemOnly; 1240f785676fSDimitry Andric case bitc::ATTR_KIND_INLINE_HINT: 1241f785676fSDimitry Andric return Attribute::InlineHint; 1242f785676fSDimitry Andric case bitc::ATTR_KIND_IN_REG: 1243f785676fSDimitry Andric return Attribute::InReg; 124491bc56edSDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE: 124591bc56edSDimitry Andric return Attribute::JumpTable; 1246f785676fSDimitry Andric case bitc::ATTR_KIND_MIN_SIZE: 1247f785676fSDimitry Andric return Attribute::MinSize; 1248f785676fSDimitry Andric case bitc::ATTR_KIND_NAKED: 1249f785676fSDimitry Andric return Attribute::Naked; 1250f785676fSDimitry Andric case bitc::ATTR_KIND_NEST: 1251f785676fSDimitry Andric return Attribute::Nest; 1252f785676fSDimitry Andric case bitc::ATTR_KIND_NO_ALIAS: 1253f785676fSDimitry Andric return Attribute::NoAlias; 1254f785676fSDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN: 1255f785676fSDimitry Andric return Attribute::NoBuiltin; 1256f785676fSDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE: 1257f785676fSDimitry Andric return Attribute::NoCapture; 1258f785676fSDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE: 1259f785676fSDimitry Andric return Attribute::NoDuplicate; 1260f785676fSDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1261f785676fSDimitry Andric return Attribute::NoImplicitFloat; 1262f785676fSDimitry Andric case bitc::ATTR_KIND_NO_INLINE: 1263f785676fSDimitry Andric return Attribute::NoInline; 12647d523365SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE: 12657d523365SDimitry Andric return Attribute::NoRecurse; 1266f785676fSDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND: 1267f785676fSDimitry Andric return Attribute::NonLazyBind; 126891bc56edSDimitry Andric case bitc::ATTR_KIND_NON_NULL: 126991bc56edSDimitry Andric return Attribute::NonNull; 127091bc56edSDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE: 127191bc56edSDimitry Andric return Attribute::Dereferenceable; 1272ff0cc061SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1273ff0cc061SDimitry Andric return Attribute::DereferenceableOrNull; 1274f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE: 1275f785676fSDimitry Andric return Attribute::NoRedZone; 1276f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RETURN: 1277f785676fSDimitry Andric return Attribute::NoReturn; 1278f785676fSDimitry Andric case bitc::ATTR_KIND_NO_UNWIND: 1279f785676fSDimitry Andric return Attribute::NoUnwind; 1280f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1281f785676fSDimitry Andric return Attribute::OptimizeForSize; 1282f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE: 1283f785676fSDimitry Andric return Attribute::OptimizeNone; 1284f785676fSDimitry Andric case bitc::ATTR_KIND_READ_NONE: 1285f785676fSDimitry Andric return Attribute::ReadNone; 1286f785676fSDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 1287f785676fSDimitry Andric return Attribute::ReadOnly; 1288f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNED: 1289f785676fSDimitry Andric return Attribute::Returned; 1290f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE: 1291f785676fSDimitry Andric return Attribute::ReturnsTwice; 1292f785676fSDimitry Andric case bitc::ATTR_KIND_S_EXT: 1293f785676fSDimitry Andric return Attribute::SExt; 1294f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT: 1295f785676fSDimitry Andric return Attribute::StackAlignment; 1296f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT: 1297f785676fSDimitry Andric return Attribute::StackProtect; 1298f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1299f785676fSDimitry Andric return Attribute::StackProtectReq; 1300f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1301f785676fSDimitry Andric return Attribute::StackProtectStrong; 13028f0fd8f6SDimitry Andric case bitc::ATTR_KIND_SAFESTACK: 13038f0fd8f6SDimitry Andric return Attribute::SafeStack; 1304f785676fSDimitry Andric case bitc::ATTR_KIND_STRUCT_RET: 1305f785676fSDimitry Andric return Attribute::StructRet; 1306f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1307f785676fSDimitry Andric return Attribute::SanitizeAddress; 1308f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD: 1309f785676fSDimitry Andric return Attribute::SanitizeThread; 1310f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY: 1311f785676fSDimitry Andric return Attribute::SanitizeMemory; 1312f785676fSDimitry Andric case bitc::ATTR_KIND_UW_TABLE: 1313f785676fSDimitry Andric return Attribute::UWTable; 1314f785676fSDimitry Andric case bitc::ATTR_KIND_Z_EXT: 1315f785676fSDimitry Andric return Attribute::ZExt; 1316f785676fSDimitry Andric } 1317f785676fSDimitry Andric } 1318f785676fSDimitry Andric 1319ff0cc061SDimitry Andric std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1320ff0cc061SDimitry Andric unsigned &Alignment) { 1321ff0cc061SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero 1322ff0cc061SDimitry Andric // can be used for default alignment. 1323ff0cc061SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1) 13248f0fd8f6SDimitry Andric return error("Invalid alignment value"); 1325ff0cc061SDimitry Andric Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1326ff0cc061SDimitry Andric return std::error_code(); 1327ff0cc061SDimitry Andric } 1328ff0cc061SDimitry Andric 13298f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttrKind(uint64_t Code, 1330f785676fSDimitry Andric Attribute::AttrKind *Kind) { 13318f0fd8f6SDimitry Andric *Kind = getAttrFromCode(Code); 1332f785676fSDimitry Andric if (*Kind == Attribute::None) 13338f0fd8f6SDimitry Andric return error(BitcodeError::CorruptedBitcode, 133439d628a0SDimitry Andric "Unknown attribute kind (" + Twine(Code) + ")"); 133591bc56edSDimitry Andric return std::error_code(); 1336f785676fSDimitry Andric } 1337f785676fSDimitry Andric 13388f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttributeGroupBlock() { 1339139f7f9bSDimitry Andric if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 13408f0fd8f6SDimitry Andric return error("Invalid record"); 1341139f7f9bSDimitry Andric 1342139f7f9bSDimitry Andric if (!MAttributeGroups.empty()) 13438f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1344139f7f9bSDimitry Andric 1345139f7f9bSDimitry Andric SmallVector<uint64_t, 64> Record; 1346139f7f9bSDimitry Andric 1347139f7f9bSDimitry Andric // Read all the records. 1348139f7f9bSDimitry Andric while (1) { 1349139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1350139f7f9bSDimitry Andric 1351139f7f9bSDimitry Andric switch (Entry.Kind) { 1352139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1353139f7f9bSDimitry Andric case BitstreamEntry::Error: 13548f0fd8f6SDimitry Andric return error("Malformed block"); 1355139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 135691bc56edSDimitry Andric return std::error_code(); 1357139f7f9bSDimitry Andric case BitstreamEntry::Record: 1358139f7f9bSDimitry Andric // The interesting case. 1359139f7f9bSDimitry Andric break; 1360139f7f9bSDimitry Andric } 1361139f7f9bSDimitry Andric 1362139f7f9bSDimitry Andric // Read a record. 1363139f7f9bSDimitry Andric Record.clear(); 1364139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1365139f7f9bSDimitry Andric default: // Default behavior: ignore. 1366139f7f9bSDimitry Andric break; 1367139f7f9bSDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1368139f7f9bSDimitry Andric if (Record.size() < 3) 13698f0fd8f6SDimitry Andric return error("Invalid record"); 1370139f7f9bSDimitry Andric 1371139f7f9bSDimitry Andric uint64_t GrpID = Record[0]; 1372139f7f9bSDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1373139f7f9bSDimitry Andric 1374139f7f9bSDimitry Andric AttrBuilder B; 1375139f7f9bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1376139f7f9bSDimitry Andric if (Record[i] == 0) { // Enum attribute 1377f785676fSDimitry Andric Attribute::AttrKind Kind; 13788f0fd8f6SDimitry Andric if (std::error_code EC = parseAttrKind(Record[++i], &Kind)) 1379f785676fSDimitry Andric return EC; 1380f785676fSDimitry Andric 1381f785676fSDimitry Andric B.addAttribute(Kind); 138291bc56edSDimitry Andric } else if (Record[i] == 1) { // Integer attribute 1383f785676fSDimitry Andric Attribute::AttrKind Kind; 13848f0fd8f6SDimitry Andric if (std::error_code EC = parseAttrKind(Record[++i], &Kind)) 1385f785676fSDimitry Andric return EC; 1386f785676fSDimitry Andric if (Kind == Attribute::Alignment) 1387139f7f9bSDimitry Andric B.addAlignmentAttr(Record[++i]); 138891bc56edSDimitry Andric else if (Kind == Attribute::StackAlignment) 1389139f7f9bSDimitry Andric B.addStackAlignmentAttr(Record[++i]); 139091bc56edSDimitry Andric else if (Kind == Attribute::Dereferenceable) 139191bc56edSDimitry Andric B.addDereferenceableAttr(Record[++i]); 1392ff0cc061SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull) 1393ff0cc061SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]); 1394139f7f9bSDimitry Andric } else { // String attribute 1395139f7f9bSDimitry Andric assert((Record[i] == 3 || Record[i] == 4) && 1396139f7f9bSDimitry Andric "Invalid attribute group entry"); 1397139f7f9bSDimitry Andric bool HasValue = (Record[i++] == 4); 1398139f7f9bSDimitry Andric SmallString<64> KindStr; 1399139f7f9bSDimitry Andric SmallString<64> ValStr; 1400139f7f9bSDimitry Andric 1401139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1402139f7f9bSDimitry Andric KindStr += Record[i++]; 1403139f7f9bSDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated"); 1404139f7f9bSDimitry Andric 1405139f7f9bSDimitry Andric if (HasValue) { 1406139f7f9bSDimitry Andric // Has a value associated with it. 1407139f7f9bSDimitry Andric ++i; // Skip the '0' that terminates the "kind" string. 1408139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1409139f7f9bSDimitry Andric ValStr += Record[i++]; 1410139f7f9bSDimitry Andric assert(Record[i] == 0 && "Value string not null terminated"); 1411139f7f9bSDimitry Andric } 1412139f7f9bSDimitry Andric 1413139f7f9bSDimitry Andric B.addAttribute(KindStr.str(), ValStr.str()); 1414139f7f9bSDimitry Andric } 1415139f7f9bSDimitry Andric } 1416139f7f9bSDimitry Andric 1417139f7f9bSDimitry Andric MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 1418139f7f9bSDimitry Andric break; 1419139f7f9bSDimitry Andric } 1420f22ef01cSRoman Divacky } 1421f22ef01cSRoman Divacky } 1422f22ef01cSRoman Divacky } 1423f22ef01cSRoman Divacky 14248f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseTypeTable() { 142517a519f9SDimitry Andric if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 14268f0fd8f6SDimitry Andric return error("Invalid record"); 1427f22ef01cSRoman Divacky 14288f0fd8f6SDimitry Andric return parseTypeTableBody(); 142917a519f9SDimitry Andric } 143017a519f9SDimitry Andric 14318f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseTypeTableBody() { 1432f22ef01cSRoman Divacky if (!TypeList.empty()) 14338f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1434f22ef01cSRoman Divacky 1435f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1436f22ef01cSRoman Divacky unsigned NumRecords = 0; 1437f22ef01cSRoman Divacky 143817a519f9SDimitry Andric SmallString<64> TypeName; 143917a519f9SDimitry Andric 1440f22ef01cSRoman Divacky // Read all the records for this type table. 1441f22ef01cSRoman Divacky while (1) { 1442139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1443139f7f9bSDimitry Andric 1444139f7f9bSDimitry Andric switch (Entry.Kind) { 1445139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1446139f7f9bSDimitry Andric case BitstreamEntry::Error: 14478f0fd8f6SDimitry Andric return error("Malformed block"); 1448139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1449f22ef01cSRoman Divacky if (NumRecords != TypeList.size()) 14508f0fd8f6SDimitry Andric return error("Malformed block"); 145191bc56edSDimitry Andric return std::error_code(); 1452139f7f9bSDimitry Andric case BitstreamEntry::Record: 1453139f7f9bSDimitry Andric // The interesting case. 1454139f7f9bSDimitry Andric break; 1455f22ef01cSRoman Divacky } 1456f22ef01cSRoman Divacky 1457f22ef01cSRoman Divacky // Read a record. 1458f22ef01cSRoman Divacky Record.clear(); 145991bc56edSDimitry Andric Type *ResultTy = nullptr; 1460139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1461f785676fSDimitry Andric default: 14628f0fd8f6SDimitry Andric return error("Invalid value"); 1463f22ef01cSRoman Divacky case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1464f22ef01cSRoman Divacky // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1465f22ef01cSRoman Divacky // type list. This allows us to reserve space. 1466f22ef01cSRoman Divacky if (Record.size() < 1) 14678f0fd8f6SDimitry Andric return error("Invalid record"); 146817a519f9SDimitry Andric TypeList.resize(Record[0]); 1469f22ef01cSRoman Divacky continue; 1470f22ef01cSRoman Divacky case bitc::TYPE_CODE_VOID: // VOID 1471f22ef01cSRoman Divacky ResultTy = Type::getVoidTy(Context); 1472f22ef01cSRoman Divacky break; 1473dff0c46cSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF 1474dff0c46cSDimitry Andric ResultTy = Type::getHalfTy(Context); 1475dff0c46cSDimitry Andric break; 1476f22ef01cSRoman Divacky case bitc::TYPE_CODE_FLOAT: // FLOAT 1477f22ef01cSRoman Divacky ResultTy = Type::getFloatTy(Context); 1478f22ef01cSRoman Divacky break; 1479f22ef01cSRoman Divacky case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1480f22ef01cSRoman Divacky ResultTy = Type::getDoubleTy(Context); 1481f22ef01cSRoman Divacky break; 1482f22ef01cSRoman Divacky case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1483f22ef01cSRoman Divacky ResultTy = Type::getX86_FP80Ty(Context); 1484f22ef01cSRoman Divacky break; 1485f22ef01cSRoman Divacky case bitc::TYPE_CODE_FP128: // FP128 1486f22ef01cSRoman Divacky ResultTy = Type::getFP128Ty(Context); 1487f22ef01cSRoman Divacky break; 1488f22ef01cSRoman Divacky case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1489f22ef01cSRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context); 1490f22ef01cSRoman Divacky break; 1491f22ef01cSRoman Divacky case bitc::TYPE_CODE_LABEL: // LABEL 1492f22ef01cSRoman Divacky ResultTy = Type::getLabelTy(Context); 1493f22ef01cSRoman Divacky break; 1494f22ef01cSRoman Divacky case bitc::TYPE_CODE_METADATA: // METADATA 1495f22ef01cSRoman Divacky ResultTy = Type::getMetadataTy(Context); 1496f22ef01cSRoman Divacky break; 14972754fe60SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX 14982754fe60SDimitry Andric ResultTy = Type::getX86_MMXTy(Context); 14992754fe60SDimitry Andric break; 15007d523365SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN 15017d523365SDimitry Andric ResultTy = Type::getTokenTy(Context); 15027d523365SDimitry Andric break; 1503ff0cc061SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1504f22ef01cSRoman Divacky if (Record.size() < 1) 15058f0fd8f6SDimitry Andric return error("Invalid record"); 1506f22ef01cSRoman Divacky 1507ff0cc061SDimitry Andric uint64_t NumBits = Record[0]; 1508ff0cc061SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS || 1509ff0cc061SDimitry Andric NumBits > IntegerType::MAX_INT_BITS) 15108f0fd8f6SDimitry Andric return error("Bitwidth for integer type out of range"); 1511ff0cc061SDimitry Andric ResultTy = IntegerType::get(Context, NumBits); 1512f22ef01cSRoman Divacky break; 1513ff0cc061SDimitry Andric } 1514f22ef01cSRoman Divacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1515f22ef01cSRoman Divacky // [pointee type, address space] 1516f22ef01cSRoman Divacky if (Record.size() < 1) 15178f0fd8f6SDimitry Andric return error("Invalid record"); 1518f22ef01cSRoman Divacky unsigned AddressSpace = 0; 1519f22ef01cSRoman Divacky if (Record.size() == 2) 1520f22ef01cSRoman Divacky AddressSpace = Record[1]; 152117a519f9SDimitry Andric ResultTy = getTypeByID(Record[0]); 1522ff0cc061SDimitry Andric if (!ResultTy || 1523ff0cc061SDimitry Andric !PointerType::isValidElementType(ResultTy)) 15248f0fd8f6SDimitry Andric return error("Invalid type"); 152517a519f9SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace); 1526f22ef01cSRoman Divacky break; 1527f22ef01cSRoman Divacky } 1528dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: { 15297ae0e2c9SDimitry Andric // FIXME: attrid is dead, remove it in LLVM 4.0 1530f22ef01cSRoman Divacky // FUNCTION: [vararg, attrid, retty, paramty x N] 1531f22ef01cSRoman Divacky if (Record.size() < 3) 15328f0fd8f6SDimitry Andric return error("Invalid record"); 1533dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 153417a519f9SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) { 153517a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 153617a519f9SDimitry Andric ArgTys.push_back(T); 153717a519f9SDimitry Andric else 1538f22ef01cSRoman Divacky break; 1539f22ef01cSRoman Divacky } 154017a519f9SDimitry Andric 154117a519f9SDimitry Andric ResultTy = getTypeByID(Record[2]); 154291bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3) 15438f0fd8f6SDimitry Andric return error("Invalid type"); 154417a519f9SDimitry Andric 154517a519f9SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 154617a519f9SDimitry Andric break; 154717a519f9SDimitry Andric } 1548dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION: { 1549dff0c46cSDimitry Andric // FUNCTION: [vararg, retty, paramty x N] 1550dff0c46cSDimitry Andric if (Record.size() < 2) 15518f0fd8f6SDimitry Andric return error("Invalid record"); 1552dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 1553dff0c46cSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1554ff0cc061SDimitry Andric if (Type *T = getTypeByID(Record[i])) { 1555ff0cc061SDimitry Andric if (!FunctionType::isValidArgumentType(T)) 15568f0fd8f6SDimitry Andric return error("Invalid function argument type"); 1557dff0c46cSDimitry Andric ArgTys.push_back(T); 1558ff0cc061SDimitry Andric } 1559dff0c46cSDimitry Andric else 1560dff0c46cSDimitry Andric break; 1561dff0c46cSDimitry Andric } 1562dff0c46cSDimitry Andric 1563dff0c46cSDimitry Andric ResultTy = getTypeByID(Record[1]); 156491bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2) 15658f0fd8f6SDimitry Andric return error("Invalid type"); 1566dff0c46cSDimitry Andric 1567dff0c46cSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1568dff0c46cSDimitry Andric break; 1569dff0c46cSDimitry Andric } 157017a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1571f22ef01cSRoman Divacky if (Record.size() < 1) 15728f0fd8f6SDimitry Andric return error("Invalid record"); 1573dff0c46cSDimitry Andric SmallVector<Type*, 8> EltTys; 157417a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 157517a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 157617a519f9SDimitry Andric EltTys.push_back(T); 157717a519f9SDimitry Andric else 157817a519f9SDimitry Andric break; 157917a519f9SDimitry Andric } 158017a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 15818f0fd8f6SDimitry Andric return error("Invalid type"); 1582f22ef01cSRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]); 1583f22ef01cSRoman Divacky break; 1584f22ef01cSRoman Divacky } 158517a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 15868f0fd8f6SDimitry Andric if (convertToString(Record, 0, TypeName)) 15878f0fd8f6SDimitry Andric return error("Invalid record"); 158817a519f9SDimitry Andric continue; 158917a519f9SDimitry Andric 159017a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 159117a519f9SDimitry Andric if (Record.size() < 1) 15928f0fd8f6SDimitry Andric return error("Invalid record"); 159317a519f9SDimitry Andric 159417a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 15958f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 159617a519f9SDimitry Andric 159717a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 159817a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 159917a519f9SDimitry Andric if (Res) { 160017a519f9SDimitry Andric Res->setName(TypeName); 160191bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 160217a519f9SDimitry Andric } else // Otherwise, create a new struct. 160339d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 160417a519f9SDimitry Andric TypeName.clear(); 160517a519f9SDimitry Andric 160617a519f9SDimitry Andric SmallVector<Type*, 8> EltTys; 160717a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 160817a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 160917a519f9SDimitry Andric EltTys.push_back(T); 161017a519f9SDimitry Andric else 161117a519f9SDimitry Andric break; 161217a519f9SDimitry Andric } 161317a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16148f0fd8f6SDimitry Andric return error("Invalid record"); 161517a519f9SDimitry Andric Res->setBody(EltTys, Record[0]); 161617a519f9SDimitry Andric ResultTy = Res; 161717a519f9SDimitry Andric break; 161817a519f9SDimitry Andric } 161917a519f9SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 162017a519f9SDimitry Andric if (Record.size() != 1) 16218f0fd8f6SDimitry Andric return error("Invalid record"); 162217a519f9SDimitry Andric 162317a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16248f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 162517a519f9SDimitry Andric 162617a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 162717a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 162817a519f9SDimitry Andric if (Res) { 162917a519f9SDimitry Andric Res->setName(TypeName); 163091bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 163117a519f9SDimitry Andric } else // Otherwise, create a new struct with no body. 163239d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 163317a519f9SDimitry Andric TypeName.clear(); 163417a519f9SDimitry Andric ResultTy = Res; 163517a519f9SDimitry Andric break; 163617a519f9SDimitry Andric } 1637f22ef01cSRoman Divacky case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1638f22ef01cSRoman Divacky if (Record.size() < 2) 16398f0fd8f6SDimitry Andric return error("Invalid record"); 1640ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1641ff0cc061SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 16428f0fd8f6SDimitry Andric return error("Invalid type"); 1643ff0cc061SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]); 1644f22ef01cSRoman Divacky break; 1645f22ef01cSRoman Divacky case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1646f22ef01cSRoman Divacky if (Record.size() < 2) 16478f0fd8f6SDimitry Andric return error("Invalid record"); 164897bc6c73SDimitry Andric if (Record[0] == 0) 16498f0fd8f6SDimitry Andric return error("Invalid vector length"); 1650ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1651ff0cc061SDimitry Andric if (!ResultTy || !StructType::isValidElementType(ResultTy)) 16528f0fd8f6SDimitry Andric return error("Invalid type"); 1653ff0cc061SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0]); 1654f22ef01cSRoman Divacky break; 1655f22ef01cSRoman Divacky } 1656f22ef01cSRoman Divacky 165717a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16588f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 1659ff0cc061SDimitry Andric if (TypeList[NumRecords]) 16608f0fd8f6SDimitry Andric return error( 1661ff0cc061SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced"); 166217a519f9SDimitry Andric assert(ResultTy && "Didn't read a type?"); 166317a519f9SDimitry Andric TypeList[NumRecords++] = ResultTy; 1664f22ef01cSRoman Divacky } 1665f22ef01cSRoman Divacky } 166617a519f9SDimitry Andric 16677d523365SDimitry Andric std::error_code BitcodeReader::parseOperandBundleTags() { 16687d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 16697d523365SDimitry Andric return error("Invalid record"); 16707d523365SDimitry Andric 16717d523365SDimitry Andric if (!BundleTags.empty()) 16727d523365SDimitry Andric return error("Invalid multiple blocks"); 16737d523365SDimitry Andric 16747d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 16757d523365SDimitry Andric 16767d523365SDimitry Andric while (1) { 16777d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 16787d523365SDimitry Andric 16797d523365SDimitry Andric switch (Entry.Kind) { 16807d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 16817d523365SDimitry Andric case BitstreamEntry::Error: 16827d523365SDimitry Andric return error("Malformed block"); 16837d523365SDimitry Andric case BitstreamEntry::EndBlock: 16847d523365SDimitry Andric return std::error_code(); 16857d523365SDimitry Andric case BitstreamEntry::Record: 16867d523365SDimitry Andric // The interesting case. 16877d523365SDimitry Andric break; 16887d523365SDimitry Andric } 16897d523365SDimitry Andric 16907d523365SDimitry Andric // Tags are implicitly mapped to integers by their order. 16917d523365SDimitry Andric 16927d523365SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 16937d523365SDimitry Andric return error("Invalid record"); 16947d523365SDimitry Andric 16957d523365SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N] 16967d523365SDimitry Andric BundleTags.emplace_back(); 16977d523365SDimitry Andric if (convertToString(Record, 0, BundleTags.back())) 16987d523365SDimitry Andric return error("Invalid record"); 16997d523365SDimitry Andric Record.clear(); 17007d523365SDimitry Andric } 17017d523365SDimitry Andric } 17027d523365SDimitry Andric 17037d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record. 17047d523365SDimitry Andric ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 17057d523365SDimitry Andric unsigned NameIndex, Triple &TT) { 17067d523365SDimitry Andric SmallString<128> ValueName; 17077d523365SDimitry Andric if (convertToString(Record, NameIndex, ValueName)) 17087d523365SDimitry Andric return error("Invalid record"); 17097d523365SDimitry Andric unsigned ValueID = Record[0]; 17107d523365SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 17117d523365SDimitry Andric return error("Invalid record"); 17127d523365SDimitry Andric Value *V = ValueList[ValueID]; 17137d523365SDimitry Andric 17147d523365SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size()); 17157d523365SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos) 17167d523365SDimitry Andric return error("Invalid value name"); 17177d523365SDimitry Andric V->setName(NameStr); 17187d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 17197d523365SDimitry Andric if (GO) { 17207d523365SDimitry Andric if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 17217d523365SDimitry Andric if (TT.isOSBinFormatMachO()) 17227d523365SDimitry Andric GO->setComdat(nullptr); 17237d523365SDimitry Andric else 17247d523365SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 17257d523365SDimitry Andric } 17267d523365SDimitry Andric } 17277d523365SDimitry Andric return V; 17287d523365SDimitry Andric } 17297d523365SDimitry Andric 17307d523365SDimitry Andric /// Parse the value symbol table at either the current parsing location or 17317d523365SDimitry Andric /// at the given bit offset if provided. 17327d523365SDimitry Andric std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 17337d523365SDimitry Andric uint64_t CurrentBit; 17347d523365SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level 17357d523365SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level 17367d523365SDimitry Andric // VST (where we don't). 17377d523365SDimitry Andric if (Offset > 0) { 17387d523365SDimitry Andric // Save the current parsing location so we can jump back at the end 17397d523365SDimitry Andric // of the VST read. 17407d523365SDimitry Andric CurrentBit = Stream.GetCurrentBitNo(); 17417d523365SDimitry Andric Stream.JumpToBit(Offset * 32); 17427d523365SDimitry Andric #ifndef NDEBUG 17437d523365SDimitry Andric // Do some checking if we are in debug mode. 17447d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 17457d523365SDimitry Andric assert(Entry.Kind == BitstreamEntry::SubBlock); 17467d523365SDimitry Andric assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 17477d523365SDimitry Andric #else 17487d523365SDimitry Andric // In NDEBUG mode ignore the output so we don't get an unused variable 17497d523365SDimitry Andric // warning. 17507d523365SDimitry Andric Stream.advance(); 17517d523365SDimitry Andric #endif 17527d523365SDimitry Andric } 17537d523365SDimitry Andric 17547d523365SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset 17557d523365SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that 17567d523365SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have 17577d523365SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 17587d523365SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 17597d523365SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock 17607d523365SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same 17617d523365SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 17627d523365SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to 17637d523365SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want 17647d523365SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 17657d523365SDimitry Andric unsigned FuncBitcodeOffsetDelta = 17667d523365SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 17677d523365SDimitry Andric 1768f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 17698f0fd8f6SDimitry Andric return error("Invalid record"); 1770f22ef01cSRoman Divacky 1771f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1772f22ef01cSRoman Divacky 1773ff0cc061SDimitry Andric Triple TT(TheModule->getTargetTriple()); 1774ff0cc061SDimitry Andric 1775f22ef01cSRoman Divacky // Read all the records for this value table. 1776f22ef01cSRoman Divacky SmallString<128> ValueName; 1777f22ef01cSRoman Divacky while (1) { 1778139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1779f22ef01cSRoman Divacky 1780139f7f9bSDimitry Andric switch (Entry.Kind) { 1781139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1782139f7f9bSDimitry Andric case BitstreamEntry::Error: 17838f0fd8f6SDimitry Andric return error("Malformed block"); 1784139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 17857d523365SDimitry Andric if (Offset > 0) 17867d523365SDimitry Andric Stream.JumpToBit(CurrentBit); 178791bc56edSDimitry Andric return std::error_code(); 1788139f7f9bSDimitry Andric case BitstreamEntry::Record: 1789139f7f9bSDimitry Andric // The interesting case. 1790139f7f9bSDimitry Andric break; 1791f22ef01cSRoman Divacky } 1792f22ef01cSRoman Divacky 1793f22ef01cSRoman Divacky // Read a record. 1794f22ef01cSRoman Divacky Record.clear(); 1795139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1796f22ef01cSRoman Divacky default: // Default behavior: unknown type. 1797f22ef01cSRoman Divacky break; 1798f22ef01cSRoman Divacky case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 17997d523365SDimitry Andric ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT); 18007d523365SDimitry Andric if (std::error_code EC = ValOrErr.getError()) 18017d523365SDimitry Andric return EC; 18027d523365SDimitry Andric ValOrErr.get(); 18037d523365SDimitry Andric break; 18047d523365SDimitry Andric } 18057d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 18067d523365SDimitry Andric // VST_FNENTRY: [valueid, offset, namechar x N] 18077d523365SDimitry Andric ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT); 18087d523365SDimitry Andric if (std::error_code EC = ValOrErr.getError()) 18097d523365SDimitry Andric return EC; 18107d523365SDimitry Andric Value *V = ValOrErr.get(); 1811f22ef01cSRoman Divacky 18127d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 18137d523365SDimitry Andric if (!GO) { 18147d523365SDimitry Andric // If this is an alias, need to get the actual Function object 18157d523365SDimitry Andric // it aliases, in order to set up the DeferredFunctionInfo entry below. 18167d523365SDimitry Andric auto *GA = dyn_cast<GlobalAlias>(V); 18177d523365SDimitry Andric if (GA) 18187d523365SDimitry Andric GO = GA->getBaseObject(); 18197d523365SDimitry Andric assert(GO); 1820ff0cc061SDimitry Andric } 18217d523365SDimitry Andric 18227d523365SDimitry Andric uint64_t FuncWordOffset = Record[1]; 18237d523365SDimitry Andric Function *F = dyn_cast<Function>(GO); 18247d523365SDimitry Andric assert(F); 18257d523365SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32; 18267d523365SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 18277d523365SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block. 18287d523365SDimitry Andric // Later when parsing is resumed after function materialization, 18297d523365SDimitry Andric // we can simply skip that last function block. 18307d523365SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit) 18317d523365SDimitry Andric LastFunctionBlockBit = FuncBitOffset; 1832f22ef01cSRoman Divacky break; 1833f22ef01cSRoman Divacky } 1834f22ef01cSRoman Divacky case bitc::VST_CODE_BBENTRY: { 18358f0fd8f6SDimitry Andric if (convertToString(Record, 1, ValueName)) 18368f0fd8f6SDimitry Andric return error("Invalid record"); 1837f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[0]); 183891bc56edSDimitry Andric if (!BB) 18398f0fd8f6SDimitry Andric return error("Invalid record"); 1840f22ef01cSRoman Divacky 1841f22ef01cSRoman Divacky BB->setName(StringRef(ValueName.data(), ValueName.size())); 1842f22ef01cSRoman Divacky ValueName.clear(); 1843f22ef01cSRoman Divacky break; 1844f22ef01cSRoman Divacky } 1845f22ef01cSRoman Divacky } 1846f22ef01cSRoman Divacky } 1847f22ef01cSRoman Divacky } 1848f22ef01cSRoman Divacky 18497d523365SDimitry Andric /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 18507d523365SDimitry Andric std::error_code 18517d523365SDimitry Andric BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) { 18527d523365SDimitry Andric if (Record.size() < 2) 18537d523365SDimitry Andric return error("Invalid record"); 18547d523365SDimitry Andric 18557d523365SDimitry Andric unsigned Kind = Record[0]; 18567d523365SDimitry Andric SmallString<8> Name(Record.begin() + 1, Record.end()); 18577d523365SDimitry Andric 18587d523365SDimitry Andric unsigned NewKind = TheModule->getMDKindID(Name.str()); 18597d523365SDimitry Andric if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 18607d523365SDimitry Andric return error("Conflicting METADATA_KIND records"); 18617d523365SDimitry Andric return std::error_code(); 18627d523365SDimitry Andric } 18637d523365SDimitry Andric 1864ff0cc061SDimitry Andric static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 1865ff0cc061SDimitry Andric 18667d523365SDimitry Andric /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 18677d523365SDimitry Andric /// module level metadata. 18687d523365SDimitry Andric std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) { 1869ff0cc061SDimitry Andric IsMetadataMaterialized = true; 18707d523365SDimitry Andric unsigned NextMetadataNo = MetadataList.size(); 18717d523365SDimitry Andric if (ModuleLevel && SeenModuleValuesRecord) { 18727d523365SDimitry Andric // Now that we are parsing the module level metadata, we want to restart 18737d523365SDimitry Andric // the numbering of the MD values, and replace temp MD created earlier 18747d523365SDimitry Andric // with their real values. If we saw a METADATA_VALUE record then we 18757d523365SDimitry Andric // would have set the MetadataList size to the number specified in that 18767d523365SDimitry Andric // record, to support parsing function-level metadata first, and we need 18777d523365SDimitry Andric // to reset back to 0 to fill the MetadataList in with the parsed module 18787d523365SDimitry Andric // The function-level metadata parsing should have reset the MetadataList 18797d523365SDimitry Andric // size back to the value reported by the METADATA_VALUE record, saved in 18807d523365SDimitry Andric // NumModuleMDs. 18817d523365SDimitry Andric assert(NumModuleMDs == MetadataList.size() && 18827d523365SDimitry Andric "Expected MetadataList to only contain module level values"); 18837d523365SDimitry Andric NextMetadataNo = 0; 18847d523365SDimitry Andric } 1885f22ef01cSRoman Divacky 1886f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 18878f0fd8f6SDimitry Andric return error("Invalid record"); 1888f22ef01cSRoman Divacky 1889f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1890f22ef01cSRoman Divacky 18917d523365SDimitry Andric auto getMD = [&](unsigned ID) -> Metadata * { 18927d523365SDimitry Andric return MetadataList.getValueFwdRef(ID); 18937d523365SDimitry Andric }; 1894ff0cc061SDimitry Andric auto getMDOrNull = [&](unsigned ID) -> Metadata *{ 1895ff0cc061SDimitry Andric if (ID) 1896ff0cc061SDimitry Andric return getMD(ID - 1); 1897ff0cc061SDimitry Andric return nullptr; 1898ff0cc061SDimitry Andric }; 1899ff0cc061SDimitry Andric auto getMDString = [&](unsigned ID) -> MDString *{ 1900ff0cc061SDimitry Andric // This requires that the ID is not really a forward reference. In 1901ff0cc061SDimitry Andric // particular, the MDString must already have been resolved. 1902ff0cc061SDimitry Andric return cast_or_null<MDString>(getMDOrNull(ID)); 1903ff0cc061SDimitry Andric }; 1904ff0cc061SDimitry Andric 1905ff0cc061SDimitry Andric #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \ 1906ff0cc061SDimitry Andric (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1907ff0cc061SDimitry Andric 1908f22ef01cSRoman Divacky // Read all the records. 1909f22ef01cSRoman Divacky while (1) { 1910139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1911139f7f9bSDimitry Andric 1912139f7f9bSDimitry Andric switch (Entry.Kind) { 1913139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1914139f7f9bSDimitry Andric case BitstreamEntry::Error: 19158f0fd8f6SDimitry Andric return error("Malformed block"); 1916139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 19177d523365SDimitry Andric MetadataList.tryToResolveCycles(); 19187d523365SDimitry Andric assert((!(ModuleLevel && SeenModuleValuesRecord) || 19197d523365SDimitry Andric NumModuleMDs == MetadataList.size()) && 19207d523365SDimitry Andric "Inconsistent bitcode: METADATA_VALUES mismatch"); 192191bc56edSDimitry Andric return std::error_code(); 1922139f7f9bSDimitry Andric case BitstreamEntry::Record: 1923139f7f9bSDimitry Andric // The interesting case. 1924139f7f9bSDimitry Andric break; 1925f22ef01cSRoman Divacky } 1926f22ef01cSRoman Divacky 1927f22ef01cSRoman Divacky // Read a record. 1928f22ef01cSRoman Divacky Record.clear(); 1929139f7f9bSDimitry Andric unsigned Code = Stream.readRecord(Entry.ID, Record); 193039d628a0SDimitry Andric bool IsDistinct = false; 1931e580952dSDimitry Andric switch (Code) { 1932f22ef01cSRoman Divacky default: // Default behavior: ignore. 1933f22ef01cSRoman Divacky break; 1934f22ef01cSRoman Divacky case bitc::METADATA_NAME: { 1935139f7f9bSDimitry Andric // Read name of the named metadata. 19367ae0e2c9SDimitry Andric SmallString<8> Name(Record.begin(), Record.end()); 1937f22ef01cSRoman Divacky Record.clear(); 1938f22ef01cSRoman Divacky Code = Stream.ReadCode(); 1939f22ef01cSRoman Divacky 1940139f7f9bSDimitry Andric unsigned NextBitCode = Stream.readRecord(Code, Record); 194197bc6c73SDimitry Andric if (NextBitCode != bitc::METADATA_NAMED_NODE) 19428f0fd8f6SDimitry Andric return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 1943f22ef01cSRoman Divacky 1944f22ef01cSRoman Divacky // Read named metadata elements. 1945f22ef01cSRoman Divacky unsigned Size = Record.size(); 1946e580952dSDimitry Andric NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1947f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) { 19487d523365SDimitry Andric MDNode *MD = 19497d523365SDimitry Andric dyn_cast_or_null<MDNode>(MetadataList.getValueFwdRef(Record[i])); 195091bc56edSDimitry Andric if (!MD) 19518f0fd8f6SDimitry Andric return error("Invalid record"); 1952e580952dSDimitry Andric NMD->addOperand(MD); 1953f22ef01cSRoman Divacky } 1954f22ef01cSRoman Divacky break; 1955f22ef01cSRoman Divacky } 195639d628a0SDimitry Andric case bitc::METADATA_OLD_FN_NODE: { 195739d628a0SDimitry Andric // FIXME: Remove in 4.0. 195839d628a0SDimitry Andric // This is a LocalAsMetadata record, the only type of function-local 195939d628a0SDimitry Andric // metadata. 1960ffd1746dSEd Schouten if (Record.size() % 2 == 1) 19618f0fd8f6SDimitry Andric return error("Invalid record"); 196239d628a0SDimitry Andric 196339d628a0SDimitry Andric // If this isn't a LocalAsMetadata record, we're dropping it. This used 196439d628a0SDimitry Andric // to be legal, but there's no upgrade path. 196539d628a0SDimitry Andric auto dropRecord = [&] { 19667d523365SDimitry Andric MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++); 196739d628a0SDimitry Andric }; 196839d628a0SDimitry Andric if (Record.size() != 2) { 196939d628a0SDimitry Andric dropRecord(); 197039d628a0SDimitry Andric break; 197139d628a0SDimitry Andric } 197239d628a0SDimitry Andric 197339d628a0SDimitry Andric Type *Ty = getTypeByID(Record[0]); 197439d628a0SDimitry Andric if (Ty->isMetadataTy() || Ty->isVoidTy()) { 197539d628a0SDimitry Andric dropRecord(); 197639d628a0SDimitry Andric break; 197739d628a0SDimitry Andric } 197839d628a0SDimitry Andric 19797d523365SDimitry Andric MetadataList.assignValue( 198039d628a0SDimitry Andric LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 19817d523365SDimitry Andric NextMetadataNo++); 198239d628a0SDimitry Andric break; 198339d628a0SDimitry Andric } 198439d628a0SDimitry Andric case bitc::METADATA_OLD_NODE: { 198539d628a0SDimitry Andric // FIXME: Remove in 4.0. 198639d628a0SDimitry Andric if (Record.size() % 2 == 1) 19878f0fd8f6SDimitry Andric return error("Invalid record"); 1988f22ef01cSRoman Divacky 1989f22ef01cSRoman Divacky unsigned Size = Record.size(); 199039d628a0SDimitry Andric SmallVector<Metadata *, 8> Elts; 1991f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; i += 2) { 19926122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[i]); 1993f785676fSDimitry Andric if (!Ty) 19948f0fd8f6SDimitry Andric return error("Invalid record"); 1995f22ef01cSRoman Divacky if (Ty->isMetadataTy()) 19967d523365SDimitry Andric Elts.push_back(MetadataList.getValueFwdRef(Record[i + 1])); 199739d628a0SDimitry Andric else if (!Ty->isVoidTy()) { 199839d628a0SDimitry Andric auto *MD = 199939d628a0SDimitry Andric ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 200039d628a0SDimitry Andric assert(isa<ConstantAsMetadata>(MD) && 200139d628a0SDimitry Andric "Expected non-function-local metadata"); 200239d628a0SDimitry Andric Elts.push_back(MD); 200339d628a0SDimitry Andric } else 200491bc56edSDimitry Andric Elts.push_back(nullptr); 2005f22ef01cSRoman Divacky } 20067d523365SDimitry Andric MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++); 200739d628a0SDimitry Andric break; 200839d628a0SDimitry Andric } 200939d628a0SDimitry Andric case bitc::METADATA_VALUE: { 201039d628a0SDimitry Andric if (Record.size() != 2) 20118f0fd8f6SDimitry Andric return error("Invalid record"); 201239d628a0SDimitry Andric 201339d628a0SDimitry Andric Type *Ty = getTypeByID(Record[0]); 201439d628a0SDimitry Andric if (Ty->isMetadataTy() || Ty->isVoidTy()) 20158f0fd8f6SDimitry Andric return error("Invalid record"); 201639d628a0SDimitry Andric 20177d523365SDimitry Andric MetadataList.assignValue( 201839d628a0SDimitry Andric ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 20197d523365SDimitry Andric NextMetadataNo++); 202039d628a0SDimitry Andric break; 202139d628a0SDimitry Andric } 202239d628a0SDimitry Andric case bitc::METADATA_DISTINCT_NODE: 202339d628a0SDimitry Andric IsDistinct = true; 202439d628a0SDimitry Andric // fallthrough... 202539d628a0SDimitry Andric case bitc::METADATA_NODE: { 202639d628a0SDimitry Andric SmallVector<Metadata *, 8> Elts; 202739d628a0SDimitry Andric Elts.reserve(Record.size()); 202839d628a0SDimitry Andric for (unsigned ID : Record) 20297d523365SDimitry Andric Elts.push_back(ID ? MetadataList.getValueFwdRef(ID - 1) : nullptr); 20307d523365SDimitry Andric MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 203139d628a0SDimitry Andric : MDNode::get(Context, Elts), 20327d523365SDimitry Andric NextMetadataNo++); 203339d628a0SDimitry Andric break; 203439d628a0SDimitry Andric } 203539d628a0SDimitry Andric case bitc::METADATA_LOCATION: { 203639d628a0SDimitry Andric if (Record.size() != 5) 20378f0fd8f6SDimitry Andric return error("Invalid record"); 203839d628a0SDimitry Andric 203939d628a0SDimitry Andric unsigned Line = Record[1]; 204039d628a0SDimitry Andric unsigned Column = Record[2]; 20417d523365SDimitry Andric MDNode *Scope = cast<MDNode>(MetadataList.getValueFwdRef(Record[3])); 204239d628a0SDimitry Andric Metadata *InlinedAt = 20437d523365SDimitry Andric Record[4] ? MetadataList.getValueFwdRef(Record[4] - 1) : nullptr; 20447d523365SDimitry Andric MetadataList.assignValue( 2045ff0cc061SDimitry Andric GET_OR_DISTINCT(DILocation, Record[0], 2046ff0cc061SDimitry Andric (Context, Line, Column, Scope, InlinedAt)), 20477d523365SDimitry Andric NextMetadataNo++); 2048ff0cc061SDimitry Andric break; 2049ff0cc061SDimitry Andric } 2050ff0cc061SDimitry Andric case bitc::METADATA_GENERIC_DEBUG: { 2051ff0cc061SDimitry Andric if (Record.size() < 4) 20528f0fd8f6SDimitry Andric return error("Invalid record"); 2053ff0cc061SDimitry Andric 2054ff0cc061SDimitry Andric unsigned Tag = Record[1]; 2055ff0cc061SDimitry Andric unsigned Version = Record[2]; 2056ff0cc061SDimitry Andric 2057ff0cc061SDimitry Andric if (Tag >= 1u << 16 || Version != 0) 20588f0fd8f6SDimitry Andric return error("Invalid record"); 2059ff0cc061SDimitry Andric 2060ff0cc061SDimitry Andric auto *Header = getMDString(Record[3]); 2061ff0cc061SDimitry Andric SmallVector<Metadata *, 8> DwarfOps; 2062ff0cc061SDimitry Andric for (unsigned I = 4, E = Record.size(); I != E; ++I) 20637d523365SDimitry Andric DwarfOps.push_back( 20647d523365SDimitry Andric Record[I] ? MetadataList.getValueFwdRef(Record[I] - 1) : nullptr); 20657d523365SDimitry Andric MetadataList.assignValue( 20667d523365SDimitry Andric GET_OR_DISTINCT(GenericDINode, Record[0], 2067ff0cc061SDimitry Andric (Context, Tag, Header, DwarfOps)), 20687d523365SDimitry Andric NextMetadataNo++); 2069ff0cc061SDimitry Andric break; 2070ff0cc061SDimitry Andric } 2071ff0cc061SDimitry Andric case bitc::METADATA_SUBRANGE: { 2072ff0cc061SDimitry Andric if (Record.size() != 3) 20738f0fd8f6SDimitry Andric return error("Invalid record"); 2074ff0cc061SDimitry Andric 20757d523365SDimitry Andric MetadataList.assignValue( 2076ff0cc061SDimitry Andric GET_OR_DISTINCT(DISubrange, Record[0], 2077ff0cc061SDimitry Andric (Context, Record[1], unrotateSign(Record[2]))), 20787d523365SDimitry Andric NextMetadataNo++); 2079ff0cc061SDimitry Andric break; 2080ff0cc061SDimitry Andric } 2081ff0cc061SDimitry Andric case bitc::METADATA_ENUMERATOR: { 2082ff0cc061SDimitry Andric if (Record.size() != 3) 20838f0fd8f6SDimitry Andric return error("Invalid record"); 2084ff0cc061SDimitry Andric 20857d523365SDimitry Andric MetadataList.assignValue( 20867d523365SDimitry Andric GET_OR_DISTINCT( 20877d523365SDimitry Andric DIEnumerator, Record[0], 20887d523365SDimitry Andric (Context, unrotateSign(Record[1]), getMDString(Record[2]))), 20897d523365SDimitry Andric NextMetadataNo++); 2090ff0cc061SDimitry Andric break; 2091ff0cc061SDimitry Andric } 2092ff0cc061SDimitry Andric case bitc::METADATA_BASIC_TYPE: { 2093ff0cc061SDimitry Andric if (Record.size() != 6) 20948f0fd8f6SDimitry Andric return error("Invalid record"); 2095ff0cc061SDimitry Andric 20967d523365SDimitry Andric MetadataList.assignValue( 2097ff0cc061SDimitry Andric GET_OR_DISTINCT(DIBasicType, Record[0], 2098ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2099ff0cc061SDimitry Andric Record[3], Record[4], Record[5])), 21007d523365SDimitry Andric NextMetadataNo++); 2101ff0cc061SDimitry Andric break; 2102ff0cc061SDimitry Andric } 2103ff0cc061SDimitry Andric case bitc::METADATA_DERIVED_TYPE: { 2104ff0cc061SDimitry Andric if (Record.size() != 12) 21058f0fd8f6SDimitry Andric return error("Invalid record"); 2106ff0cc061SDimitry Andric 21077d523365SDimitry Andric MetadataList.assignValue( 2108ff0cc061SDimitry Andric GET_OR_DISTINCT(DIDerivedType, Record[0], 2109ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2110ff0cc061SDimitry Andric getMDOrNull(Record[3]), Record[4], 2111ff0cc061SDimitry Andric getMDOrNull(Record[5]), getMDOrNull(Record[6]), 2112ff0cc061SDimitry Andric Record[7], Record[8], Record[9], Record[10], 2113ff0cc061SDimitry Andric getMDOrNull(Record[11]))), 21147d523365SDimitry Andric NextMetadataNo++); 2115ff0cc061SDimitry Andric break; 2116ff0cc061SDimitry Andric } 2117ff0cc061SDimitry Andric case bitc::METADATA_COMPOSITE_TYPE: { 2118ff0cc061SDimitry Andric if (Record.size() != 16) 21198f0fd8f6SDimitry Andric return error("Invalid record"); 2120ff0cc061SDimitry Andric 21217d523365SDimitry Andric MetadataList.assignValue( 2122ff0cc061SDimitry Andric GET_OR_DISTINCT(DICompositeType, Record[0], 2123ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2124ff0cc061SDimitry Andric getMDOrNull(Record[3]), Record[4], 2125ff0cc061SDimitry Andric getMDOrNull(Record[5]), getMDOrNull(Record[6]), 2126ff0cc061SDimitry Andric Record[7], Record[8], Record[9], Record[10], 2127ff0cc061SDimitry Andric getMDOrNull(Record[11]), Record[12], 2128ff0cc061SDimitry Andric getMDOrNull(Record[13]), getMDOrNull(Record[14]), 2129ff0cc061SDimitry Andric getMDString(Record[15]))), 21307d523365SDimitry Andric NextMetadataNo++); 2131ff0cc061SDimitry Andric break; 2132ff0cc061SDimitry Andric } 2133ff0cc061SDimitry Andric case bitc::METADATA_SUBROUTINE_TYPE: { 2134ff0cc061SDimitry Andric if (Record.size() != 3) 21358f0fd8f6SDimitry Andric return error("Invalid record"); 2136ff0cc061SDimitry Andric 21377d523365SDimitry Andric MetadataList.assignValue( 2138ff0cc061SDimitry Andric GET_OR_DISTINCT(DISubroutineType, Record[0], 2139ff0cc061SDimitry Andric (Context, Record[1], getMDOrNull(Record[2]))), 21407d523365SDimitry Andric NextMetadataNo++); 2141ff0cc061SDimitry Andric break; 2142ff0cc061SDimitry Andric } 21433dac3a9bSDimitry Andric 21443dac3a9bSDimitry Andric case bitc::METADATA_MODULE: { 21453dac3a9bSDimitry Andric if (Record.size() != 6) 21463dac3a9bSDimitry Andric return error("Invalid record"); 21473dac3a9bSDimitry Andric 21487d523365SDimitry Andric MetadataList.assignValue( 21493dac3a9bSDimitry Andric GET_OR_DISTINCT(DIModule, Record[0], 21503dac3a9bSDimitry Andric (Context, getMDOrNull(Record[1]), 21513dac3a9bSDimitry Andric getMDString(Record[2]), getMDString(Record[3]), 21523dac3a9bSDimitry Andric getMDString(Record[4]), getMDString(Record[5]))), 21537d523365SDimitry Andric NextMetadataNo++); 21543dac3a9bSDimitry Andric break; 21553dac3a9bSDimitry Andric } 21563dac3a9bSDimitry Andric 2157ff0cc061SDimitry Andric case bitc::METADATA_FILE: { 2158ff0cc061SDimitry Andric if (Record.size() != 3) 21598f0fd8f6SDimitry Andric return error("Invalid record"); 2160ff0cc061SDimitry Andric 21617d523365SDimitry Andric MetadataList.assignValue( 2162ff0cc061SDimitry Andric GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]), 2163ff0cc061SDimitry Andric getMDString(Record[2]))), 21647d523365SDimitry Andric NextMetadataNo++); 2165ff0cc061SDimitry Andric break; 2166ff0cc061SDimitry Andric } 2167ff0cc061SDimitry Andric case bitc::METADATA_COMPILE_UNIT: { 21687d523365SDimitry Andric if (Record.size() < 14 || Record.size() > 16) 21698f0fd8f6SDimitry Andric return error("Invalid record"); 2170ff0cc061SDimitry Andric 21717d523365SDimitry Andric // Ignore Record[0], which indicates whether this compile unit is 21727d523365SDimitry Andric // distinct. It's always distinct. 21737d523365SDimitry Andric MetadataList.assignValue( 21747d523365SDimitry Andric DICompileUnit::getDistinct( 21757d523365SDimitry Andric Context, Record[1], getMDOrNull(Record[2]), 21768f0fd8f6SDimitry Andric getMDString(Record[3]), Record[4], getMDString(Record[5]), 21778f0fd8f6SDimitry Andric Record[6], getMDString(Record[7]), Record[8], 2178ff0cc061SDimitry Andric getMDOrNull(Record[9]), getMDOrNull(Record[10]), 2179ff0cc061SDimitry Andric getMDOrNull(Record[11]), getMDOrNull(Record[12]), 21807d523365SDimitry Andric getMDOrNull(Record[13]), 21817d523365SDimitry Andric Record.size() <= 15 ? 0 : getMDOrNull(Record[15]), 21827d523365SDimitry Andric Record.size() <= 14 ? 0 : Record[14]), 21837d523365SDimitry Andric NextMetadataNo++); 2184ff0cc061SDimitry Andric break; 2185ff0cc061SDimitry Andric } 2186ff0cc061SDimitry Andric case bitc::METADATA_SUBPROGRAM: { 21877d523365SDimitry Andric if (Record.size() != 18 && Record.size() != 19) 21888f0fd8f6SDimitry Andric return error("Invalid record"); 2189ff0cc061SDimitry Andric 21907d523365SDimitry Andric bool HasFn = Record.size() == 19; 21917d523365SDimitry Andric DISubprogram *SP = GET_OR_DISTINCT( 21927d523365SDimitry Andric DISubprogram, 21937d523365SDimitry Andric Record[0] || Record[8], // All definitions should be distinct. 2194ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 2195ff0cc061SDimitry Andric getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 2196ff0cc061SDimitry Andric getMDOrNull(Record[6]), Record[7], Record[8], Record[9], 2197ff0cc061SDimitry Andric getMDOrNull(Record[10]), Record[11], Record[12], Record[13], 21987d523365SDimitry Andric Record[14], getMDOrNull(Record[15 + HasFn]), 21997d523365SDimitry Andric getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn]))); 22007d523365SDimitry Andric MetadataList.assignValue(SP, NextMetadataNo++); 22017d523365SDimitry Andric 22027d523365SDimitry Andric // Upgrade sp->function mapping to function->sp mapping. 22037d523365SDimitry Andric if (HasFn && Record[15]) { 22047d523365SDimitry Andric if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15]))) 22057d523365SDimitry Andric if (auto *F = dyn_cast<Function>(CMD->getValue())) { 22067d523365SDimitry Andric if (F->isMaterializable()) 22077d523365SDimitry Andric // Defer until materialized; unmaterialized functions may not have 22087d523365SDimitry Andric // metadata. 22097d523365SDimitry Andric FunctionsWithSPs[F] = SP; 22107d523365SDimitry Andric else if (!F->empty()) 22117d523365SDimitry Andric F->setSubprogram(SP); 22127d523365SDimitry Andric } 22137d523365SDimitry Andric } 2214ff0cc061SDimitry Andric break; 2215ff0cc061SDimitry Andric } 2216ff0cc061SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK: { 2217ff0cc061SDimitry Andric if (Record.size() != 5) 22188f0fd8f6SDimitry Andric return error("Invalid record"); 2219ff0cc061SDimitry Andric 22207d523365SDimitry Andric MetadataList.assignValue( 2221ff0cc061SDimitry Andric GET_OR_DISTINCT(DILexicalBlock, Record[0], 2222ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2223ff0cc061SDimitry Andric getMDOrNull(Record[2]), Record[3], Record[4])), 22247d523365SDimitry Andric NextMetadataNo++); 2225ff0cc061SDimitry Andric break; 2226ff0cc061SDimitry Andric } 2227ff0cc061SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK_FILE: { 2228ff0cc061SDimitry Andric if (Record.size() != 4) 22298f0fd8f6SDimitry Andric return error("Invalid record"); 2230ff0cc061SDimitry Andric 22317d523365SDimitry Andric MetadataList.assignValue( 2232ff0cc061SDimitry Andric GET_OR_DISTINCT(DILexicalBlockFile, Record[0], 2233ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2234ff0cc061SDimitry Andric getMDOrNull(Record[2]), Record[3])), 22357d523365SDimitry Andric NextMetadataNo++); 2236ff0cc061SDimitry Andric break; 2237ff0cc061SDimitry Andric } 2238ff0cc061SDimitry Andric case bitc::METADATA_NAMESPACE: { 2239ff0cc061SDimitry Andric if (Record.size() != 5) 22408f0fd8f6SDimitry Andric return error("Invalid record"); 2241ff0cc061SDimitry Andric 22427d523365SDimitry Andric MetadataList.assignValue( 2243ff0cc061SDimitry Andric GET_OR_DISTINCT(DINamespace, Record[0], 2244ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2245ff0cc061SDimitry Andric getMDOrNull(Record[2]), getMDString(Record[3]), 2246ff0cc061SDimitry Andric Record[4])), 22477d523365SDimitry Andric NextMetadataNo++); 22487d523365SDimitry Andric break; 22497d523365SDimitry Andric } 22507d523365SDimitry Andric case bitc::METADATA_MACRO: { 22517d523365SDimitry Andric if (Record.size() != 5) 22527d523365SDimitry Andric return error("Invalid record"); 22537d523365SDimitry Andric 22547d523365SDimitry Andric MetadataList.assignValue( 22557d523365SDimitry Andric GET_OR_DISTINCT(DIMacro, Record[0], 22567d523365SDimitry Andric (Context, Record[1], Record[2], 22577d523365SDimitry Andric getMDString(Record[3]), getMDString(Record[4]))), 22587d523365SDimitry Andric NextMetadataNo++); 22597d523365SDimitry Andric break; 22607d523365SDimitry Andric } 22617d523365SDimitry Andric case bitc::METADATA_MACRO_FILE: { 22627d523365SDimitry Andric if (Record.size() != 5) 22637d523365SDimitry Andric return error("Invalid record"); 22647d523365SDimitry Andric 22657d523365SDimitry Andric MetadataList.assignValue( 22667d523365SDimitry Andric GET_OR_DISTINCT(DIMacroFile, Record[0], 22677d523365SDimitry Andric (Context, Record[1], Record[2], 22687d523365SDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 22697d523365SDimitry Andric NextMetadataNo++); 2270ff0cc061SDimitry Andric break; 2271ff0cc061SDimitry Andric } 2272ff0cc061SDimitry Andric case bitc::METADATA_TEMPLATE_TYPE: { 2273ff0cc061SDimitry Andric if (Record.size() != 3) 22748f0fd8f6SDimitry Andric return error("Invalid record"); 2275ff0cc061SDimitry Andric 22767d523365SDimitry Andric MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 2277ff0cc061SDimitry Andric Record[0], 2278ff0cc061SDimitry Andric (Context, getMDString(Record[1]), 2279ff0cc061SDimitry Andric getMDOrNull(Record[2]))), 22807d523365SDimitry Andric NextMetadataNo++); 2281ff0cc061SDimitry Andric break; 2282ff0cc061SDimitry Andric } 2283ff0cc061SDimitry Andric case bitc::METADATA_TEMPLATE_VALUE: { 2284ff0cc061SDimitry Andric if (Record.size() != 5) 22858f0fd8f6SDimitry Andric return error("Invalid record"); 2286ff0cc061SDimitry Andric 22877d523365SDimitry Andric MetadataList.assignValue( 2288ff0cc061SDimitry Andric GET_OR_DISTINCT(DITemplateValueParameter, Record[0], 2289ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2290ff0cc061SDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 22917d523365SDimitry Andric NextMetadataNo++); 2292ff0cc061SDimitry Andric break; 2293ff0cc061SDimitry Andric } 2294ff0cc061SDimitry Andric case bitc::METADATA_GLOBAL_VAR: { 2295ff0cc061SDimitry Andric if (Record.size() != 11) 22968f0fd8f6SDimitry Andric return error("Invalid record"); 2297ff0cc061SDimitry Andric 22987d523365SDimitry Andric MetadataList.assignValue( 2299ff0cc061SDimitry Andric GET_OR_DISTINCT(DIGlobalVariable, Record[0], 2300ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2301ff0cc061SDimitry Andric getMDString(Record[2]), getMDString(Record[3]), 2302ff0cc061SDimitry Andric getMDOrNull(Record[4]), Record[5], 2303ff0cc061SDimitry Andric getMDOrNull(Record[6]), Record[7], Record[8], 2304ff0cc061SDimitry Andric getMDOrNull(Record[9]), getMDOrNull(Record[10]))), 23057d523365SDimitry Andric NextMetadataNo++); 2306ff0cc061SDimitry Andric break; 2307ff0cc061SDimitry Andric } 2308ff0cc061SDimitry Andric case bitc::METADATA_LOCAL_VAR: { 2309ff0cc061SDimitry Andric // 10th field is for the obseleted 'inlinedAt:' field. 23107d523365SDimitry Andric if (Record.size() < 8 || Record.size() > 10) 23118f0fd8f6SDimitry Andric return error("Invalid record"); 2312ff0cc061SDimitry Andric 23137d523365SDimitry Andric // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 23147d523365SDimitry Andric // DW_TAG_arg_variable. 23157d523365SDimitry Andric bool HasTag = Record.size() > 8; 23167d523365SDimitry Andric MetadataList.assignValue( 2317ff0cc061SDimitry Andric GET_OR_DISTINCT(DILocalVariable, Record[0], 23187d523365SDimitry Andric (Context, getMDOrNull(Record[1 + HasTag]), 23197d523365SDimitry Andric getMDString(Record[2 + HasTag]), 23207d523365SDimitry Andric getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 23217d523365SDimitry Andric getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag], 23227d523365SDimitry Andric Record[7 + HasTag])), 23237d523365SDimitry Andric NextMetadataNo++); 2324ff0cc061SDimitry Andric break; 2325ff0cc061SDimitry Andric } 2326ff0cc061SDimitry Andric case bitc::METADATA_EXPRESSION: { 2327ff0cc061SDimitry Andric if (Record.size() < 1) 23288f0fd8f6SDimitry Andric return error("Invalid record"); 2329ff0cc061SDimitry Andric 23307d523365SDimitry Andric MetadataList.assignValue( 2331ff0cc061SDimitry Andric GET_OR_DISTINCT(DIExpression, Record[0], 2332ff0cc061SDimitry Andric (Context, makeArrayRef(Record).slice(1))), 23337d523365SDimitry Andric NextMetadataNo++); 2334ff0cc061SDimitry Andric break; 2335ff0cc061SDimitry Andric } 2336ff0cc061SDimitry Andric case bitc::METADATA_OBJC_PROPERTY: { 2337ff0cc061SDimitry Andric if (Record.size() != 8) 23388f0fd8f6SDimitry Andric return error("Invalid record"); 2339ff0cc061SDimitry Andric 23407d523365SDimitry Andric MetadataList.assignValue( 2341ff0cc061SDimitry Andric GET_OR_DISTINCT(DIObjCProperty, Record[0], 2342ff0cc061SDimitry Andric (Context, getMDString(Record[1]), 2343ff0cc061SDimitry Andric getMDOrNull(Record[2]), Record[3], 2344ff0cc061SDimitry Andric getMDString(Record[4]), getMDString(Record[5]), 2345ff0cc061SDimitry Andric Record[6], getMDOrNull(Record[7]))), 23467d523365SDimitry Andric NextMetadataNo++); 2347ff0cc061SDimitry Andric break; 2348ff0cc061SDimitry Andric } 2349ff0cc061SDimitry Andric case bitc::METADATA_IMPORTED_ENTITY: { 2350ff0cc061SDimitry Andric if (Record.size() != 6) 23518f0fd8f6SDimitry Andric return error("Invalid record"); 2352ff0cc061SDimitry Andric 23537d523365SDimitry Andric MetadataList.assignValue( 2354ff0cc061SDimitry Andric GET_OR_DISTINCT(DIImportedEntity, Record[0], 2355ff0cc061SDimitry Andric (Context, Record[1], getMDOrNull(Record[2]), 2356ff0cc061SDimitry Andric getMDOrNull(Record[3]), Record[4], 2357ff0cc061SDimitry Andric getMDString(Record[5]))), 23587d523365SDimitry Andric NextMetadataNo++); 2359f22ef01cSRoman Divacky break; 2360f22ef01cSRoman Divacky } 2361f22ef01cSRoman Divacky case bitc::METADATA_STRING: { 236291bc56edSDimitry Andric std::string String(Record.begin(), Record.end()); 236391bc56edSDimitry Andric llvm::UpgradeMDStringConstant(String); 236439d628a0SDimitry Andric Metadata *MD = MDString::get(Context, String); 23657d523365SDimitry Andric MetadataList.assignValue(MD, NextMetadataNo++); 2366f22ef01cSRoman Divacky break; 2367f22ef01cSRoman Divacky } 2368f22ef01cSRoman Divacky case bitc::METADATA_KIND: { 23697d523365SDimitry Andric // Support older bitcode files that had METADATA_KIND records in a 23707d523365SDimitry Andric // block with METADATA_BLOCK_ID. 23717d523365SDimitry Andric if (std::error_code EC = parseMetadataKindRecord(Record)) 23727d523365SDimitry Andric return EC; 2373f22ef01cSRoman Divacky break; 2374f22ef01cSRoman Divacky } 2375f22ef01cSRoman Divacky } 2376f22ef01cSRoman Divacky } 2377ff0cc061SDimitry Andric #undef GET_OR_DISTINCT 2378f22ef01cSRoman Divacky } 2379f22ef01cSRoman Divacky 23807d523365SDimitry Andric /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 23817d523365SDimitry Andric std::error_code BitcodeReader::parseMetadataKinds() { 23827d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 23837d523365SDimitry Andric return error("Invalid record"); 23847d523365SDimitry Andric 23857d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 23867d523365SDimitry Andric 23877d523365SDimitry Andric // Read all the records. 23887d523365SDimitry Andric while (1) { 23897d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 23907d523365SDimitry Andric 23917d523365SDimitry Andric switch (Entry.Kind) { 23927d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 23937d523365SDimitry Andric case BitstreamEntry::Error: 23947d523365SDimitry Andric return error("Malformed block"); 23957d523365SDimitry Andric case BitstreamEntry::EndBlock: 23967d523365SDimitry Andric return std::error_code(); 23977d523365SDimitry Andric case BitstreamEntry::Record: 23987d523365SDimitry Andric // The interesting case. 23997d523365SDimitry Andric break; 24007d523365SDimitry Andric } 24017d523365SDimitry Andric 24027d523365SDimitry Andric // Read a record. 24037d523365SDimitry Andric Record.clear(); 24047d523365SDimitry Andric unsigned Code = Stream.readRecord(Entry.ID, Record); 24057d523365SDimitry Andric switch (Code) { 24067d523365SDimitry Andric default: // Default behavior: ignore. 24077d523365SDimitry Andric break; 24087d523365SDimitry Andric case bitc::METADATA_KIND: { 24097d523365SDimitry Andric if (std::error_code EC = parseMetadataKindRecord(Record)) 24107d523365SDimitry Andric return EC; 24117d523365SDimitry Andric break; 24127d523365SDimitry Andric } 24137d523365SDimitry Andric } 24147d523365SDimitry Andric } 24157d523365SDimitry Andric } 24167d523365SDimitry Andric 24178f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR 24188f0fd8f6SDimitry Andric /// encoding. 24193861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2420f22ef01cSRoman Divacky if ((V & 1) == 0) 2421f22ef01cSRoman Divacky return V >> 1; 2422f22ef01cSRoman Divacky if (V != 1) 2423f22ef01cSRoman Divacky return -(V >> 1); 2424f22ef01cSRoman Divacky // There is no such thing as -0 with integers. "-0" really means MININT. 2425f22ef01cSRoman Divacky return 1ULL << 63; 2426f22ef01cSRoman Divacky } 2427f22ef01cSRoman Divacky 24288f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can. 24298f0fd8f6SDimitry Andric std::error_code BitcodeReader::resolveGlobalAndAliasInits() { 2430f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 2431f22ef01cSRoman Divacky std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 2432f785676fSDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 243339d628a0SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 24348f0fd8f6SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 2435f22ef01cSRoman Divacky 2436f22ef01cSRoman Divacky GlobalInitWorklist.swap(GlobalInits); 2437f22ef01cSRoman Divacky AliasInitWorklist.swap(AliasInits); 2438f785676fSDimitry Andric FunctionPrefixWorklist.swap(FunctionPrefixes); 243939d628a0SDimitry Andric FunctionPrologueWorklist.swap(FunctionPrologues); 24408f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2441f22ef01cSRoman Divacky 2442f22ef01cSRoman Divacky while (!GlobalInitWorklist.empty()) { 2443f22ef01cSRoman Divacky unsigned ValID = GlobalInitWorklist.back().second; 2444f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2445f22ef01cSRoman Divacky // Not ready to resolve this yet, it requires something later in the file. 2446f22ef01cSRoman Divacky GlobalInits.push_back(GlobalInitWorklist.back()); 2447f22ef01cSRoman Divacky } else { 244891bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2449f22ef01cSRoman Divacky GlobalInitWorklist.back().first->setInitializer(C); 2450f22ef01cSRoman Divacky else 24518f0fd8f6SDimitry Andric return error("Expected a constant"); 2452f22ef01cSRoman Divacky } 2453f22ef01cSRoman Divacky GlobalInitWorklist.pop_back(); 2454f22ef01cSRoman Divacky } 2455f22ef01cSRoman Divacky 2456f22ef01cSRoman Divacky while (!AliasInitWorklist.empty()) { 2457f22ef01cSRoman Divacky unsigned ValID = AliasInitWorklist.back().second; 2458f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2459f22ef01cSRoman Divacky AliasInits.push_back(AliasInitWorklist.back()); 2460f22ef01cSRoman Divacky } else { 246197bc6c73SDimitry Andric Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 246297bc6c73SDimitry Andric if (!C) 24638f0fd8f6SDimitry Andric return error("Expected a constant"); 246497bc6c73SDimitry Andric GlobalAlias *Alias = AliasInitWorklist.back().first; 246597bc6c73SDimitry Andric if (C->getType() != Alias->getType()) 24668f0fd8f6SDimitry Andric return error("Alias and aliasee types don't match"); 246797bc6c73SDimitry Andric Alias->setAliasee(C); 2468f22ef01cSRoman Divacky } 2469f22ef01cSRoman Divacky AliasInitWorklist.pop_back(); 2470f22ef01cSRoman Divacky } 2471f785676fSDimitry Andric 2472f785676fSDimitry Andric while (!FunctionPrefixWorklist.empty()) { 2473f785676fSDimitry Andric unsigned ValID = FunctionPrefixWorklist.back().second; 2474f785676fSDimitry Andric if (ValID >= ValueList.size()) { 2475f785676fSDimitry Andric FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2476f785676fSDimitry Andric } else { 247791bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2478f785676fSDimitry Andric FunctionPrefixWorklist.back().first->setPrefixData(C); 2479f785676fSDimitry Andric else 24808f0fd8f6SDimitry Andric return error("Expected a constant"); 2481f785676fSDimitry Andric } 2482f785676fSDimitry Andric FunctionPrefixWorklist.pop_back(); 2483f785676fSDimitry Andric } 2484f785676fSDimitry Andric 248539d628a0SDimitry Andric while (!FunctionPrologueWorklist.empty()) { 248639d628a0SDimitry Andric unsigned ValID = FunctionPrologueWorklist.back().second; 248739d628a0SDimitry Andric if (ValID >= ValueList.size()) { 248839d628a0SDimitry Andric FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 248939d628a0SDimitry Andric } else { 249039d628a0SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 249139d628a0SDimitry Andric FunctionPrologueWorklist.back().first->setPrologueData(C); 249239d628a0SDimitry Andric else 24938f0fd8f6SDimitry Andric return error("Expected a constant"); 249439d628a0SDimitry Andric } 249539d628a0SDimitry Andric FunctionPrologueWorklist.pop_back(); 249639d628a0SDimitry Andric } 249739d628a0SDimitry Andric 24988f0fd8f6SDimitry Andric while (!FunctionPersonalityFnWorklist.empty()) { 24998f0fd8f6SDimitry Andric unsigned ValID = FunctionPersonalityFnWorklist.back().second; 25008f0fd8f6SDimitry Andric if (ValID >= ValueList.size()) { 25018f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 25028f0fd8f6SDimitry Andric } else { 25038f0fd8f6SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 25048f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 25058f0fd8f6SDimitry Andric else 25068f0fd8f6SDimitry Andric return error("Expected a constant"); 25078f0fd8f6SDimitry Andric } 25088f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.pop_back(); 25098f0fd8f6SDimitry Andric } 25108f0fd8f6SDimitry Andric 251191bc56edSDimitry Andric return std::error_code(); 2512f22ef01cSRoman Divacky } 2513f22ef01cSRoman Divacky 25148f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 25157ae0e2c9SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size()); 25167ae0e2c9SDimitry Andric std::transform(Vals.begin(), Vals.end(), Words.begin(), 25173861d79fSDimitry Andric BitcodeReader::decodeSignRotatedValue); 25187ae0e2c9SDimitry Andric 25197ae0e2c9SDimitry Andric return APInt(TypeBits, Words); 25207ae0e2c9SDimitry Andric } 25217ae0e2c9SDimitry Andric 25228f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseConstants() { 2523f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 25248f0fd8f6SDimitry Andric return error("Invalid record"); 2525f22ef01cSRoman Divacky 2526f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 2527f22ef01cSRoman Divacky 2528f22ef01cSRoman Divacky // Read all the records for this value table. 25296122f3e6SDimitry Andric Type *CurTy = Type::getInt32Ty(Context); 2530f22ef01cSRoman Divacky unsigned NextCstNo = ValueList.size(); 2531f22ef01cSRoman Divacky while (1) { 2532139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2533139f7f9bSDimitry Andric 2534139f7f9bSDimitry Andric switch (Entry.Kind) { 2535139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2536139f7f9bSDimitry Andric case BitstreamEntry::Error: 25378f0fd8f6SDimitry Andric return error("Malformed block"); 2538139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2539139f7f9bSDimitry Andric if (NextCstNo != ValueList.size()) 25408f0fd8f6SDimitry Andric return error("Invalid ronstant reference"); 2541139f7f9bSDimitry Andric 2542139f7f9bSDimitry Andric // Once all the constants have been read, go through and resolve forward 2543139f7f9bSDimitry Andric // references. 25448f0fd8f6SDimitry Andric ValueList.resolveConstantForwardRefs(); 254591bc56edSDimitry Andric return std::error_code(); 2546139f7f9bSDimitry Andric case BitstreamEntry::Record: 2547139f7f9bSDimitry Andric // The interesting case. 2548f22ef01cSRoman Divacky break; 2549f22ef01cSRoman Divacky } 2550f22ef01cSRoman Divacky 2551f22ef01cSRoman Divacky // Read a record. 2552f22ef01cSRoman Divacky Record.clear(); 255391bc56edSDimitry Andric Value *V = nullptr; 2554139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2555f22ef01cSRoman Divacky switch (BitCode) { 2556f22ef01cSRoman Divacky default: // Default behavior: unknown constant 2557f22ef01cSRoman Divacky case bitc::CST_CODE_UNDEF: // UNDEF 2558f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2559f22ef01cSRoman Divacky break; 2560f22ef01cSRoman Divacky case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2561f22ef01cSRoman Divacky if (Record.empty()) 25628f0fd8f6SDimitry Andric return error("Invalid record"); 256391bc56edSDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 25648f0fd8f6SDimitry Andric return error("Invalid record"); 2565f22ef01cSRoman Divacky CurTy = TypeList[Record[0]]; 2566f22ef01cSRoman Divacky continue; // Skip the ValueList manipulation. 2567f22ef01cSRoman Divacky case bitc::CST_CODE_NULL: // NULL 2568f22ef01cSRoman Divacky V = Constant::getNullValue(CurTy); 2569f22ef01cSRoman Divacky break; 2570f22ef01cSRoman Divacky case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2571f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 25728f0fd8f6SDimitry Andric return error("Invalid record"); 25733861d79fSDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2574f22ef01cSRoman Divacky break; 2575f22ef01cSRoman Divacky case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2576f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 25778f0fd8f6SDimitry Andric return error("Invalid record"); 2578f22ef01cSRoman Divacky 25798f0fd8f6SDimitry Andric APInt VInt = 25808f0fd8f6SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 25817ae0e2c9SDimitry Andric V = ConstantInt::get(Context, VInt); 25827ae0e2c9SDimitry Andric 2583f22ef01cSRoman Divacky break; 2584f22ef01cSRoman Divacky } 2585f22ef01cSRoman Divacky case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2586f22ef01cSRoman Divacky if (Record.empty()) 25878f0fd8f6SDimitry Andric return error("Invalid record"); 2588dff0c46cSDimitry Andric if (CurTy->isHalfTy()) 2589139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 2590139f7f9bSDimitry Andric APInt(16, (uint16_t)Record[0]))); 2591dff0c46cSDimitry Andric else if (CurTy->isFloatTy()) 2592139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 2593139f7f9bSDimitry Andric APInt(32, (uint32_t)Record[0]))); 2594f22ef01cSRoman Divacky else if (CurTy->isDoubleTy()) 2595139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 2596139f7f9bSDimitry Andric APInt(64, Record[0]))); 2597f22ef01cSRoman Divacky else if (CurTy->isX86_FP80Ty()) { 2598f22ef01cSRoman Divacky // Bits are not stored the same way as a normal i80 APInt, compensate. 2599f22ef01cSRoman Divacky uint64_t Rearrange[2]; 2600f22ef01cSRoman Divacky Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2601f22ef01cSRoman Divacky Rearrange[1] = Record[0] >> 48; 2602139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 2603139f7f9bSDimitry Andric APInt(80, Rearrange))); 2604f22ef01cSRoman Divacky } else if (CurTy->isFP128Ty()) 2605139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 2606139f7f9bSDimitry Andric APInt(128, Record))); 2607f22ef01cSRoman Divacky else if (CurTy->isPPC_FP128Ty()) 2608139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 2609139f7f9bSDimitry Andric APInt(128, Record))); 2610f22ef01cSRoman Divacky else 2611f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2612f22ef01cSRoman Divacky break; 2613f22ef01cSRoman Divacky } 2614f22ef01cSRoman Divacky 2615f22ef01cSRoman Divacky case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2616f22ef01cSRoman Divacky if (Record.empty()) 26178f0fd8f6SDimitry Andric return error("Invalid record"); 2618f22ef01cSRoman Divacky 2619f22ef01cSRoman Divacky unsigned Size = Record.size(); 2620dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 2621f22ef01cSRoman Divacky 26226122f3e6SDimitry Andric if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2623f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2624f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2625f22ef01cSRoman Divacky STy->getElementType(i))); 2626f22ef01cSRoman Divacky V = ConstantStruct::get(STy, Elts); 26276122f3e6SDimitry Andric } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 26286122f3e6SDimitry Andric Type *EltTy = ATy->getElementType(); 2629f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2630f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2631f22ef01cSRoman Divacky V = ConstantArray::get(ATy, Elts); 26326122f3e6SDimitry Andric } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 26336122f3e6SDimitry Andric Type *EltTy = VTy->getElementType(); 2634f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2635f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2636f22ef01cSRoman Divacky V = ConstantVector::get(Elts); 2637f22ef01cSRoman Divacky } else { 2638f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2639f22ef01cSRoman Divacky } 2640f22ef01cSRoman Divacky break; 2641f22ef01cSRoman Divacky } 2642dff0c46cSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values] 2643f22ef01cSRoman Divacky case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2644f22ef01cSRoman Divacky if (Record.empty()) 26458f0fd8f6SDimitry Andric return error("Invalid record"); 2646f22ef01cSRoman Divacky 26477ae0e2c9SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end()); 2648dff0c46cSDimitry Andric V = ConstantDataArray::getString(Context, Elts, 2649dff0c46cSDimitry Andric BitCode == bitc::CST_CODE_CSTRING); 2650f22ef01cSRoman Divacky break; 2651f22ef01cSRoman Divacky } 2652dff0c46cSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value] 2653dff0c46cSDimitry Andric if (Record.empty()) 26548f0fd8f6SDimitry Andric return error("Invalid record"); 2655dff0c46cSDimitry Andric 2656dff0c46cSDimitry Andric Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2657dff0c46cSDimitry Andric if (EltTy->isIntegerTy(8)) { 2658dff0c46cSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2659dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2660dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2661dff0c46cSDimitry Andric else 2662dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2663dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(16)) { 2664dff0c46cSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2665dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2666dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2667dff0c46cSDimitry Andric else 2668dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2669dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(32)) { 2670dff0c46cSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2671dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2672dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2673dff0c46cSDimitry Andric else 2674dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2675dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(64)) { 2676dff0c46cSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2677dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2678dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2679dff0c46cSDimitry Andric else 2680dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2681444ed5c5SDimitry Andric } else if (EltTy->isHalfTy()) { 2682444ed5c5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2683444ed5c5SDimitry Andric if (isa<VectorType>(CurTy)) 2684444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2685444ed5c5SDimitry Andric else 2686444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2687dff0c46cSDimitry Andric } else if (EltTy->isFloatTy()) { 2688444ed5c5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2689dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2690444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2691dff0c46cSDimitry Andric else 2692444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2693dff0c46cSDimitry Andric } else if (EltTy->isDoubleTy()) { 2694444ed5c5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2695dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2696444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2697dff0c46cSDimitry Andric else 2698444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2699dff0c46cSDimitry Andric } else { 27008f0fd8f6SDimitry Andric return error("Invalid type for value"); 2701dff0c46cSDimitry Andric } 2702dff0c46cSDimitry Andric break; 2703dff0c46cSDimitry Andric } 2704dff0c46cSDimitry Andric 2705f22ef01cSRoman Divacky case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2706f785676fSDimitry Andric if (Record.size() < 3) 27078f0fd8f6SDimitry Andric return error("Invalid record"); 27088f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2709f22ef01cSRoman Divacky if (Opc < 0) { 2710f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown binop. 2711f22ef01cSRoman Divacky } else { 2712f22ef01cSRoman Divacky Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2713f22ef01cSRoman Divacky Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2714f22ef01cSRoman Divacky unsigned Flags = 0; 2715f22ef01cSRoman Divacky if (Record.size() >= 4) { 2716f22ef01cSRoman Divacky if (Opc == Instruction::Add || 2717f22ef01cSRoman Divacky Opc == Instruction::Sub || 27182754fe60SDimitry Andric Opc == Instruction::Mul || 27192754fe60SDimitry Andric Opc == Instruction::Shl) { 2720f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2721f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap; 2722f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2723f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 27242754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 27252754fe60SDimitry Andric Opc == Instruction::UDiv || 27262754fe60SDimitry Andric Opc == Instruction::LShr || 27272754fe60SDimitry Andric Opc == Instruction::AShr) { 27282754fe60SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT)) 2729f22ef01cSRoman Divacky Flags |= SDivOperator::IsExact; 2730f22ef01cSRoman Divacky } 2731f22ef01cSRoman Divacky } 2732f22ef01cSRoman Divacky V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2733f22ef01cSRoman Divacky } 2734f22ef01cSRoman Divacky break; 2735f22ef01cSRoman Divacky } 2736f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2737f785676fSDimitry Andric if (Record.size() < 3) 27388f0fd8f6SDimitry Andric return error("Invalid record"); 27398f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]); 2740f22ef01cSRoman Divacky if (Opc < 0) { 2741f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown cast. 2742f22ef01cSRoman Divacky } else { 27436122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 2744f785676fSDimitry Andric if (!OpTy) 27458f0fd8f6SDimitry Andric return error("Invalid record"); 2746f22ef01cSRoman Divacky Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2747f785676fSDimitry Andric V = UpgradeBitCastExpr(Opc, Op, CurTy); 2748f785676fSDimitry Andric if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2749f22ef01cSRoman Divacky } 2750f22ef01cSRoman Divacky break; 2751f22ef01cSRoman Divacky } 2752f22ef01cSRoman Divacky case bitc::CST_CODE_CE_INBOUNDS_GEP: 2753f22ef01cSRoman Divacky case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 2754ff0cc061SDimitry Andric unsigned OpNum = 0; 2755ff0cc061SDimitry Andric Type *PointeeType = nullptr; 2756ff0cc061SDimitry Andric if (Record.size() % 2) 2757ff0cc061SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]); 2758f22ef01cSRoman Divacky SmallVector<Constant*, 16> Elts; 2759ff0cc061SDimitry Andric while (OpNum != Record.size()) { 2760ff0cc061SDimitry Andric Type *ElTy = getTypeByID(Record[OpNum++]); 2761f785676fSDimitry Andric if (!ElTy) 27628f0fd8f6SDimitry Andric return error("Invalid record"); 2763ff0cc061SDimitry Andric Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2764f22ef01cSRoman Divacky } 2765ff0cc061SDimitry Andric 2766ff0cc061SDimitry Andric if (PointeeType && 2767ff0cc061SDimitry Andric PointeeType != 2768ff0cc061SDimitry Andric cast<SequentialType>(Elts[0]->getType()->getScalarType()) 2769ff0cc061SDimitry Andric ->getElementType()) 27708f0fd8f6SDimitry Andric return error("Explicit gep operator type does not match pointee type " 2771ff0cc061SDimitry Andric "of pointer operand"); 2772ff0cc061SDimitry Andric 27736122f3e6SDimitry Andric ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2774ff0cc061SDimitry Andric V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 27756122f3e6SDimitry Andric BitCode == 27766122f3e6SDimitry Andric bitc::CST_CODE_CE_INBOUNDS_GEP); 2777f22ef01cSRoman Divacky break; 2778f22ef01cSRoman Divacky } 2779f785676fSDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2780f785676fSDimitry Andric if (Record.size() < 3) 27818f0fd8f6SDimitry Andric return error("Invalid record"); 2782f785676fSDimitry Andric 2783f785676fSDimitry Andric Type *SelectorTy = Type::getInt1Ty(Context); 2784f785676fSDimitry Andric 27857d523365SDimitry Andric // The selector might be an i1 or an <n x i1> 27867d523365SDimitry Andric // Get the type from the ValueList before getting a forward ref. 2787f785676fSDimitry Andric if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 27887d523365SDimitry Andric if (Value *V = ValueList[Record[0]]) 27897d523365SDimitry Andric if (SelectorTy != V->getType()) 27907d523365SDimitry Andric SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2791f785676fSDimitry Andric 2792f785676fSDimitry Andric V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2793f785676fSDimitry Andric SelectorTy), 2794f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[1],CurTy), 2795f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[2],CurTy)); 2796f22ef01cSRoman Divacky break; 2797f785676fSDimitry Andric } 279891bc56edSDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT 279991bc56edSDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2800f785676fSDimitry Andric if (Record.size() < 3) 28018f0fd8f6SDimitry Andric return error("Invalid record"); 28026122f3e6SDimitry Andric VectorType *OpTy = 2803f22ef01cSRoman Divacky dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 280491bc56edSDimitry Andric if (!OpTy) 28058f0fd8f6SDimitry Andric return error("Invalid record"); 2806f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 280791bc56edSDimitry Andric Constant *Op1 = nullptr; 280891bc56edSDimitry Andric if (Record.size() == 4) { 280991bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 281091bc56edSDimitry Andric if (!IdxTy) 28118f0fd8f6SDimitry Andric return error("Invalid record"); 281291bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 281391bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 281491bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 281591bc56edSDimitry Andric if (!Op1) 28168f0fd8f6SDimitry Andric return error("Invalid record"); 2817f22ef01cSRoman Divacky V = ConstantExpr::getExtractElement(Op0, Op1); 2818f22ef01cSRoman Divacky break; 2819f22ef01cSRoman Divacky } 282091bc56edSDimitry Andric case bitc::CST_CODE_CE_INSERTELT 282191bc56edSDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval] 28226122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 282391bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 28248f0fd8f6SDimitry Andric return error("Invalid record"); 2825f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2826f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2827f22ef01cSRoman Divacky OpTy->getElementType()); 282891bc56edSDimitry Andric Constant *Op2 = nullptr; 282991bc56edSDimitry Andric if (Record.size() == 4) { 283091bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 283191bc56edSDimitry Andric if (!IdxTy) 28328f0fd8f6SDimitry Andric return error("Invalid record"); 283391bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 283491bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 283591bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 283691bc56edSDimitry Andric if (!Op2) 28378f0fd8f6SDimitry Andric return error("Invalid record"); 2838f22ef01cSRoman Divacky V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2839f22ef01cSRoman Divacky break; 2840f22ef01cSRoman Divacky } 2841f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 28426122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 284391bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 28448f0fd8f6SDimitry Andric return error("Invalid record"); 2845f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2846f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 28476122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2848f22ef01cSRoman Divacky OpTy->getNumElements()); 2849f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2850f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2851f22ef01cSRoman Divacky break; 2852f22ef01cSRoman Divacky } 2853f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 28546122f3e6SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy); 28556122f3e6SDimitry Andric VectorType *OpTy = 28562754fe60SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 285791bc56edSDimitry Andric if (Record.size() < 4 || !RTy || !OpTy) 28588f0fd8f6SDimitry Andric return error("Invalid record"); 2859f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2860f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 28616122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2862f22ef01cSRoman Divacky RTy->getNumElements()); 2863f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2864f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2865f22ef01cSRoman Divacky break; 2866f22ef01cSRoman Divacky } 2867f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2868f785676fSDimitry Andric if (Record.size() < 4) 28698f0fd8f6SDimitry Andric return error("Invalid record"); 28706122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 287191bc56edSDimitry Andric if (!OpTy) 28728f0fd8f6SDimitry Andric return error("Invalid record"); 2873f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2874f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2875f22ef01cSRoman Divacky 2876f22ef01cSRoman Divacky if (OpTy->isFPOrFPVectorTy()) 2877f22ef01cSRoman Divacky V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2878f22ef01cSRoman Divacky else 2879f22ef01cSRoman Divacky V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2880f22ef01cSRoman Divacky break; 2881f22ef01cSRoman Divacky } 28823861d79fSDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords. 28833861d79fSDimitry Andric // FIXME: Remove with the 4.0 release. 28843861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: { 2885f785676fSDimitry Andric if (Record.size() < 2) 28868f0fd8f6SDimitry Andric return error("Invalid record"); 2887f22ef01cSRoman Divacky std::string AsmStr, ConstrStr; 2888f22ef01cSRoman Divacky bool HasSideEffects = Record[0] & 1; 2889f22ef01cSRoman Divacky bool IsAlignStack = Record[0] >> 1; 2890f22ef01cSRoman Divacky unsigned AsmStrSize = Record[1]; 2891f22ef01cSRoman Divacky if (2+AsmStrSize >= Record.size()) 28928f0fd8f6SDimitry Andric return error("Invalid record"); 2893f22ef01cSRoman Divacky unsigned ConstStrSize = Record[2+AsmStrSize]; 2894f22ef01cSRoman Divacky if (3+AsmStrSize+ConstStrSize > Record.size()) 28958f0fd8f6SDimitry Andric return error("Invalid record"); 2896f22ef01cSRoman Divacky 2897f22ef01cSRoman Divacky for (unsigned i = 0; i != AsmStrSize; ++i) 2898f22ef01cSRoman Divacky AsmStr += (char)Record[2+i]; 2899f22ef01cSRoman Divacky for (unsigned i = 0; i != ConstStrSize; ++i) 2900f22ef01cSRoman Divacky ConstrStr += (char)Record[3+AsmStrSize+i]; 29016122f3e6SDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 2902f22ef01cSRoman Divacky V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2903f22ef01cSRoman Divacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2904f22ef01cSRoman Divacky break; 2905f22ef01cSRoman Divacky } 29063861d79fSDimitry Andric // This version adds support for the asm dialect keywords (e.g., 29073861d79fSDimitry Andric // inteldialect). 29083861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM: { 2909f785676fSDimitry Andric if (Record.size() < 2) 29108f0fd8f6SDimitry Andric return error("Invalid record"); 29113861d79fSDimitry Andric std::string AsmStr, ConstrStr; 29123861d79fSDimitry Andric bool HasSideEffects = Record[0] & 1; 29133861d79fSDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1; 29143861d79fSDimitry Andric unsigned AsmDialect = Record[0] >> 2; 29153861d79fSDimitry Andric unsigned AsmStrSize = Record[1]; 29163861d79fSDimitry Andric if (2+AsmStrSize >= Record.size()) 29178f0fd8f6SDimitry Andric return error("Invalid record"); 29183861d79fSDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 29193861d79fSDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 29208f0fd8f6SDimitry Andric return error("Invalid record"); 29213861d79fSDimitry Andric 29223861d79fSDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 29233861d79fSDimitry Andric AsmStr += (char)Record[2+i]; 29243861d79fSDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 29253861d79fSDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 29263861d79fSDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 29273861d79fSDimitry Andric V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 29283861d79fSDimitry Andric AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 29293861d79fSDimitry Andric InlineAsm::AsmDialect(AsmDialect)); 29303861d79fSDimitry Andric break; 29313861d79fSDimitry Andric } 2932f22ef01cSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{ 2933f785676fSDimitry Andric if (Record.size() < 3) 29348f0fd8f6SDimitry Andric return error("Invalid record"); 29356122f3e6SDimitry Andric Type *FnTy = getTypeByID(Record[0]); 293691bc56edSDimitry Andric if (!FnTy) 29378f0fd8f6SDimitry Andric return error("Invalid record"); 2938f22ef01cSRoman Divacky Function *Fn = 2939f22ef01cSRoman Divacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 294091bc56edSDimitry Andric if (!Fn) 29418f0fd8f6SDimitry Andric return error("Invalid record"); 294239d628a0SDimitry Andric 29433861d79fSDimitry Andric // If the function is already parsed we can insert the block address right 29443861d79fSDimitry Andric // away. 294539d628a0SDimitry Andric BasicBlock *BB; 294639d628a0SDimitry Andric unsigned BBID = Record[2]; 294739d628a0SDimitry Andric if (!BBID) 294839d628a0SDimitry Andric // Invalid reference to entry block. 29498f0fd8f6SDimitry Andric return error("Invalid ID"); 29503861d79fSDimitry Andric if (!Fn->empty()) { 29513861d79fSDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 295239d628a0SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) { 29533861d79fSDimitry Andric if (BBI == BBE) 29548f0fd8f6SDimitry Andric return error("Invalid ID"); 29553861d79fSDimitry Andric ++BBI; 29563861d79fSDimitry Andric } 29577d523365SDimitry Andric BB = &*BBI; 29583861d79fSDimitry Andric } else { 29593861d79fSDimitry Andric // Otherwise insert a placeholder and remember it so it can be inserted 29603861d79fSDimitry Andric // when the function is parsed. 296139d628a0SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn]; 296239d628a0SDimitry Andric if (FwdBBs.empty()) 296339d628a0SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn); 296439d628a0SDimitry Andric if (FwdBBs.size() < BBID + 1) 296539d628a0SDimitry Andric FwdBBs.resize(BBID + 1); 296639d628a0SDimitry Andric if (!FwdBBs[BBID]) 296739d628a0SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context); 296839d628a0SDimitry Andric BB = FwdBBs[BBID]; 29693861d79fSDimitry Andric } 297039d628a0SDimitry Andric V = BlockAddress::get(Fn, BB); 2971f22ef01cSRoman Divacky break; 2972f22ef01cSRoman Divacky } 2973f22ef01cSRoman Divacky } 2974f22ef01cSRoman Divacky 29758f0fd8f6SDimitry Andric ValueList.assignValue(V, NextCstNo); 2976f22ef01cSRoman Divacky ++NextCstNo; 2977f22ef01cSRoman Divacky } 2978f22ef01cSRoman Divacky } 2979f22ef01cSRoman Divacky 29808f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseUseLists() { 2981dff0c46cSDimitry Andric if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 29828f0fd8f6SDimitry Andric return error("Invalid record"); 2983dff0c46cSDimitry Andric 2984dff0c46cSDimitry Andric // Read all the records. 298539d628a0SDimitry Andric SmallVector<uint64_t, 64> Record; 2986dff0c46cSDimitry Andric while (1) { 2987139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2988139f7f9bSDimitry Andric 2989139f7f9bSDimitry Andric switch (Entry.Kind) { 2990139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2991139f7f9bSDimitry Andric case BitstreamEntry::Error: 29928f0fd8f6SDimitry Andric return error("Malformed block"); 2993139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 299491bc56edSDimitry Andric return std::error_code(); 2995139f7f9bSDimitry Andric case BitstreamEntry::Record: 2996139f7f9bSDimitry Andric // The interesting case. 2997139f7f9bSDimitry Andric break; 2998dff0c46cSDimitry Andric } 2999dff0c46cSDimitry Andric 3000dff0c46cSDimitry Andric // Read a use list record. 3001dff0c46cSDimitry Andric Record.clear(); 300239d628a0SDimitry Andric bool IsBB = false; 3003139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 3004dff0c46cSDimitry Andric default: // Default behavior: unknown type. 3005dff0c46cSDimitry Andric break; 300639d628a0SDimitry Andric case bitc::USELIST_CODE_BB: 300739d628a0SDimitry Andric IsBB = true; 300839d628a0SDimitry Andric // fallthrough 300939d628a0SDimitry Andric case bitc::USELIST_CODE_DEFAULT: { 3010dff0c46cSDimitry Andric unsigned RecordLength = Record.size(); 301139d628a0SDimitry Andric if (RecordLength < 3) 301239d628a0SDimitry Andric // Records should have at least an ID and two indexes. 30138f0fd8f6SDimitry Andric return error("Invalid record"); 301439d628a0SDimitry Andric unsigned ID = Record.back(); 301539d628a0SDimitry Andric Record.pop_back(); 301639d628a0SDimitry Andric 301739d628a0SDimitry Andric Value *V; 301839d628a0SDimitry Andric if (IsBB) { 301939d628a0SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found"); 302039d628a0SDimitry Andric V = FunctionBBs[ID]; 302139d628a0SDimitry Andric } else 302239d628a0SDimitry Andric V = ValueList[ID]; 302339d628a0SDimitry Andric unsigned NumUses = 0; 302439d628a0SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order; 30257d523365SDimitry Andric for (const Use &U : V->materialized_uses()) { 302639d628a0SDimitry Andric if (++NumUses > Record.size()) 302739d628a0SDimitry Andric break; 302839d628a0SDimitry Andric Order[&U] = Record[NumUses - 1]; 302939d628a0SDimitry Andric } 303039d628a0SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size()) 303139d628a0SDimitry Andric // Mismatches can happen if the functions are being materialized lazily 303239d628a0SDimitry Andric // (out-of-order), or a value has been upgraded. 303339d628a0SDimitry Andric break; 303439d628a0SDimitry Andric 303539d628a0SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) { 303639d628a0SDimitry Andric return Order.lookup(&L) < Order.lookup(&R); 303739d628a0SDimitry Andric }); 3038dff0c46cSDimitry Andric break; 3039dff0c46cSDimitry Andric } 3040dff0c46cSDimitry Andric } 3041dff0c46cSDimitry Andric } 3042dff0c46cSDimitry Andric } 3043dff0c46cSDimitry Andric 3044ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it. 3045ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata. 3046ff0cc061SDimitry Andric std::error_code BitcodeReader::rememberAndSkipMetadata() { 3047ff0cc061SDimitry Andric // Save the current stream state. 3048ff0cc061SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 3049ff0cc061SDimitry Andric DeferredMetadataInfo.push_back(CurBit); 3050ff0cc061SDimitry Andric 3051ff0cc061SDimitry Andric // Skip over the block for now. 3052ff0cc061SDimitry Andric if (Stream.SkipBlock()) 30538f0fd8f6SDimitry Andric return error("Invalid record"); 3054ff0cc061SDimitry Andric return std::error_code(); 3055ff0cc061SDimitry Andric } 3056ff0cc061SDimitry Andric 3057ff0cc061SDimitry Andric std::error_code BitcodeReader::materializeMetadata() { 3058ff0cc061SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) { 3059ff0cc061SDimitry Andric // Move the bit stream to the saved position. 3060ff0cc061SDimitry Andric Stream.JumpToBit(BitPos); 30617d523365SDimitry Andric if (std::error_code EC = parseMetadata(true)) 3062ff0cc061SDimitry Andric return EC; 3063ff0cc061SDimitry Andric } 3064ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 3065ff0cc061SDimitry Andric return std::error_code(); 3066ff0cc061SDimitry Andric } 3067ff0cc061SDimitry Andric 3068ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3069ff0cc061SDimitry Andric 30707d523365SDimitry Andric void BitcodeReader::saveMetadataList( 30717d523365SDimitry Andric DenseMap<const Metadata *, unsigned> &MetadataToIDs, bool OnlyTempMD) { 30727d523365SDimitry Andric for (unsigned ID = 0; ID < MetadataList.size(); ++ID) { 30737d523365SDimitry Andric Metadata *MD = MetadataList[ID]; 30747d523365SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD); 30754d0b32cdSDimitry Andric assert((!N || (N->isResolved() || N->isTemporary())) && 30764d0b32cdSDimitry Andric "Found non-resolved non-temp MDNode while saving metadata"); 30777d523365SDimitry Andric // Save all values if !OnlyTempMD, otherwise just the temporary metadata. 30784d0b32cdSDimitry Andric // Note that in the !OnlyTempMD case we need to save all Metadata, not 30794d0b32cdSDimitry Andric // just MDNode, as we may have references to other types of module-level 30804d0b32cdSDimitry Andric // metadata (e.g. ValueAsMetadata) from instructions. 30817d523365SDimitry Andric if (!OnlyTempMD || (N && N->isTemporary())) { 30827d523365SDimitry Andric // Will call this after materializing each function, in order to 30837d523365SDimitry Andric // handle remapping of the function's instructions/metadata. 30847d523365SDimitry Andric // See if we already have an entry in that case. 30857d523365SDimitry Andric if (OnlyTempMD && MetadataToIDs.count(MD)) { 30867d523365SDimitry Andric assert(MetadataToIDs[MD] == ID && "Inconsistent metadata value id"); 30877d523365SDimitry Andric continue; 30887d523365SDimitry Andric } 30894d0b32cdSDimitry Andric if (N && N->isTemporary()) 30904d0b32cdSDimitry Andric // Ensure that we assert if someone tries to RAUW this temporary 30914d0b32cdSDimitry Andric // metadata while it is the key of a map. The flag will be set back 30924d0b32cdSDimitry Andric // to true when the saved metadata list is destroyed. 30934d0b32cdSDimitry Andric N->setCanReplace(false); 30947d523365SDimitry Andric MetadataToIDs[MD] = ID; 30957d523365SDimitry Andric } 30967d523365SDimitry Andric } 30977d523365SDimitry Andric } 30987d523365SDimitry Andric 30998f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then 31008f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 31018f0fd8f6SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBody() { 3102f22ef01cSRoman Divacky // Get the function we are talking about. 3103f22ef01cSRoman Divacky if (FunctionsWithBodies.empty()) 31048f0fd8f6SDimitry Andric return error("Insufficient function protos"); 3105f22ef01cSRoman Divacky 3106f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back(); 3107f22ef01cSRoman Divacky FunctionsWithBodies.pop_back(); 3108f22ef01cSRoman Divacky 3109f22ef01cSRoman Divacky // Save the current stream state. 3110f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo(); 31117d523365SDimitry Andric assert( 31127d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 31137d523365SDimitry Andric "Mismatch between VST and scanned function offsets"); 3114f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit; 3115f22ef01cSRoman Divacky 3116f22ef01cSRoman Divacky // Skip over the function block for now. 3117f22ef01cSRoman Divacky if (Stream.SkipBlock()) 31188f0fd8f6SDimitry Andric return error("Invalid record"); 311991bc56edSDimitry Andric return std::error_code(); 3120f22ef01cSRoman Divacky } 3121f22ef01cSRoman Divacky 31228f0fd8f6SDimitry Andric std::error_code BitcodeReader::globalCleanup() { 3123f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up. 31248f0fd8f6SDimitry Andric resolveGlobalAndAliasInits(); 3125f22ef01cSRoman Divacky if (!GlobalInits.empty() || !AliasInits.empty()) 31268f0fd8f6SDimitry Andric return error("Malformed global initializer set"); 3127f22ef01cSRoman Divacky 3128f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point 31298f0fd8f6SDimitry Andric for (Function &F : *TheModule) { 3130f22ef01cSRoman Divacky Function *NewFn; 31318f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 31323dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn; 3133f22ef01cSRoman Divacky } 3134f22ef01cSRoman Divacky 3135e580952dSDimitry Andric // Look for global variables which need to be renamed. 31368f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 31378f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV); 313891bc56edSDimitry Andric 3139f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that 3140f22ef01cSRoman Divacky // want lazy deserialization. 3141f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 3142f22ef01cSRoman Divacky std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 314391bc56edSDimitry Andric return std::error_code(); 3144f22ef01cSRoman Divacky } 3145f22ef01cSRoman Divacky 31467d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 31477d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 31487d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 31497d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST. 31507d523365SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBodies() { 3151dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit); 31527d523365SDimitry Andric 31537d523365SDimitry Andric if (Stream.AtEndOfStream()) 31547d523365SDimitry Andric return error("Could not find function in stream"); 31557d523365SDimitry Andric 31567d523365SDimitry Andric if (!SeenFirstFunctionBody) 31577d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 31587d523365SDimitry Andric 31597d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have 31607d523365SDimitry Andric // finished the parse greedily. 31617d523365SDimitry Andric assert(SeenValueSymbolTable); 31627d523365SDimitry Andric 31637d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 31647d523365SDimitry Andric 31657d523365SDimitry Andric while (1) { 31667d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 31677d523365SDimitry Andric switch (Entry.Kind) { 31687d523365SDimitry Andric default: 31697d523365SDimitry Andric return error("Expect SubBlock"); 31707d523365SDimitry Andric case BitstreamEntry::SubBlock: 31717d523365SDimitry Andric switch (Entry.ID) { 31727d523365SDimitry Andric default: 31737d523365SDimitry Andric return error("Expect function block"); 31747d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 31757d523365SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBody()) 31767d523365SDimitry Andric return EC; 31777d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 31787d523365SDimitry Andric return std::error_code(); 31797d523365SDimitry Andric } 31807d523365SDimitry Andric } 31817d523365SDimitry Andric } 31827d523365SDimitry Andric } 31837d523365SDimitry Andric 31847d523365SDimitry Andric std::error_code BitcodeReader::parseBitcodeVersion() { 31857d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 31867d523365SDimitry Andric return error("Invalid record"); 31877d523365SDimitry Andric 31887d523365SDimitry Andric // Read all the records. 31897d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 31907d523365SDimitry Andric while (1) { 31917d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 31927d523365SDimitry Andric 31937d523365SDimitry Andric switch (Entry.Kind) { 31947d523365SDimitry Andric default: 31957d523365SDimitry Andric case BitstreamEntry::Error: 31967d523365SDimitry Andric return error("Malformed block"); 31977d523365SDimitry Andric case BitstreamEntry::EndBlock: 31987d523365SDimitry Andric return std::error_code(); 31997d523365SDimitry Andric case BitstreamEntry::Record: 32007d523365SDimitry Andric // The interesting case. 32017d523365SDimitry Andric break; 32027d523365SDimitry Andric } 32037d523365SDimitry Andric 32047d523365SDimitry Andric // Read a record. 32057d523365SDimitry Andric Record.clear(); 32067d523365SDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 32077d523365SDimitry Andric switch (BitCode) { 32087d523365SDimitry Andric default: // Default behavior: reject 32097d523365SDimitry Andric return error("Invalid value"); 32107d523365SDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x 32117d523365SDimitry Andric // N] 32127d523365SDimitry Andric convertToString(Record, 0, ProducerIdentification); 32137d523365SDimitry Andric break; 32147d523365SDimitry Andric } 32157d523365SDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 32167d523365SDimitry Andric unsigned epoch = (unsigned)Record[0]; 32177d523365SDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 32187d523365SDimitry Andric return error( 32197d523365SDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 32207d523365SDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 32217d523365SDimitry Andric } 32227d523365SDimitry Andric } 32237d523365SDimitry Andric } 32247d523365SDimitry Andric } 32257d523365SDimitry Andric } 32267d523365SDimitry Andric 32277d523365SDimitry Andric std::error_code BitcodeReader::parseModule(uint64_t ResumeBit, 32287d523365SDimitry Andric bool ShouldLazyLoadMetadata) { 32297d523365SDimitry Andric if (ResumeBit) 32307d523365SDimitry Andric Stream.JumpToBit(ResumeBit); 3231dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 32328f0fd8f6SDimitry Andric return error("Invalid record"); 3233dff0c46cSDimitry Andric 3234dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record; 3235dff0c46cSDimitry Andric std::vector<std::string> SectionTable; 3236dff0c46cSDimitry Andric std::vector<std::string> GCTable; 3237dff0c46cSDimitry Andric 3238dff0c46cSDimitry Andric // Read all the records for this module. 3239139f7f9bSDimitry Andric while (1) { 3240139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3241dff0c46cSDimitry Andric 3242139f7f9bSDimitry Andric switch (Entry.Kind) { 3243139f7f9bSDimitry Andric case BitstreamEntry::Error: 32448f0fd8f6SDimitry Andric return error("Malformed block"); 3245139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 32468f0fd8f6SDimitry Andric return globalCleanup(); 3247dff0c46cSDimitry Andric 3248139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3249139f7f9bSDimitry Andric switch (Entry.ID) { 3250f22ef01cSRoman Divacky default: // Skip unknown content. 3251f22ef01cSRoman Divacky if (Stream.SkipBlock()) 32528f0fd8f6SDimitry Andric return error("Invalid record"); 3253f22ef01cSRoman Divacky break; 3254f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID: 3255f22ef01cSRoman Divacky if (Stream.ReadBlockInfoBlock()) 32568f0fd8f6SDimitry Andric return error("Malformed block"); 3257f22ef01cSRoman Divacky break; 3258f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID: 32598f0fd8f6SDimitry Andric if (std::error_code EC = parseAttributeBlock()) 3260f785676fSDimitry Andric return EC; 3261f22ef01cSRoman Divacky break; 3262139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 32638f0fd8f6SDimitry Andric if (std::error_code EC = parseAttributeGroupBlock()) 3264f785676fSDimitry Andric return EC; 3265139f7f9bSDimitry Andric break; 326617a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 32678f0fd8f6SDimitry Andric if (std::error_code EC = parseTypeTable()) 3268f785676fSDimitry Andric return EC; 3269f22ef01cSRoman Divacky break; 3270f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 32717d523365SDimitry Andric if (!SeenValueSymbolTable) { 32727d523365SDimitry Andric // Either this is an old form VST without function index and an 32737d523365SDimitry Andric // associated VST forward declaration record (which would have caused 32747d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered 32757d523365SDimitry Andric // normally in the stream), or there were no function blocks to 32767d523365SDimitry Andric // trigger an earlier parsing of the VST. 32777d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 32788f0fd8f6SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 3279f785676fSDimitry Andric return EC; 3280dff0c46cSDimitry Andric SeenValueSymbolTable = true; 32817d523365SDimitry Andric } else { 32827d523365SDimitry Andric // We must have had a VST forward declaration record, which caused 32837d523365SDimitry Andric // the parser to jump to and parse the VST earlier. 32847d523365SDimitry Andric assert(VSTOffset > 0); 32857d523365SDimitry Andric if (Stream.SkipBlock()) 32867d523365SDimitry Andric return error("Invalid record"); 32877d523365SDimitry Andric } 3288f22ef01cSRoman Divacky break; 3289f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 32908f0fd8f6SDimitry Andric if (std::error_code EC = parseConstants()) 3291f785676fSDimitry Andric return EC; 32928f0fd8f6SDimitry Andric if (std::error_code EC = resolveGlobalAndAliasInits()) 3293f785676fSDimitry Andric return EC; 3294f22ef01cSRoman Divacky break; 3295f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3296ff0cc061SDimitry Andric if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 3297ff0cc061SDimitry Andric if (std::error_code EC = rememberAndSkipMetadata()) 3298ff0cc061SDimitry Andric return EC; 3299ff0cc061SDimitry Andric break; 3300ff0cc061SDimitry Andric } 3301ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 33027d523365SDimitry Andric if (std::error_code EC = parseMetadata(true)) 33037d523365SDimitry Andric return EC; 33047d523365SDimitry Andric break; 33057d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 33067d523365SDimitry Andric if (std::error_code EC = parseMetadataKinds()) 3307f785676fSDimitry Andric return EC; 3308f22ef01cSRoman Divacky break; 3309f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID: 3310f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the 3311f22ef01cSRoman Divacky // FunctionsWithBodies list. 3312dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) { 3313f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 33148f0fd8f6SDimitry Andric if (std::error_code EC = globalCleanup()) 3315f785676fSDimitry Andric return EC; 3316dff0c46cSDimitry Andric SeenFirstFunctionBody = true; 3317f22ef01cSRoman Divacky } 3318f22ef01cSRoman Divacky 33197d523365SDimitry Andric if (VSTOffset > 0) { 33207d523365SDimitry Andric // If we have a VST forward declaration record, make sure we 33217d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to 33227d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 33237d523365SDimitry Andric if (!SeenValueSymbolTable) { 33247d523365SDimitry Andric if (std::error_code EC = 33257d523365SDimitry Andric BitcodeReader::parseValueSymbolTable(VSTOffset)) 33267d523365SDimitry Andric return EC; 33277d523365SDimitry Andric SeenValueSymbolTable = true; 33287d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below. 33297d523365SDimitry Andric // This is necessary in case we have an anonymous function that 33307d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we 33317d523365SDimitry Andric // need to fall back to the lazy parse to find its offset. 33327d523365SDimitry Andric } else { 33337d523365SDimitry Andric // If we have a VST forward declaration record, but have already 33347d523365SDimitry Andric // parsed the VST (just above, when the first function body was 33357d523365SDimitry Andric // encountered here), then we are resuming the parse after 33367d523365SDimitry Andric // materializing functions. The ResumeBit points to the 33377d523365SDimitry Andric // start of the last function block recorded in the 33387d523365SDimitry Andric // DeferredFunctionInfo map. Skip it. 33397d523365SDimitry Andric if (Stream.SkipBlock()) 33407d523365SDimitry Andric return error("Invalid record"); 33417d523365SDimitry Andric continue; 33427d523365SDimitry Andric } 33437d523365SDimitry Andric } 33447d523365SDimitry Andric 33457d523365SDimitry Andric // Support older bitcode files that did not have the function 33467d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as 33477d523365SDimitry Andric // well as anonymous functions that do not have VST entries. 33487d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 33498f0fd8f6SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBody()) 3350f785676fSDimitry Andric return EC; 33517d523365SDimitry Andric 33523dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 33533dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode 33543dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not 33553dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now. 33563dac3a9bSDimitry Andric if (SeenValueSymbolTable) { 3357dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 335891bc56edSDimitry Andric return std::error_code(); 3359dff0c46cSDimitry Andric } 3360dff0c46cSDimitry Andric break; 3361dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID: 33628f0fd8f6SDimitry Andric if (std::error_code EC = parseUseLists()) 3363f785676fSDimitry Andric return EC; 3364f22ef01cSRoman Divacky break; 33657d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 33667d523365SDimitry Andric if (std::error_code EC = parseOperandBundleTags()) 33677d523365SDimitry Andric return EC; 33687d523365SDimitry Andric break; 3369f22ef01cSRoman Divacky } 3370f22ef01cSRoman Divacky continue; 3371139f7f9bSDimitry Andric 3372139f7f9bSDimitry Andric case BitstreamEntry::Record: 3373139f7f9bSDimitry Andric // The interesting case. 3374139f7f9bSDimitry Andric break; 3375f22ef01cSRoman Divacky } 3376f22ef01cSRoman Divacky 3377f22ef01cSRoman Divacky 3378f22ef01cSRoman Divacky // Read a record. 33797d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 33807d523365SDimitry Andric switch (BitCode) { 3381f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content. 33823861d79fSDimitry Andric case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 3383f22ef01cSRoman Divacky if (Record.size() < 1) 33848f0fd8f6SDimitry Andric return error("Invalid record"); 33853861d79fSDimitry Andric // Only version #0 and #1 are supported so far. 33863861d79fSDimitry Andric unsigned module_version = Record[0]; 33873861d79fSDimitry Andric switch (module_version) { 3388f785676fSDimitry Andric default: 33898f0fd8f6SDimitry Andric return error("Invalid value"); 33903861d79fSDimitry Andric case 0: 33913861d79fSDimitry Andric UseRelativeIDs = false; 3392f22ef01cSRoman Divacky break; 33933861d79fSDimitry Andric case 1: 33943861d79fSDimitry Andric UseRelativeIDs = true; 33953861d79fSDimitry Andric break; 33963861d79fSDimitry Andric } 33973861d79fSDimitry Andric break; 33983861d79fSDimitry Andric } 3399f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3400f22ef01cSRoman Divacky std::string S; 34018f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34028f0fd8f6SDimitry Andric return error("Invalid record"); 3403f22ef01cSRoman Divacky TheModule->setTargetTriple(S); 3404f22ef01cSRoman Divacky break; 3405f22ef01cSRoman Divacky } 3406f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3407f22ef01cSRoman Divacky std::string S; 34088f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34098f0fd8f6SDimitry Andric return error("Invalid record"); 3410f22ef01cSRoman Divacky TheModule->setDataLayout(S); 3411f22ef01cSRoman Divacky break; 3412f22ef01cSRoman Divacky } 3413f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3414f22ef01cSRoman Divacky std::string S; 34158f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34168f0fd8f6SDimitry Andric return error("Invalid record"); 3417f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S); 3418f22ef01cSRoman Divacky break; 3419f22ef01cSRoman Divacky } 3420f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3421139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 3422f22ef01cSRoman Divacky std::string S; 34238f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34248f0fd8f6SDimitry Andric return error("Invalid record"); 3425139f7f9bSDimitry Andric // Ignore value. 3426f22ef01cSRoman Divacky break; 3427f22ef01cSRoman Divacky } 3428f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3429f22ef01cSRoman Divacky std::string S; 34308f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34318f0fd8f6SDimitry Andric return error("Invalid record"); 3432f22ef01cSRoman Divacky SectionTable.push_back(S); 3433f22ef01cSRoman Divacky break; 3434f22ef01cSRoman Divacky } 3435f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3436f22ef01cSRoman Divacky std::string S; 34378f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34388f0fd8f6SDimitry Andric return error("Invalid record"); 3439f22ef01cSRoman Divacky GCTable.push_back(S); 3440f22ef01cSRoman Divacky break; 3441f22ef01cSRoman Divacky } 344291bc56edSDimitry Andric case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 344391bc56edSDimitry Andric if (Record.size() < 2) 34448f0fd8f6SDimitry Andric return error("Invalid record"); 344591bc56edSDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 344691bc56edSDimitry Andric unsigned ComdatNameSize = Record[1]; 344791bc56edSDimitry Andric std::string ComdatName; 344891bc56edSDimitry Andric ComdatName.reserve(ComdatNameSize); 344991bc56edSDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 345091bc56edSDimitry Andric ComdatName += (char)Record[2 + i]; 345191bc56edSDimitry Andric Comdat *C = TheModule->getOrInsertComdat(ComdatName); 345291bc56edSDimitry Andric C->setSelectionKind(SK); 345391bc56edSDimitry Andric ComdatList.push_back(C); 345491bc56edSDimitry Andric break; 345591bc56edSDimitry Andric } 3456f22ef01cSRoman Divacky // GLOBALVAR: [pointer type, isconst, initid, 34572754fe60SDimitry Andric // linkage, alignment, section, visibility, threadlocal, 3458ff0cc061SDimitry Andric // unnamed_addr, externally_initialized, dllstorageclass, 3459ff0cc061SDimitry Andric // comdat] 3460f22ef01cSRoman Divacky case bitc::MODULE_CODE_GLOBALVAR: { 3461f22ef01cSRoman Divacky if (Record.size() < 6) 34628f0fd8f6SDimitry Andric return error("Invalid record"); 34636122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 3464f785676fSDimitry Andric if (!Ty) 34658f0fd8f6SDimitry Andric return error("Invalid record"); 3466ff0cc061SDimitry Andric bool isConstant = Record[1] & 1; 3467ff0cc061SDimitry Andric bool explicitType = Record[1] & 2; 3468ff0cc061SDimitry Andric unsigned AddressSpace; 3469ff0cc061SDimitry Andric if (explicitType) { 3470ff0cc061SDimitry Andric AddressSpace = Record[1] >> 2; 3471ff0cc061SDimitry Andric } else { 3472f22ef01cSRoman Divacky if (!Ty->isPointerTy()) 34738f0fd8f6SDimitry Andric return error("Invalid type for value"); 3474ff0cc061SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3475f22ef01cSRoman Divacky Ty = cast<PointerType>(Ty)->getElementType(); 3476ff0cc061SDimitry Andric } 3477f22ef01cSRoman Divacky 3478ff0cc061SDimitry Andric uint64_t RawLinkage = Record[3]; 3479ff0cc061SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3480ff0cc061SDimitry Andric unsigned Alignment; 3481ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[4], Alignment)) 3482ff0cc061SDimitry Andric return EC; 3483f22ef01cSRoman Divacky std::string Section; 3484f22ef01cSRoman Divacky if (Record[5]) { 3485f22ef01cSRoman Divacky if (Record[5]-1 >= SectionTable.size()) 34868f0fd8f6SDimitry Andric return error("Invalid ID"); 3487f22ef01cSRoman Divacky Section = SectionTable[Record[5]-1]; 3488f22ef01cSRoman Divacky } 3489f22ef01cSRoman Divacky GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 349091bc56edSDimitry Andric // Local linkage must have default visibility. 349191bc56edSDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 349291bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 34938f0fd8f6SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 34947ae0e2c9SDimitry Andric 34957ae0e2c9SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3496f22ef01cSRoman Divacky if (Record.size() > 7) 34978f0fd8f6SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 3498f22ef01cSRoman Divacky 34992754fe60SDimitry Andric bool UnnamedAddr = false; 35002754fe60SDimitry Andric if (Record.size() > 8) 35012754fe60SDimitry Andric UnnamedAddr = Record[8]; 35022754fe60SDimitry Andric 3503139f7f9bSDimitry Andric bool ExternallyInitialized = false; 3504139f7f9bSDimitry Andric if (Record.size() > 9) 3505139f7f9bSDimitry Andric ExternallyInitialized = Record[9]; 3506139f7f9bSDimitry Andric 3507f22ef01cSRoman Divacky GlobalVariable *NewGV = 350891bc56edSDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 3509139f7f9bSDimitry Andric TLM, AddressSpace, ExternallyInitialized); 3510f22ef01cSRoman Divacky NewGV->setAlignment(Alignment); 3511f22ef01cSRoman Divacky if (!Section.empty()) 3512f22ef01cSRoman Divacky NewGV->setSection(Section); 3513f22ef01cSRoman Divacky NewGV->setVisibility(Visibility); 35142754fe60SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 3515f22ef01cSRoman Divacky 351691bc56edSDimitry Andric if (Record.size() > 10) 35178f0fd8f6SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 351891bc56edSDimitry Andric else 35198f0fd8f6SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 352091bc56edSDimitry Andric 3521f22ef01cSRoman Divacky ValueList.push_back(NewGV); 3522f22ef01cSRoman Divacky 3523f22ef01cSRoman Divacky // Remember which value to use for the global initializer. 3524f22ef01cSRoman Divacky if (unsigned InitID = Record[2]) 3525f22ef01cSRoman Divacky GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 352691bc56edSDimitry Andric 3527ff0cc061SDimitry Andric if (Record.size() > 11) { 352891bc56edSDimitry Andric if (unsigned ComdatID = Record[11]) { 3529ff0cc061SDimitry Andric if (ComdatID > ComdatList.size()) 35308f0fd8f6SDimitry Andric return error("Invalid global variable comdat ID"); 353191bc56edSDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 353291bc56edSDimitry Andric } 3533ff0cc061SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 3534ff0cc061SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 3535ff0cc061SDimitry Andric } 3536f22ef01cSRoman Divacky break; 3537f22ef01cSRoman Divacky } 3538f22ef01cSRoman Divacky // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 353991bc56edSDimitry Andric // alignment, section, visibility, gc, unnamed_addr, 354039d628a0SDimitry Andric // prologuedata, dllstorageclass, comdat, prefixdata] 3541f22ef01cSRoman Divacky case bitc::MODULE_CODE_FUNCTION: { 3542f22ef01cSRoman Divacky if (Record.size() < 8) 35438f0fd8f6SDimitry Andric return error("Invalid record"); 35446122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 3545f785676fSDimitry Andric if (!Ty) 35468f0fd8f6SDimitry Andric return error("Invalid record"); 3547ff0cc061SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty)) 3548ff0cc061SDimitry Andric Ty = PTy->getElementType(); 3549ff0cc061SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty); 3550f22ef01cSRoman Divacky if (!FTy) 35518f0fd8f6SDimitry Andric return error("Invalid type for value"); 35527d523365SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 35537d523365SDimitry Andric if (CC & ~CallingConv::MaxID) 35547d523365SDimitry Andric return error("Invalid calling convention ID"); 3555f22ef01cSRoman Divacky 3556f22ef01cSRoman Divacky Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 3557f22ef01cSRoman Divacky "", TheModule); 3558f22ef01cSRoman Divacky 35597d523365SDimitry Andric Func->setCallingConv(CC); 3560f22ef01cSRoman Divacky bool isProto = Record[2]; 3561ff0cc061SDimitry Andric uint64_t RawLinkage = Record[3]; 3562ff0cc061SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 3563f22ef01cSRoman Divacky Func->setAttributes(getAttributes(Record[4])); 3564f22ef01cSRoman Divacky 3565ff0cc061SDimitry Andric unsigned Alignment; 3566ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[5], Alignment)) 3567ff0cc061SDimitry Andric return EC; 3568ff0cc061SDimitry Andric Func->setAlignment(Alignment); 3569f22ef01cSRoman Divacky if (Record[6]) { 3570f22ef01cSRoman Divacky if (Record[6]-1 >= SectionTable.size()) 35718f0fd8f6SDimitry Andric return error("Invalid ID"); 3572f22ef01cSRoman Divacky Func->setSection(SectionTable[Record[6]-1]); 3573f22ef01cSRoman Divacky } 357491bc56edSDimitry Andric // Local linkage must have default visibility. 357591bc56edSDimitry Andric if (!Func->hasLocalLinkage()) 357691bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 35778f0fd8f6SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 3578f22ef01cSRoman Divacky if (Record.size() > 8 && Record[8]) { 3579ff0cc061SDimitry Andric if (Record[8]-1 >= GCTable.size()) 35808f0fd8f6SDimitry Andric return error("Invalid ID"); 3581f22ef01cSRoman Divacky Func->setGC(GCTable[Record[8]-1].c_str()); 3582f22ef01cSRoman Divacky } 35832754fe60SDimitry Andric bool UnnamedAddr = false; 35842754fe60SDimitry Andric if (Record.size() > 9) 35852754fe60SDimitry Andric UnnamedAddr = Record[9]; 35862754fe60SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 3587f785676fSDimitry Andric if (Record.size() > 10 && Record[10] != 0) 358839d628a0SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 358991bc56edSDimitry Andric 359091bc56edSDimitry Andric if (Record.size() > 11) 35918f0fd8f6SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 359291bc56edSDimitry Andric else 35938f0fd8f6SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 359491bc56edSDimitry Andric 3595ff0cc061SDimitry Andric if (Record.size() > 12) { 359691bc56edSDimitry Andric if (unsigned ComdatID = Record[12]) { 3597ff0cc061SDimitry Andric if (ComdatID > ComdatList.size()) 35988f0fd8f6SDimitry Andric return error("Invalid function comdat ID"); 359991bc56edSDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 360091bc56edSDimitry Andric } 3601ff0cc061SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 3602ff0cc061SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1)); 3603ff0cc061SDimitry Andric } 360491bc56edSDimitry Andric 360539d628a0SDimitry Andric if (Record.size() > 13 && Record[13] != 0) 360639d628a0SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 360739d628a0SDimitry Andric 36088f0fd8f6SDimitry Andric if (Record.size() > 14 && Record[14] != 0) 36098f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 36108f0fd8f6SDimitry Andric 3611f22ef01cSRoman Divacky ValueList.push_back(Func); 3612f22ef01cSRoman Divacky 3613f22ef01cSRoman Divacky // If this is a function with a body, remember the prototype we are 3614f22ef01cSRoman Divacky // creating now, so that we can match up the body with them later. 3615dff0c46cSDimitry Andric if (!isProto) { 361639d628a0SDimitry Andric Func->setIsMaterializable(true); 3617f22ef01cSRoman Divacky FunctionsWithBodies.push_back(Func); 361839d628a0SDimitry Andric DeferredFunctionInfo[Func] = 0; 3619dff0c46cSDimitry Andric } 3620f22ef01cSRoman Divacky break; 3621f22ef01cSRoman Divacky } 36227d523365SDimitry Andric // ALIAS: [alias type, addrspace, aliasee val#, linkage] 36237d523365SDimitry Andric // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 36247d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS: 36257d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: { 36267d523365SDimitry Andric bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS; 36277d523365SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 36288f0fd8f6SDimitry Andric return error("Invalid record"); 36297d523365SDimitry Andric unsigned OpNum = 0; 36307d523365SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]); 3631f785676fSDimitry Andric if (!Ty) 36328f0fd8f6SDimitry Andric return error("Invalid record"); 36337d523365SDimitry Andric 36347d523365SDimitry Andric unsigned AddrSpace; 36357d523365SDimitry Andric if (!NewRecord) { 363691bc56edSDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 363791bc56edSDimitry Andric if (!PTy) 36388f0fd8f6SDimitry Andric return error("Invalid type for value"); 36397d523365SDimitry Andric Ty = PTy->getElementType(); 36407d523365SDimitry Andric AddrSpace = PTy->getAddressSpace(); 36417d523365SDimitry Andric } else { 36427d523365SDimitry Andric AddrSpace = Record[OpNum++]; 36437d523365SDimitry Andric } 3644f22ef01cSRoman Divacky 36457d523365SDimitry Andric auto Val = Record[OpNum++]; 36467d523365SDimitry Andric auto Linkage = Record[OpNum++]; 36477d523365SDimitry Andric auto *NewGA = GlobalAlias::create( 36487d523365SDimitry Andric Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule); 3649f22ef01cSRoman Divacky // Old bitcode files didn't have visibility field. 365091bc56edSDimitry Andric // Local linkage must have default visibility. 36517d523365SDimitry Andric if (OpNum != Record.size()) { 36527d523365SDimitry Andric auto VisInd = OpNum++; 36537d523365SDimitry Andric if (!NewGA->hasLocalLinkage()) 365491bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 36557d523365SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 36567d523365SDimitry Andric } 36577d523365SDimitry Andric if (OpNum != Record.size()) 36587d523365SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 365991bc56edSDimitry Andric else 36607d523365SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 36617d523365SDimitry Andric if (OpNum != Record.size()) 36627d523365SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 36637d523365SDimitry Andric if (OpNum != Record.size()) 36647d523365SDimitry Andric NewGA->setUnnamedAddr(Record[OpNum++]); 3665f22ef01cSRoman Divacky ValueList.push_back(NewGA); 36667d523365SDimitry Andric AliasInits.push_back(std::make_pair(NewGA, Val)); 3667f22ef01cSRoman Divacky break; 3668f22ef01cSRoman Divacky } 3669f22ef01cSRoman Divacky /// MODULE_CODE_PURGEVALS: [numvals] 3670f22ef01cSRoman Divacky case bitc::MODULE_CODE_PURGEVALS: 3671f22ef01cSRoman Divacky // Trim down the value list to the specified size. 3672f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] > ValueList.size()) 36738f0fd8f6SDimitry Andric return error("Invalid record"); 3674f22ef01cSRoman Divacky ValueList.shrinkTo(Record[0]); 3675f22ef01cSRoman Divacky break; 36767d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 36777d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 36787d523365SDimitry Andric if (Record.size() < 1) 36797d523365SDimitry Andric return error("Invalid record"); 36807d523365SDimitry Andric VSTOffset = Record[0]; 36817d523365SDimitry Andric break; 36827d523365SDimitry Andric /// MODULE_CODE_METADATA_VALUES: [numvals] 36837d523365SDimitry Andric case bitc::MODULE_CODE_METADATA_VALUES: 36847d523365SDimitry Andric if (Record.size() < 1) 36857d523365SDimitry Andric return error("Invalid record"); 36867d523365SDimitry Andric assert(!IsMetadataMaterialized); 36877d523365SDimitry Andric // This record contains the number of metadata values in the module-level 36887d523365SDimitry Andric // METADATA_BLOCK. It is used to support lazy parsing of metadata as 36897d523365SDimitry Andric // a postpass, where we will parse function-level metadata first. 36907d523365SDimitry Andric // This is needed because the ids of metadata are assigned implicitly 36917d523365SDimitry Andric // based on their ordering in the bitcode, with the function-level 36927d523365SDimitry Andric // metadata ids starting after the module-level metadata ids. Otherwise, 36937d523365SDimitry Andric // we would have to parse the module-level metadata block to prime the 36947d523365SDimitry Andric // MetadataList when we are lazy loading metadata during function 36957d523365SDimitry Andric // importing. Initialize the MetadataList size here based on the 36967d523365SDimitry Andric // record value, regardless of whether we are doing lazy metadata 36977d523365SDimitry Andric // loading, so that we have consistent handling and assertion 36987d523365SDimitry Andric // checking in parseMetadata for module-level metadata. 36997d523365SDimitry Andric NumModuleMDs = Record[0]; 37007d523365SDimitry Andric SeenModuleValuesRecord = true; 37017d523365SDimitry Andric assert(MetadataList.size() == 0); 37027d523365SDimitry Andric MetadataList.resize(NumModuleMDs); 37037d523365SDimitry Andric break; 3704f22ef01cSRoman Divacky } 3705f22ef01cSRoman Divacky Record.clear(); 3706f22ef01cSRoman Divacky } 3707f22ef01cSRoman Divacky } 3708f22ef01cSRoman Divacky 37097d523365SDimitry Andric /// Helper to read the header common to all bitcode files. 37107d523365SDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 37117d523365SDimitry Andric // Sniff for the signature. 37127d523365SDimitry Andric if (Stream.Read(8) != 'B' || 37137d523365SDimitry Andric Stream.Read(8) != 'C' || 37147d523365SDimitry Andric Stream.Read(4) != 0x0 || 37157d523365SDimitry Andric Stream.Read(4) != 0xC || 37167d523365SDimitry Andric Stream.Read(4) != 0xE || 37177d523365SDimitry Andric Stream.Read(4) != 0xD) 37187d523365SDimitry Andric return false; 37197d523365SDimitry Andric return true; 37207d523365SDimitry Andric } 37217d523365SDimitry Andric 37228f0fd8f6SDimitry Andric std::error_code 37238f0fd8f6SDimitry Andric BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 37248f0fd8f6SDimitry Andric Module *M, bool ShouldLazyLoadMetadata) { 37258f0fd8f6SDimitry Andric TheModule = M; 3726f22ef01cSRoman Divacky 37278f0fd8f6SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 3728f785676fSDimitry Andric return EC; 3729f22ef01cSRoman Divacky 3730f22ef01cSRoman Divacky // Sniff for the signature. 37317d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 37328f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 3733f22ef01cSRoman Divacky 3734f22ef01cSRoman Divacky // We expect a number of well-defined blocks, though we don't necessarily 3735f22ef01cSRoman Divacky // need to understand them all. 3736139f7f9bSDimitry Andric while (1) { 3737ff0cc061SDimitry Andric if (Stream.AtEndOfStream()) { 3738ff0cc061SDimitry Andric // We didn't really read a proper Module. 37398f0fd8f6SDimitry Andric return error("Malformed IR file"); 3740ff0cc061SDimitry Andric } 3741bd5abe19SDimitry Andric 3742139f7f9bSDimitry Andric BitstreamEntry Entry = 3743139f7f9bSDimitry Andric Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 3744f22ef01cSRoman Divacky 37458f0fd8f6SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock) 37468f0fd8f6SDimitry Andric return error("Malformed block"); 3747f22ef01cSRoman Divacky 37487d523365SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 37497d523365SDimitry Andric parseBitcodeVersion(); 37507d523365SDimitry Andric continue; 37517d523365SDimitry Andric } 37527d523365SDimitry Andric 37538f0fd8f6SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 37547d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata); 37558f0fd8f6SDimitry Andric 3756f22ef01cSRoman Divacky if (Stream.SkipBlock()) 37578f0fd8f6SDimitry Andric return error("Invalid record"); 3758139f7f9bSDimitry Andric } 3759f22ef01cSRoman Divacky } 3760f22ef01cSRoman Divacky 376191bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 37622754fe60SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 37638f0fd8f6SDimitry Andric return error("Invalid record"); 37642754fe60SDimitry Andric 37652754fe60SDimitry Andric SmallVector<uint64_t, 64> Record; 37662754fe60SDimitry Andric 376791bc56edSDimitry Andric std::string Triple; 37682754fe60SDimitry Andric // Read all the records for this module. 3769139f7f9bSDimitry Andric while (1) { 3770139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 37712754fe60SDimitry Andric 3772139f7f9bSDimitry Andric switch (Entry.Kind) { 3773139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3774139f7f9bSDimitry Andric case BitstreamEntry::Error: 37758f0fd8f6SDimitry Andric return error("Malformed block"); 3776139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 377791bc56edSDimitry Andric return Triple; 3778139f7f9bSDimitry Andric case BitstreamEntry::Record: 3779139f7f9bSDimitry Andric // The interesting case. 37802754fe60SDimitry Andric break; 37812754fe60SDimitry Andric } 37822754fe60SDimitry Andric 37832754fe60SDimitry Andric // Read a record. 3784139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 37852754fe60SDimitry Andric default: break; // Default behavior, ignore unknown content. 37862754fe60SDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 37872754fe60SDimitry Andric std::string S; 37888f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 37898f0fd8f6SDimitry Andric return error("Invalid record"); 37902754fe60SDimitry Andric Triple = S; 37912754fe60SDimitry Andric break; 37922754fe60SDimitry Andric } 37932754fe60SDimitry Andric } 37942754fe60SDimitry Andric Record.clear(); 37952754fe60SDimitry Andric } 379691bc56edSDimitry Andric llvm_unreachable("Exit infinite loop"); 37972754fe60SDimitry Andric } 37982754fe60SDimitry Andric 379991bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseTriple() { 38008f0fd8f6SDimitry Andric if (std::error_code EC = initStream(nullptr)) 3801f785676fSDimitry Andric return EC; 38022754fe60SDimitry Andric 38032754fe60SDimitry Andric // Sniff for the signature. 38047d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 38058f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 38062754fe60SDimitry Andric 38072754fe60SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 38082754fe60SDimitry Andric // need to understand them all. 3809139f7f9bSDimitry Andric while (1) { 3810139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 38112754fe60SDimitry Andric 3812139f7f9bSDimitry Andric switch (Entry.Kind) { 3813139f7f9bSDimitry Andric case BitstreamEntry::Error: 38148f0fd8f6SDimitry Andric return error("Malformed block"); 3815139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 381691bc56edSDimitry Andric return std::error_code(); 3817139f7f9bSDimitry Andric 3818139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3819139f7f9bSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 382091bc56edSDimitry Andric return parseModuleTriple(); 3821139f7f9bSDimitry Andric 3822139f7f9bSDimitry Andric // Ignore other sub-blocks. 3823f785676fSDimitry Andric if (Stream.SkipBlock()) 38248f0fd8f6SDimitry Andric return error("Malformed block"); 3825139f7f9bSDimitry Andric continue; 3826139f7f9bSDimitry Andric 3827139f7f9bSDimitry Andric case BitstreamEntry::Record: 3828139f7f9bSDimitry Andric Stream.skipRecord(Entry.ID); 3829139f7f9bSDimitry Andric continue; 3830139f7f9bSDimitry Andric } 3831139f7f9bSDimitry Andric } 38322754fe60SDimitry Andric } 38332754fe60SDimitry Andric 38347d523365SDimitry Andric ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() { 38357d523365SDimitry Andric if (std::error_code EC = initStream(nullptr)) 38367d523365SDimitry Andric return EC; 38377d523365SDimitry Andric 38387d523365SDimitry Andric // Sniff for the signature. 38397d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 38407d523365SDimitry Andric return error("Invalid bitcode signature"); 38417d523365SDimitry Andric 38427d523365SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 38437d523365SDimitry Andric // need to understand them all. 38447d523365SDimitry Andric while (1) { 38457d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 38467d523365SDimitry Andric switch (Entry.Kind) { 38477d523365SDimitry Andric case BitstreamEntry::Error: 38487d523365SDimitry Andric return error("Malformed block"); 38497d523365SDimitry Andric case BitstreamEntry::EndBlock: 38507d523365SDimitry Andric return std::error_code(); 38517d523365SDimitry Andric 38527d523365SDimitry Andric case BitstreamEntry::SubBlock: 38537d523365SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 38547d523365SDimitry Andric if (std::error_code EC = parseBitcodeVersion()) 38557d523365SDimitry Andric return EC; 38567d523365SDimitry Andric return ProducerIdentification; 38577d523365SDimitry Andric } 38587d523365SDimitry Andric // Ignore other sub-blocks. 38597d523365SDimitry Andric if (Stream.SkipBlock()) 38607d523365SDimitry Andric return error("Malformed block"); 38617d523365SDimitry Andric continue; 38627d523365SDimitry Andric case BitstreamEntry::Record: 38637d523365SDimitry Andric Stream.skipRecord(Entry.ID); 38647d523365SDimitry Andric continue; 38657d523365SDimitry Andric } 38667d523365SDimitry Andric } 38677d523365SDimitry Andric } 38687d523365SDimitry Andric 38698f0fd8f6SDimitry Andric /// Parse metadata attachments. 38708f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseMetadataAttachment(Function &F) { 3871f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 38728f0fd8f6SDimitry Andric return error("Invalid record"); 3873f22ef01cSRoman Divacky 3874f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3875f22ef01cSRoman Divacky while (1) { 3876139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3877139f7f9bSDimitry Andric 3878139f7f9bSDimitry Andric switch (Entry.Kind) { 3879139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3880139f7f9bSDimitry Andric case BitstreamEntry::Error: 38818f0fd8f6SDimitry Andric return error("Malformed block"); 3882139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 388391bc56edSDimitry Andric return std::error_code(); 3884139f7f9bSDimitry Andric case BitstreamEntry::Record: 3885139f7f9bSDimitry Andric // The interesting case. 3886f22ef01cSRoman Divacky break; 3887f22ef01cSRoman Divacky } 3888139f7f9bSDimitry Andric 3889f22ef01cSRoman Divacky // Read a metadata attachment record. 3890f22ef01cSRoman Divacky Record.clear(); 3891139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 3892f22ef01cSRoman Divacky default: // Default behavior: ignore. 3893f22ef01cSRoman Divacky break; 389417a519f9SDimitry Andric case bitc::METADATA_ATTACHMENT: { 3895f22ef01cSRoman Divacky unsigned RecordLength = Record.size(); 3896ff0cc061SDimitry Andric if (Record.empty()) 38978f0fd8f6SDimitry Andric return error("Invalid record"); 3898ff0cc061SDimitry Andric if (RecordLength % 2 == 0) { 3899ff0cc061SDimitry Andric // A function attachment. 3900ff0cc061SDimitry Andric for (unsigned I = 0; I != RecordLength; I += 2) { 3901ff0cc061SDimitry Andric auto K = MDKindMap.find(Record[I]); 3902ff0cc061SDimitry Andric if (K == MDKindMap.end()) 39038f0fd8f6SDimitry Andric return error("Invalid ID"); 39047d523365SDimitry Andric Metadata *MD = MetadataList.getValueFwdRef(Record[I + 1]); 3905ff0cc061SDimitry Andric F.setMetadata(K->second, cast<MDNode>(MD)); 3906ff0cc061SDimitry Andric } 3907ff0cc061SDimitry Andric continue; 3908ff0cc061SDimitry Andric } 3909ff0cc061SDimitry Andric 3910ff0cc061SDimitry Andric // An instruction attachment. 3911f22ef01cSRoman Divacky Instruction *Inst = InstructionList[Record[0]]; 3912f22ef01cSRoman Divacky for (unsigned i = 1; i != RecordLength; i = i+2) { 3913f22ef01cSRoman Divacky unsigned Kind = Record[i]; 3914e580952dSDimitry Andric DenseMap<unsigned, unsigned>::iterator I = 3915e580952dSDimitry Andric MDKindMap.find(Kind); 3916e580952dSDimitry Andric if (I == MDKindMap.end()) 39178f0fd8f6SDimitry Andric return error("Invalid ID"); 39187d523365SDimitry Andric Metadata *Node = MetadataList.getValueFwdRef(Record[i + 1]); 391939d628a0SDimitry Andric if (isa<LocalAsMetadata>(Node)) 392039d628a0SDimitry Andric // Drop the attachment. This used to be legal, but there's no 392139d628a0SDimitry Andric // upgrade path. 392239d628a0SDimitry Andric break; 3923e580952dSDimitry Andric Inst->setMetadata(I->second, cast<MDNode>(Node)); 3924f785676fSDimitry Andric if (I->second == LLVMContext::MD_tbaa) 3925f785676fSDimitry Andric InstsWithTBAATag.push_back(Inst); 3926f22ef01cSRoman Divacky } 3927f22ef01cSRoman Divacky break; 3928f22ef01cSRoman Divacky } 3929f22ef01cSRoman Divacky } 3930f22ef01cSRoman Divacky } 3931f22ef01cSRoman Divacky } 3932f22ef01cSRoman Divacky 39337d523365SDimitry Andric static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 39347d523365SDimitry Andric LLVMContext &Context = PtrType->getContext(); 3935ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType)) 39367d523365SDimitry Andric return error(Context, "Load/Store operand is not a pointer type"); 3937ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3938ff0cc061SDimitry Andric 3939ff0cc061SDimitry Andric if (ValType && ValType != ElemType) 39407d523365SDimitry Andric return error(Context, "Explicit load/store type does not match pointee " 39417d523365SDimitry Andric "type of pointer operand"); 3942ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType)) 39437d523365SDimitry Andric return error(Context, "Cannot load/store from pointer"); 3944ff0cc061SDimitry Andric return std::error_code(); 3945ff0cc061SDimitry Andric } 3946ff0cc061SDimitry Andric 39478f0fd8f6SDimitry Andric /// Lazily parse the specified function body block. 39488f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseFunctionBody(Function *F) { 3949f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 39508f0fd8f6SDimitry Andric return error("Invalid record"); 3951f22ef01cSRoman Divacky 3952f22ef01cSRoman Divacky InstructionList.clear(); 3953f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size(); 39547d523365SDimitry Andric unsigned ModuleMetadataListSize = MetadataList.size(); 3955f22ef01cSRoman Divacky 3956f22ef01cSRoman Divacky // Add all the function arguments to the value table. 39577d523365SDimitry Andric for (Argument &I : F->args()) 39587d523365SDimitry Andric ValueList.push_back(&I); 3959f22ef01cSRoman Divacky 3960f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size(); 396191bc56edSDimitry Andric BasicBlock *CurBB = nullptr; 3962f22ef01cSRoman Divacky unsigned CurBBNo = 0; 3963f22ef01cSRoman Divacky 3964f22ef01cSRoman Divacky DebugLoc LastLoc; 396539d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 396639d628a0SDimitry Andric if (CurBB && !CurBB->empty()) 396739d628a0SDimitry Andric return &CurBB->back(); 396839d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 396939d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 397039d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 397139d628a0SDimitry Andric return nullptr; 397239d628a0SDimitry Andric }; 3973f22ef01cSRoman Divacky 39747d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 39757d523365SDimitry Andric 3976f22ef01cSRoman Divacky // Read all the records. 3977f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3978f22ef01cSRoman Divacky while (1) { 3979139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3980f22ef01cSRoman Divacky 3981139f7f9bSDimitry Andric switch (Entry.Kind) { 3982139f7f9bSDimitry Andric case BitstreamEntry::Error: 39838f0fd8f6SDimitry Andric return error("Malformed block"); 3984139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 3985139f7f9bSDimitry Andric goto OutOfRecordLoop; 3986139f7f9bSDimitry Andric 3987139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3988139f7f9bSDimitry Andric switch (Entry.ID) { 3989f22ef01cSRoman Divacky default: // Skip unknown content. 3990f22ef01cSRoman Divacky if (Stream.SkipBlock()) 39918f0fd8f6SDimitry Andric return error("Invalid record"); 3992f22ef01cSRoman Divacky break; 3993f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 39948f0fd8f6SDimitry Andric if (std::error_code EC = parseConstants()) 3995f785676fSDimitry Andric return EC; 3996f22ef01cSRoman Divacky NextValueNo = ValueList.size(); 3997f22ef01cSRoman Divacky break; 3998f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 39998f0fd8f6SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 4000f785676fSDimitry Andric return EC; 4001f22ef01cSRoman Divacky break; 4002f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID: 40038f0fd8f6SDimitry Andric if (std::error_code EC = parseMetadataAttachment(*F)) 4004f785676fSDimitry Andric return EC; 4005f22ef01cSRoman Divacky break; 4006f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 40078f0fd8f6SDimitry Andric if (std::error_code EC = parseMetadata()) 4008f785676fSDimitry Andric return EC; 4009f22ef01cSRoman Divacky break; 401039d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID: 40118f0fd8f6SDimitry Andric if (std::error_code EC = parseUseLists()) 401239d628a0SDimitry Andric return EC; 401339d628a0SDimitry Andric break; 4014f22ef01cSRoman Divacky } 4015f22ef01cSRoman Divacky continue; 4016f22ef01cSRoman Divacky 4017139f7f9bSDimitry Andric case BitstreamEntry::Record: 4018139f7f9bSDimitry Andric // The interesting case. 4019139f7f9bSDimitry Andric break; 4020f22ef01cSRoman Divacky } 4021f22ef01cSRoman Divacky 4022f22ef01cSRoman Divacky // Read a record. 4023f22ef01cSRoman Divacky Record.clear(); 402491bc56edSDimitry Andric Instruction *I = nullptr; 4025139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4026f22ef01cSRoman Divacky switch (BitCode) { 4027f22ef01cSRoman Divacky default: // Default behavior: reject 40288f0fd8f6SDimitry Andric return error("Invalid value"); 402939d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4030f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0) 40318f0fd8f6SDimitry Andric return error("Invalid record"); 4032f22ef01cSRoman Divacky // Create all the basic blocks for the function. 4033f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]); 403439d628a0SDimitry Andric 403539d628a0SDimitry Andric // See if anything took the address of blocks in this function. 403639d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 403739d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 4038f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4039f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 404039d628a0SDimitry Andric } else { 404139d628a0SDimitry Andric auto &BBRefs = BBFRI->second; 404239d628a0SDimitry Andric // Check for invalid basic block references. 404339d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 40448f0fd8f6SDimitry Andric return error("Invalid ID"); 404539d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 404639d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 404739d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 404839d628a0SDimitry Andric ++I) 404939d628a0SDimitry Andric if (I < RE && BBRefs[I]) { 405039d628a0SDimitry Andric BBRefs[I]->insertInto(F); 405139d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I]; 405239d628a0SDimitry Andric } else { 405339d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 405439d628a0SDimitry Andric } 405539d628a0SDimitry Andric 405639d628a0SDimitry Andric // Erase from the table. 405739d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 405839d628a0SDimitry Andric } 405939d628a0SDimitry Andric 4060f22ef01cSRoman Divacky CurBB = FunctionBBs[0]; 4061f22ef01cSRoman Divacky continue; 406239d628a0SDimitry Andric } 4063f22ef01cSRoman Divacky 4064f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4065f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same 4066f22ef01cSRoman Divacky // location as the previous instruction with a location. 406739d628a0SDimitry Andric I = getLastInstruction(); 4068f22ef01cSRoman Divacky 406991bc56edSDimitry Andric if (!I) 40708f0fd8f6SDimitry Andric return error("Invalid record"); 4071f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 407291bc56edSDimitry Andric I = nullptr; 4073f22ef01cSRoman Divacky continue; 4074f22ef01cSRoman Divacky 407517a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 407639d628a0SDimitry Andric I = getLastInstruction(); 407791bc56edSDimitry Andric if (!I || Record.size() < 4) 40788f0fd8f6SDimitry Andric return error("Invalid record"); 4079f22ef01cSRoman Divacky 4080f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1]; 4081f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3]; 4082f22ef01cSRoman Divacky 408391bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 40847d523365SDimitry Andric if (ScopeID) 40857d523365SDimitry Andric Scope = cast<MDNode>(MetadataList.getValueFwdRef(ScopeID - 1)); 40867d523365SDimitry Andric if (IAID) 40877d523365SDimitry Andric IA = cast<MDNode>(MetadataList.getValueFwdRef(IAID - 1)); 4088f22ef01cSRoman Divacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4089f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 409091bc56edSDimitry Andric I = nullptr; 4091f22ef01cSRoman Divacky continue; 4092f22ef01cSRoman Divacky } 4093f22ef01cSRoman Divacky 4094f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4095f22ef01cSRoman Divacky unsigned OpNum = 0; 4096f22ef01cSRoman Divacky Value *LHS, *RHS; 4097f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 40983861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4099f22ef01cSRoman Divacky OpNum+1 > Record.size()) 41008f0fd8f6SDimitry Andric return error("Invalid record"); 4101f22ef01cSRoman Divacky 41028f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4103f785676fSDimitry Andric if (Opc == -1) 41048f0fd8f6SDimitry Andric return error("Invalid record"); 4105f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4106f22ef01cSRoman Divacky InstructionList.push_back(I); 4107f22ef01cSRoman Divacky if (OpNum < Record.size()) { 4108f22ef01cSRoman Divacky if (Opc == Instruction::Add || 4109f22ef01cSRoman Divacky Opc == Instruction::Sub || 41102754fe60SDimitry Andric Opc == Instruction::Mul || 41112754fe60SDimitry Andric Opc == Instruction::Shl) { 4112f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4113f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4114f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4115f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 41162754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 41172754fe60SDimitry Andric Opc == Instruction::UDiv || 41182754fe60SDimitry Andric Opc == Instruction::LShr || 41192754fe60SDimitry Andric Opc == Instruction::AShr) { 41202754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4121f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true); 4122139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) { 4123875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4124139f7f9bSDimitry Andric if (FMF.any()) 4125139f7f9bSDimitry Andric I->setFastMathFlags(FMF); 4126f22ef01cSRoman Divacky } 4127139f7f9bSDimitry Andric 4128f22ef01cSRoman Divacky } 4129f22ef01cSRoman Divacky break; 4130f22ef01cSRoman Divacky } 4131f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4132f22ef01cSRoman Divacky unsigned OpNum = 0; 4133f22ef01cSRoman Divacky Value *Op; 4134f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4135f22ef01cSRoman Divacky OpNum+2 != Record.size()) 41368f0fd8f6SDimitry Andric return error("Invalid record"); 4137f22ef01cSRoman Divacky 41386122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]); 41398f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 414091bc56edSDimitry Andric if (Opc == -1 || !ResTy) 41418f0fd8f6SDimitry Andric return error("Invalid record"); 414291bc56edSDimitry Andric Instruction *Temp = nullptr; 4143f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4144f785676fSDimitry Andric if (Temp) { 4145f785676fSDimitry Andric InstructionList.push_back(Temp); 4146f785676fSDimitry Andric CurBB->getInstList().push_back(Temp); 4147f785676fSDimitry Andric } 4148f785676fSDimitry Andric } else { 41497d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 41507d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 41517d523365SDimitry Andric return error("Invalid cast"); 41527d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 4153f785676fSDimitry Andric } 4154f22ef01cSRoman Divacky InstructionList.push_back(I); 4155f22ef01cSRoman Divacky break; 4156f22ef01cSRoman Divacky } 4157ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4158ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 4159ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4160f22ef01cSRoman Divacky unsigned OpNum = 0; 4161ff0cc061SDimitry Andric 4162ff0cc061SDimitry Andric Type *Ty; 4163ff0cc061SDimitry Andric bool InBounds; 4164ff0cc061SDimitry Andric 4165ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4166ff0cc061SDimitry Andric InBounds = Record[OpNum++]; 4167ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4168ff0cc061SDimitry Andric } else { 4169ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4170ff0cc061SDimitry Andric Ty = nullptr; 4171ff0cc061SDimitry Andric } 4172ff0cc061SDimitry Andric 4173f22ef01cSRoman Divacky Value *BasePtr; 4174f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 41758f0fd8f6SDimitry Andric return error("Invalid record"); 4176f22ef01cSRoman Divacky 4177ff0cc061SDimitry Andric if (!Ty) 4178ff0cc061SDimitry Andric Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 4179ff0cc061SDimitry Andric ->getElementType(); 4180ff0cc061SDimitry Andric else if (Ty != 4181ff0cc061SDimitry Andric cast<SequentialType>(BasePtr->getType()->getScalarType()) 4182ff0cc061SDimitry Andric ->getElementType()) 41838f0fd8f6SDimitry Andric return error( 4184ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand"); 4185ff0cc061SDimitry Andric 4186f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx; 4187f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4188f22ef01cSRoman Divacky Value *Op; 4189f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 41908f0fd8f6SDimitry Andric return error("Invalid record"); 4191f22ef01cSRoman Divacky GEPIdx.push_back(Op); 4192f22ef01cSRoman Divacky } 4193f22ef01cSRoman Divacky 4194ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4195ff0cc061SDimitry Andric 4196f22ef01cSRoman Divacky InstructionList.push_back(I); 4197ff0cc061SDimitry Andric if (InBounds) 4198f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 4199f22ef01cSRoman Divacky break; 4200f22ef01cSRoman Divacky } 4201f22ef01cSRoman Divacky 4202f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4203f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices] 4204f22ef01cSRoman Divacky unsigned OpNum = 0; 4205f22ef01cSRoman Divacky Value *Agg; 4206f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 42078f0fd8f6SDimitry Andric return error("Invalid record"); 4208f22ef01cSRoman Divacky 4209ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 4210ff0cc061SDimitry Andric if (OpNum == RecSize) 42118f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4212ff0cc061SDimitry Andric 4213f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx; 4214ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 4215ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4216ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 4217ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 4218f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 4219ff0cc061SDimitry Andric 4220ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 42218f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type"); 4222f22ef01cSRoman Divacky if ((unsigned)Index != Index) 42238f0fd8f6SDimitry Andric return error("Invalid value"); 4224ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 42258f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 4226ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 42278f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 4228f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index); 4229ff0cc061SDimitry Andric 4230ff0cc061SDimitry Andric if (IsStruct) 4231ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 4232ff0cc061SDimitry Andric else 4233ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 4234f22ef01cSRoman Divacky } 4235f22ef01cSRoman Divacky 423617a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4237f22ef01cSRoman Divacky InstructionList.push_back(I); 4238f22ef01cSRoman Divacky break; 4239f22ef01cSRoman Divacky } 4240f22ef01cSRoman Divacky 4241f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: { 4242f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices] 4243f22ef01cSRoman Divacky unsigned OpNum = 0; 4244f22ef01cSRoman Divacky Value *Agg; 4245f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 42468f0fd8f6SDimitry Andric return error("Invalid record"); 4247f22ef01cSRoman Divacky Value *Val; 4248f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 42498f0fd8f6SDimitry Andric return error("Invalid record"); 4250f22ef01cSRoman Divacky 4251ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 4252ff0cc061SDimitry Andric if (OpNum == RecSize) 42538f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 4254ff0cc061SDimitry Andric 4255f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx; 4256ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 4257ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4258ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 4259ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 4260f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 4261ff0cc061SDimitry Andric 4262ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 42638f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type"); 4264f22ef01cSRoman Divacky if ((unsigned)Index != Index) 42658f0fd8f6SDimitry Andric return error("Invalid value"); 4266ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 42678f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index"); 4268ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 42698f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index"); 4270ff0cc061SDimitry Andric 4271f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index); 4272ff0cc061SDimitry Andric if (IsStruct) 4273ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 4274ff0cc061SDimitry Andric else 4275ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 4276f22ef01cSRoman Divacky } 4277f22ef01cSRoman Divacky 4278ff0cc061SDimitry Andric if (CurTy != Val->getType()) 42798f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 4280ff0cc061SDimitry Andric 428117a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4282f22ef01cSRoman Divacky InstructionList.push_back(I); 4283f22ef01cSRoman Divacky break; 4284f22ef01cSRoman Divacky } 4285f22ef01cSRoman Divacky 4286f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4287f22ef01cSRoman Divacky // obsolete form of select 4288f22ef01cSRoman Divacky // handles select i1 ... in old bitcode 4289f22ef01cSRoman Divacky unsigned OpNum = 0; 4290f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 4291f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 42923861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 42933861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 42948f0fd8f6SDimitry Andric return error("Invalid record"); 4295f22ef01cSRoman Divacky 4296f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 4297f22ef01cSRoman Divacky InstructionList.push_back(I); 4298f22ef01cSRoman Divacky break; 4299f22ef01cSRoman Divacky } 4300f22ef01cSRoman Divacky 4301f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4302f22ef01cSRoman Divacky // new form of select 4303f22ef01cSRoman Divacky // handles select i1 or select [N x i1] 4304f22ef01cSRoman Divacky unsigned OpNum = 0; 4305f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 4306f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 43073861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4308f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond)) 43098f0fd8f6SDimitry Andric return error("Invalid record"); 4310f22ef01cSRoman Divacky 4311f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1] 43126122f3e6SDimitry Andric if (VectorType* vector_type = 43136122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 4314f22ef01cSRoman Divacky // expect <n x i1> 4315f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 43168f0fd8f6SDimitry Andric return error("Invalid type for value"); 4317f22ef01cSRoman Divacky } else { 4318f22ef01cSRoman Divacky // expect i1 4319f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context)) 43208f0fd8f6SDimitry Andric return error("Invalid type for value"); 4321f22ef01cSRoman Divacky } 4322f22ef01cSRoman Divacky 4323f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 4324f22ef01cSRoman Divacky InstructionList.push_back(I); 4325f22ef01cSRoman Divacky break; 4326f22ef01cSRoman Divacky } 4327f22ef01cSRoman Divacky 4328f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4329f22ef01cSRoman Divacky unsigned OpNum = 0; 4330f22ef01cSRoman Divacky Value *Vec, *Idx; 4331f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 433291bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 43338f0fd8f6SDimitry Andric return error("Invalid record"); 4334ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 43358f0fd8f6SDimitry Andric return error("Invalid type for value"); 4336f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx); 4337f22ef01cSRoman Divacky InstructionList.push_back(I); 4338f22ef01cSRoman Divacky break; 4339f22ef01cSRoman Divacky } 4340f22ef01cSRoman Divacky 4341f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4342f22ef01cSRoman Divacky unsigned OpNum = 0; 4343f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx; 4344ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 43458f0fd8f6SDimitry Andric return error("Invalid record"); 4346ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 43478f0fd8f6SDimitry Andric return error("Invalid type for value"); 4348ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 4349f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) || 435091bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 43518f0fd8f6SDimitry Andric return error("Invalid record"); 4352f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx); 4353f22ef01cSRoman Divacky InstructionList.push_back(I); 4354f22ef01cSRoman Divacky break; 4355f22ef01cSRoman Divacky } 4356f22ef01cSRoman Divacky 4357f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4358f22ef01cSRoman Divacky unsigned OpNum = 0; 4359f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask; 4360f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 43613861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 43628f0fd8f6SDimitry Andric return error("Invalid record"); 4363f22ef01cSRoman Divacky 4364f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 43658f0fd8f6SDimitry Andric return error("Invalid record"); 4366ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 43678f0fd8f6SDimitry Andric return error("Invalid type for value"); 4368f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4369f22ef01cSRoman Divacky InstructionList.push_back(I); 4370f22ef01cSRoman Divacky break; 4371f22ef01cSRoman Divacky } 4372f22ef01cSRoman Divacky 4373f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4374f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool 4375f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4376f22ef01cSRoman Divacky // both legal on vectors but had different behaviour. 4377f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4378f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool 4379f22ef01cSRoman Divacky 4380f22ef01cSRoman Divacky unsigned OpNum = 0; 4381f22ef01cSRoman Divacky Value *LHS, *RHS; 4382f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4383875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4384875ed548SDimitry Andric return error("Invalid record"); 4385875ed548SDimitry Andric 4386875ed548SDimitry Andric unsigned PredVal = Record[OpNum]; 4387875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4388875ed548SDimitry Andric FastMathFlags FMF; 4389875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1) 4390875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 4391875ed548SDimitry Andric 4392875ed548SDimitry Andric if (OpNum+1 != Record.size()) 43938f0fd8f6SDimitry Andric return error("Invalid record"); 4394f22ef01cSRoman Divacky 4395f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy()) 4396875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4397f22ef01cSRoman Divacky else 4398875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4399875ed548SDimitry Andric 4400875ed548SDimitry Andric if (FMF.any()) 4401875ed548SDimitry Andric I->setFastMathFlags(FMF); 4402f22ef01cSRoman Divacky InstructionList.push_back(I); 4403f22ef01cSRoman Divacky break; 4404f22ef01cSRoman Divacky } 4405f22ef01cSRoman Divacky 4406f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4407f22ef01cSRoman Divacky { 4408f22ef01cSRoman Divacky unsigned Size = Record.size(); 4409f22ef01cSRoman Divacky if (Size == 0) { 4410f22ef01cSRoman Divacky I = ReturnInst::Create(Context); 4411f22ef01cSRoman Divacky InstructionList.push_back(I); 4412f22ef01cSRoman Divacky break; 4413f22ef01cSRoman Divacky } 4414f22ef01cSRoman Divacky 4415f22ef01cSRoman Divacky unsigned OpNum = 0; 441691bc56edSDimitry Andric Value *Op = nullptr; 4417f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 44188f0fd8f6SDimitry Andric return error("Invalid record"); 441917a519f9SDimitry Andric if (OpNum != Record.size()) 44208f0fd8f6SDimitry Andric return error("Invalid record"); 4421f22ef01cSRoman Divacky 442217a519f9SDimitry Andric I = ReturnInst::Create(Context, Op); 4423f22ef01cSRoman Divacky InstructionList.push_back(I); 4424f22ef01cSRoman Divacky break; 4425f22ef01cSRoman Divacky } 4426f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4427f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3) 44288f0fd8f6SDimitry Andric return error("Invalid record"); 4429f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]); 443091bc56edSDimitry Andric if (!TrueDest) 44318f0fd8f6SDimitry Andric return error("Invalid record"); 4432f22ef01cSRoman Divacky 4433f22ef01cSRoman Divacky if (Record.size() == 1) { 4434f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest); 4435f22ef01cSRoman Divacky InstructionList.push_back(I); 4436f22ef01cSRoman Divacky } 4437f22ef01cSRoman Divacky else { 4438f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]); 44393861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, 44403861d79fSDimitry Andric Type::getInt1Ty(Context)); 444191bc56edSDimitry Andric if (!FalseDest || !Cond) 44428f0fd8f6SDimitry Andric return error("Invalid record"); 4443f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond); 4444f22ef01cSRoman Divacky InstructionList.push_back(I); 4445f22ef01cSRoman Divacky } 4446f22ef01cSRoman Divacky break; 4447f22ef01cSRoman Divacky } 44487d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 44497d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 44507d523365SDimitry Andric return error("Invalid record"); 44517d523365SDimitry Andric unsigned Idx = 0; 44527d523365SDimitry Andric Value *CleanupPad = 44537d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44547d523365SDimitry Andric if (!CleanupPad) 44557d523365SDimitry Andric return error("Invalid record"); 44567d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 44577d523365SDimitry Andric if (Record.size() == 2) { 44587d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 44597d523365SDimitry Andric if (!UnwindDest) 44607d523365SDimitry Andric return error("Invalid record"); 44617d523365SDimitry Andric } 44627d523365SDimitry Andric 44637d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 44647d523365SDimitry Andric InstructionList.push_back(I); 44657d523365SDimitry Andric break; 44667d523365SDimitry Andric } 44677d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 44687d523365SDimitry Andric if (Record.size() != 2) 44697d523365SDimitry Andric return error("Invalid record"); 44707d523365SDimitry Andric unsigned Idx = 0; 44717d523365SDimitry Andric Value *CatchPad = 44727d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44737d523365SDimitry Andric if (!CatchPad) 44747d523365SDimitry Andric return error("Invalid record"); 44757d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 44767d523365SDimitry Andric if (!BB) 44777d523365SDimitry Andric return error("Invalid record"); 44787d523365SDimitry Andric 44797d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 44807d523365SDimitry Andric InstructionList.push_back(I); 44817d523365SDimitry Andric break; 44827d523365SDimitry Andric } 44837d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 44847d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 44857d523365SDimitry Andric if (Record.size() < 2) 44867d523365SDimitry Andric return error("Invalid record"); 44877d523365SDimitry Andric 44887d523365SDimitry Andric unsigned Idx = 0; 44897d523365SDimitry Andric 44907d523365SDimitry Andric Value *ParentPad = 44917d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44927d523365SDimitry Andric 44937d523365SDimitry Andric unsigned NumHandlers = Record[Idx++]; 44947d523365SDimitry Andric 44957d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 44967d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 44977d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 44987d523365SDimitry Andric if (!BB) 44997d523365SDimitry Andric return error("Invalid record"); 45007d523365SDimitry Andric Handlers.push_back(BB); 45017d523365SDimitry Andric } 45027d523365SDimitry Andric 45037d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 45047d523365SDimitry Andric if (Idx + 1 == Record.size()) { 45057d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 45067d523365SDimitry Andric if (!UnwindDest) 45077d523365SDimitry Andric return error("Invalid record"); 45087d523365SDimitry Andric } 45097d523365SDimitry Andric 45107d523365SDimitry Andric if (Record.size() != Idx) 45117d523365SDimitry Andric return error("Invalid record"); 45127d523365SDimitry Andric 45137d523365SDimitry Andric auto *CatchSwitch = 45147d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 45157d523365SDimitry Andric for (BasicBlock *Handler : Handlers) 45167d523365SDimitry Andric CatchSwitch->addHandler(Handler); 45177d523365SDimitry Andric I = CatchSwitch; 45187d523365SDimitry Andric InstructionList.push_back(I); 45197d523365SDimitry Andric break; 45207d523365SDimitry Andric } 45217d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 45227d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 45237d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 45247d523365SDimitry Andric if (Record.size() < 2) 45257d523365SDimitry Andric return error("Invalid record"); 45267d523365SDimitry Andric 45277d523365SDimitry Andric unsigned Idx = 0; 45287d523365SDimitry Andric 45297d523365SDimitry Andric Value *ParentPad = 45307d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 45317d523365SDimitry Andric 45327d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 45337d523365SDimitry Andric 45347d523365SDimitry Andric SmallVector<Value *, 2> Args; 45357d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 45367d523365SDimitry Andric Value *Val; 45377d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 45387d523365SDimitry Andric return error("Invalid record"); 45397d523365SDimitry Andric Args.push_back(Val); 45407d523365SDimitry Andric } 45417d523365SDimitry Andric 45427d523365SDimitry Andric if (Record.size() != Idx) 45437d523365SDimitry Andric return error("Invalid record"); 45447d523365SDimitry Andric 45457d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 45467d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 45477d523365SDimitry Andric else 45487d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 45497d523365SDimitry Andric InstructionList.push_back(I); 45507d523365SDimitry Andric break; 45517d523365SDimitry Andric } 4552f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 45537ae0e2c9SDimitry Andric // Check magic 45547ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4555f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 4556f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it. 4557f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use 4558f785676fSDimitry Andric // this format again. 45597ae0e2c9SDimitry Andric 45607ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 45617ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 45627ae0e2c9SDimitry Andric 45633861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 45647ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 456591bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 45668f0fd8f6SDimitry Andric return error("Invalid record"); 45677ae0e2c9SDimitry Andric 45687ae0e2c9SDimitry Andric unsigned NumCases = Record[4]; 45697ae0e2c9SDimitry Andric 45707ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 45717ae0e2c9SDimitry Andric InstructionList.push_back(SI); 45727ae0e2c9SDimitry Andric 45737ae0e2c9SDimitry Andric unsigned CurIdx = 5; 45747ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 4575f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 45767ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++]; 45777ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 45787ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 45797ae0e2c9SDimitry Andric 45807ae0e2c9SDimitry Andric APInt Low; 45817ae0e2c9SDimitry Andric unsigned ActiveWords = 1; 45827ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 45837ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 45848f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 45857ae0e2c9SDimitry Andric ValueBitWidth); 45867ae0e2c9SDimitry Andric CurIdx += ActiveWords; 45877ae0e2c9SDimitry Andric 45887ae0e2c9SDimitry Andric if (!isSingleNumber) { 45897ae0e2c9SDimitry Andric ActiveWords = 1; 45907ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 45917ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 45928f0fd8f6SDimitry Andric APInt High = readWideAPInt( 45938f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 45947ae0e2c9SDimitry Andric CurIdx += ActiveWords; 4595f785676fSDimitry Andric 4596f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be 4597f785676fSDimitry Andric // compared as signed or unsigned values. The partially 4598f785676fSDimitry Andric // implemented changes that used this format in the past used 4599f785676fSDimitry Andric // unsigned comparisons. 4600f785676fSDimitry Andric for ( ; Low.ule(High); ++Low) 4601f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 46027ae0e2c9SDimitry Andric } else 4603f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 46047ae0e2c9SDimitry Andric } 46057ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4606f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4607f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi) 4608f785676fSDimitry Andric SI->addCase(*cvi, DestBB); 46097ae0e2c9SDimitry Andric } 46107ae0e2c9SDimitry Andric I = SI; 46117ae0e2c9SDimitry Andric break; 46127ae0e2c9SDimitry Andric } 46137ae0e2c9SDimitry Andric 46147ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges. 46157ae0e2c9SDimitry Andric 4616f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0) 46178f0fd8f6SDimitry Andric return error("Invalid record"); 46186122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 46193861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4620f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]); 462191bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 46228f0fd8f6SDimitry Andric return error("Invalid record"); 4623f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2; 4624f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4625f22ef01cSRoman Divacky InstructionList.push_back(SI); 4626f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) { 4627f22ef01cSRoman Divacky ConstantInt *CaseVal = 4628f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4629f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 463091bc56edSDimitry Andric if (!CaseVal || !DestBB) { 4631f22ef01cSRoman Divacky delete SI; 46328f0fd8f6SDimitry Andric return error("Invalid record"); 4633f22ef01cSRoman Divacky } 4634f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB); 4635f22ef01cSRoman Divacky } 4636f22ef01cSRoman Divacky I = SI; 4637f22ef01cSRoman Divacky break; 4638f22ef01cSRoman Divacky } 4639f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4640f22ef01cSRoman Divacky if (Record.size() < 2) 46418f0fd8f6SDimitry Andric return error("Invalid record"); 46426122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 46433861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy); 464491bc56edSDimitry Andric if (!OpTy || !Address) 46458f0fd8f6SDimitry Andric return error("Invalid record"); 4646f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2; 4647f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4648f22ef01cSRoman Divacky InstructionList.push_back(IBI); 4649f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 4650f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4651f22ef01cSRoman Divacky IBI->addDestination(DestBB); 4652f22ef01cSRoman Divacky } else { 4653f22ef01cSRoman Divacky delete IBI; 46548f0fd8f6SDimitry Andric return error("Invalid record"); 4655f22ef01cSRoman Divacky } 4656f22ef01cSRoman Divacky } 4657f22ef01cSRoman Divacky I = IBI; 4658f22ef01cSRoman Divacky break; 4659f22ef01cSRoman Divacky } 4660f22ef01cSRoman Divacky 4661f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: { 4662f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4663f785676fSDimitry Andric if (Record.size() < 4) 46648f0fd8f6SDimitry Andric return error("Invalid record"); 4665ff0cc061SDimitry Andric unsigned OpNum = 0; 4666ff0cc061SDimitry Andric AttributeSet PAL = getAttributes(Record[OpNum++]); 4667ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4668ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4669ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4670f22ef01cSRoman Divacky 4671ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 4672ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 && 4673ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 46748f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type"); 4675ff0cc061SDimitry Andric 4676f22ef01cSRoman Divacky Value *Callee; 4677f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 46788f0fd8f6SDimitry Andric return error("Invalid record"); 4679f22ef01cSRoman Divacky 46806122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4681ff0cc061SDimitry Andric if (!CalleeTy) 46828f0fd8f6SDimitry Andric return error("Callee is not a pointer"); 4683ff0cc061SDimitry Andric if (!FTy) { 4684ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4685ff0cc061SDimitry Andric if (!FTy) 46868f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4687ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy) 46888f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of " 4689ff0cc061SDimitry Andric "callee operand"); 4690ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 46918f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4692f22ef01cSRoman Divacky 4693f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops; 4694f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 46953861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, 46963861d79fSDimitry Andric FTy->getParamType(i))); 469791bc56edSDimitry Andric if (!Ops.back()) 46988f0fd8f6SDimitry Andric return error("Invalid record"); 4699f22ef01cSRoman Divacky } 4700f22ef01cSRoman Divacky 4701f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4702f22ef01cSRoman Divacky if (Record.size() != OpNum) 47038f0fd8f6SDimitry Andric return error("Invalid record"); 4704f22ef01cSRoman Divacky } else { 4705f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4706f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4707f22ef01cSRoman Divacky Value *Op; 4708f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 47098f0fd8f6SDimitry Andric return error("Invalid record"); 4710f22ef01cSRoman Divacky Ops.push_back(Op); 4711f22ef01cSRoman Divacky } 4712f22ef01cSRoman Divacky } 4713f22ef01cSRoman Divacky 47147d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 47157d523365SDimitry Andric OperandBundles.clear(); 4716f22ef01cSRoman Divacky InstructionList.push_back(I); 47177d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 47187d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4719f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL); 4720f22ef01cSRoman Divacky break; 4721f22ef01cSRoman Divacky } 47226122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 47236122f3e6SDimitry Andric unsigned Idx = 0; 472491bc56edSDimitry Andric Value *Val = nullptr; 47256122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 47268f0fd8f6SDimitry Andric return error("Invalid record"); 47276122f3e6SDimitry Andric I = ResumeInst::Create(Val); 47286122f3e6SDimitry Andric InstructionList.push_back(I); 47296122f3e6SDimitry Andric break; 47306122f3e6SDimitry Andric } 4731f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4732f22ef01cSRoman Divacky I = new UnreachableInst(Context); 4733f22ef01cSRoman Divacky InstructionList.push_back(I); 4734f22ef01cSRoman Divacky break; 4735f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4736f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1)) 47378f0fd8f6SDimitry Andric return error("Invalid record"); 47386122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4739f785676fSDimitry Andric if (!Ty) 47408f0fd8f6SDimitry Andric return error("Invalid record"); 4741f22ef01cSRoman Divacky 47423b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4743f22ef01cSRoman Divacky InstructionList.push_back(PN); 4744f22ef01cSRoman Divacky 4745f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 47463861d79fSDimitry Andric Value *V; 47473861d79fSDimitry Andric // With the new function encoding, it is possible that operands have 47483861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR 47493861d79fSDimitry Andric // representation to keep the encoding small. 47503861d79fSDimitry Andric if (UseRelativeIDs) 47513861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty); 47523861d79fSDimitry Andric else 47533861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty); 4754f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]); 4755f785676fSDimitry Andric if (!V || !BB) 47568f0fd8f6SDimitry Andric return error("Invalid record"); 4757f22ef01cSRoman Divacky PN->addIncoming(V, BB); 4758f22ef01cSRoman Divacky } 4759f22ef01cSRoman Divacky I = PN; 4760f22ef01cSRoman Divacky break; 4761f22ef01cSRoman Divacky } 4762f22ef01cSRoman Divacky 47638f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 47648f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 47656122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 47666122f3e6SDimitry Andric unsigned Idx = 0; 47678f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 47688f0fd8f6SDimitry Andric if (Record.size() < 3) 47698f0fd8f6SDimitry Andric return error("Invalid record"); 47708f0fd8f6SDimitry Andric } else { 47718f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 47726122f3e6SDimitry Andric if (Record.size() < 4) 47738f0fd8f6SDimitry Andric return error("Invalid record"); 47748f0fd8f6SDimitry Andric } 47756122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]); 4776f785676fSDimitry Andric if (!Ty) 47778f0fd8f6SDimitry Andric return error("Invalid record"); 47788f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 477991bc56edSDimitry Andric Value *PersFn = nullptr; 47806122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 47818f0fd8f6SDimitry Andric return error("Invalid record"); 47828f0fd8f6SDimitry Andric 47838f0fd8f6SDimitry Andric if (!F->hasPersonalityFn()) 47848f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 47858f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 47868f0fd8f6SDimitry Andric return error("Personality function mismatch"); 47878f0fd8f6SDimitry Andric } 47886122f3e6SDimitry Andric 47896122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++]; 47906122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++]; 47918f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 47926122f3e6SDimitry Andric LP->setCleanup(IsCleanup); 47936122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 47946122f3e6SDimitry Andric LandingPadInst::ClauseType CT = 47956122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 47966122f3e6SDimitry Andric Value *Val; 47976122f3e6SDimitry Andric 47986122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 47996122f3e6SDimitry Andric delete LP; 48008f0fd8f6SDimitry Andric return error("Invalid record"); 48016122f3e6SDimitry Andric } 48026122f3e6SDimitry Andric 48036122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch || 48046122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) && 48056122f3e6SDimitry Andric "Catch clause has a invalid type!"); 48066122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter || 48076122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) && 48086122f3e6SDimitry Andric "Filter clause has invalid type!"); 480991bc56edSDimitry Andric LP->addClause(cast<Constant>(Val)); 48106122f3e6SDimitry Andric } 48116122f3e6SDimitry Andric 48126122f3e6SDimitry Andric I = LP; 48136122f3e6SDimitry Andric InstructionList.push_back(I); 48146122f3e6SDimitry Andric break; 48156122f3e6SDimitry Andric } 48166122f3e6SDimitry Andric 481717a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 481817a519f9SDimitry Andric if (Record.size() != 4) 48198f0fd8f6SDimitry Andric return error("Invalid record"); 4820ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3]; 4821ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5; 4822ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 48237d523365SDimitry Andric // Reserve bit 7 for SwiftError flag. 48247d523365SDimitry Andric // const uint64_t SwiftErrorMask = uint64_t(1) << 7; 4825ff0cc061SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask; 4826ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask; 4827ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4828ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) { 4829ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4830ff0cc061SDimitry Andric if (!PTy) 48318f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type"); 4832ff0cc061SDimitry Andric Ty = PTy->getElementType(); 4833ff0cc061SDimitry Andric } 48346122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 483517a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy); 4836ff0cc061SDimitry Andric unsigned Align; 4837ff0cc061SDimitry Andric if (std::error_code EC = 4838ff0cc061SDimitry Andric parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4839ff0cc061SDimitry Andric return EC; 4840ff0cc061SDimitry Andric } 4841f785676fSDimitry Andric if (!Ty || !Size) 48428f0fd8f6SDimitry Andric return error("Invalid record"); 4843ff0cc061SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, Size, Align); 484491bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca); 484591bc56edSDimitry Andric I = AI; 4846f22ef01cSRoman Divacky InstructionList.push_back(I); 4847f22ef01cSRoman Divacky break; 4848f22ef01cSRoman Divacky } 4849f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4850f22ef01cSRoman Divacky unsigned OpNum = 0; 4851f22ef01cSRoman Divacky Value *Op; 4852f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4853ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 48548f0fd8f6SDimitry Andric return error("Invalid record"); 4855f22ef01cSRoman Divacky 4856ff0cc061SDimitry Andric Type *Ty = nullptr; 4857ff0cc061SDimitry Andric if (OpNum + 3 == Record.size()) 4858ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 48597d523365SDimitry Andric if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4860ff0cc061SDimitry Andric return EC; 4861ff0cc061SDimitry Andric if (!Ty) 4862ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4863ff0cc061SDimitry Andric 4864ff0cc061SDimitry Andric unsigned Align; 4865ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4866ff0cc061SDimitry Andric return EC; 4867ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4868ff0cc061SDimitry Andric 4869f22ef01cSRoman Divacky InstructionList.push_back(I); 4870f22ef01cSRoman Divacky break; 4871f22ef01cSRoman Divacky } 48726122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 48736122f3e6SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 48746122f3e6SDimitry Andric unsigned OpNum = 0; 48756122f3e6SDimitry Andric Value *Op; 48766122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4877ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 48788f0fd8f6SDimitry Andric return error("Invalid record"); 48796122f3e6SDimitry Andric 4880ff0cc061SDimitry Andric Type *Ty = nullptr; 4881ff0cc061SDimitry Andric if (OpNum + 5 == Record.size()) 4882ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 48837d523365SDimitry Andric if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4884ff0cc061SDimitry Andric return EC; 4885ff0cc061SDimitry Andric if (!Ty) 4886ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4887ff0cc061SDimitry Andric 48888f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 48896122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Release || 48906122f3e6SDimitry Andric Ordering == AcquireRelease) 48918f0fd8f6SDimitry Andric return error("Invalid record"); 48926122f3e6SDimitry Andric if (Ordering != NotAtomic && Record[OpNum] == 0) 48938f0fd8f6SDimitry Andric return error("Invalid record"); 48948f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 48956122f3e6SDimitry Andric 4896ff0cc061SDimitry Andric unsigned Align; 4897ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4898ff0cc061SDimitry Andric return EC; 4899ff0cc061SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 4900ff0cc061SDimitry Andric 49016122f3e6SDimitry Andric InstructionList.push_back(I); 49026122f3e6SDimitry Andric break; 49036122f3e6SDimitry Andric } 4904ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 4905ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4906f22ef01cSRoman Divacky unsigned OpNum = 0; 4907f22ef01cSRoman Divacky Value *Val, *Ptr; 4908f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4909ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE 4910ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4911ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4912ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4913ff0cc061SDimitry Andric Val)) || 4914f22ef01cSRoman Divacky OpNum + 2 != Record.size()) 49158f0fd8f6SDimitry Andric return error("Invalid record"); 4916f22ef01cSRoman Divacky 49177d523365SDimitry Andric if (std::error_code EC = 49187d523365SDimitry Andric typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4919ff0cc061SDimitry Andric return EC; 4920ff0cc061SDimitry Andric unsigned Align; 4921ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4922ff0cc061SDimitry Andric return EC; 4923ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4924f22ef01cSRoman Divacky InstructionList.push_back(I); 4925f22ef01cSRoman Divacky break; 4926f22ef01cSRoman Divacky } 4927ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 4928ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 49296122f3e6SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 49306122f3e6SDimitry Andric unsigned OpNum = 0; 49316122f3e6SDimitry Andric Value *Val, *Ptr; 49326122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4933ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4934ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4935ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4936ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4937ff0cc061SDimitry Andric Val)) || 49386122f3e6SDimitry Andric OpNum + 4 != Record.size()) 49398f0fd8f6SDimitry Andric return error("Invalid record"); 49406122f3e6SDimitry Andric 49417d523365SDimitry Andric if (std::error_code EC = 49427d523365SDimitry Andric typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4943ff0cc061SDimitry Andric return EC; 49448f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 49456122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Acquire || 49466122f3e6SDimitry Andric Ordering == AcquireRelease) 49478f0fd8f6SDimitry Andric return error("Invalid record"); 49488f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 49496122f3e6SDimitry Andric if (Ordering != NotAtomic && Record[OpNum] == 0) 49508f0fd8f6SDimitry Andric return error("Invalid record"); 49516122f3e6SDimitry Andric 4952ff0cc061SDimitry Andric unsigned Align; 4953ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4954ff0cc061SDimitry Andric return EC; 4955ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 49566122f3e6SDimitry Andric InstructionList.push_back(I); 49576122f3e6SDimitry Andric break; 49586122f3e6SDimitry Andric } 4959ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 49606122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 496191bc56edSDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 496291bc56edSDimitry Andric // failureordering?, isweak?] 49636122f3e6SDimitry Andric unsigned OpNum = 0; 49646122f3e6SDimitry Andric Value *Ptr, *Cmp, *New; 49656122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4966ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4967ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4968ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4969ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4970ff0cc061SDimitry Andric Cmp)) || 4971ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4972ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 49738f0fd8f6SDimitry Andric return error("Invalid record"); 49748f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 497591bc56edSDimitry Andric if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 49768f0fd8f6SDimitry Andric return error("Invalid record"); 49778f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 497891bc56edSDimitry Andric 49797d523365SDimitry Andric if (std::error_code EC = 49807d523365SDimitry Andric typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4981ff0cc061SDimitry Andric return EC; 498291bc56edSDimitry Andric AtomicOrdering FailureOrdering; 498391bc56edSDimitry Andric if (Record.size() < 7) 498491bc56edSDimitry Andric FailureOrdering = 498591bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 498691bc56edSDimitry Andric else 49878f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 498891bc56edSDimitry Andric 498991bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 499091bc56edSDimitry Andric SynchScope); 49916122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 499291bc56edSDimitry Andric 499391bc56edSDimitry Andric if (Record.size() < 8) { 499491bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 499591bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be 499691bc56edSDimitry Andric // expecting the first component of a modern cmpxchg. 499791bc56edSDimitry Andric CurBB->getInstList().push_back(I); 499891bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0); 499991bc56edSDimitry Andric } else { 500091bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 500191bc56edSDimitry Andric } 500291bc56edSDimitry Andric 50036122f3e6SDimitry Andric InstructionList.push_back(I); 50046122f3e6SDimitry Andric break; 50056122f3e6SDimitry Andric } 50066122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 50076122f3e6SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 50086122f3e6SDimitry Andric unsigned OpNum = 0; 50096122f3e6SDimitry Andric Value *Ptr, *Val; 50106122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 50113861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, 50126122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) || 50136122f3e6SDimitry Andric OpNum+4 != Record.size()) 50148f0fd8f6SDimitry Andric return error("Invalid record"); 50158f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 50166122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 50176122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 50188f0fd8f6SDimitry Andric return error("Invalid record"); 50198f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 50206122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Unordered) 50218f0fd8f6SDimitry Andric return error("Invalid record"); 50228f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 50236122f3e6SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 50246122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 50256122f3e6SDimitry Andric InstructionList.push_back(I); 50266122f3e6SDimitry Andric break; 50276122f3e6SDimitry Andric } 50286122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 50296122f3e6SDimitry Andric if (2 != Record.size()) 50308f0fd8f6SDimitry Andric return error("Invalid record"); 50318f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 50326122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Unordered || 50336122f3e6SDimitry Andric Ordering == Monotonic) 50348f0fd8f6SDimitry Andric return error("Invalid record"); 50358f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 50366122f3e6SDimitry Andric I = new FenceInst(Context, Ordering, SynchScope); 50376122f3e6SDimitry Andric InstructionList.push_back(I); 50386122f3e6SDimitry Andric break; 50396122f3e6SDimitry Andric } 504017a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 50417d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5042f22ef01cSRoman Divacky if (Record.size() < 3) 50438f0fd8f6SDimitry Andric return error("Invalid record"); 5044f22ef01cSRoman Divacky 5045ff0cc061SDimitry Andric unsigned OpNum = 0; 5046ff0cc061SDimitry Andric AttributeSet PAL = getAttributes(Record[OpNum++]); 5047ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 5048f22ef01cSRoman Divacky 50497d523365SDimitry Andric FastMathFlags FMF; 50507d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 50517d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 50527d523365SDimitry Andric if (!FMF.any()) 50537d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 50547d523365SDimitry Andric } 50557d523365SDimitry Andric 5056ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 50577d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5058ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 50598f0fd8f6SDimitry Andric return error("Explicit call type is not a function type"); 5060ff0cc061SDimitry Andric 5061f22ef01cSRoman Divacky Value *Callee; 5062f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 50638f0fd8f6SDimitry Andric return error("Invalid record"); 5064f22ef01cSRoman Divacky 50656122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5066ff0cc061SDimitry Andric if (!OpTy) 50678f0fd8f6SDimitry Andric return error("Callee is not a pointer type"); 5068ff0cc061SDimitry Andric if (!FTy) { 5069ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5070ff0cc061SDimitry Andric if (!FTy) 50718f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 5072ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy) 50738f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of " 5074ff0cc061SDimitry Andric "callee operand"); 5075ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 50768f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 5077f22ef01cSRoman Divacky 5078f22ef01cSRoman Divacky SmallVector<Value*, 16> Args; 5079f22ef01cSRoman Divacky // Read the fixed params. 5080f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 508117a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 5082f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum])); 5083f22ef01cSRoman Divacky else 50843861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 50853861d79fSDimitry Andric FTy->getParamType(i))); 508691bc56edSDimitry Andric if (!Args.back()) 50878f0fd8f6SDimitry Andric return error("Invalid record"); 5088f22ef01cSRoman Divacky } 5089f22ef01cSRoman Divacky 5090f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 5091f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 5092f22ef01cSRoman Divacky if (OpNum != Record.size()) 50938f0fd8f6SDimitry Andric return error("Invalid record"); 5094f22ef01cSRoman Divacky } else { 5095f22ef01cSRoman Divacky while (OpNum != Record.size()) { 5096f22ef01cSRoman Divacky Value *Op; 5097f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 50988f0fd8f6SDimitry Andric return error("Invalid record"); 5099f22ef01cSRoman Divacky Args.push_back(Op); 5100f22ef01cSRoman Divacky } 5101f22ef01cSRoman Divacky } 5102f22ef01cSRoman Divacky 51037d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 51047d523365SDimitry Andric OperandBundles.clear(); 5105f22ef01cSRoman Divacky InstructionList.push_back(I); 5106f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv( 51077d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 510891bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 51097d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 511091bc56edSDimitry Andric TCK = CallInst::TCK_Tail; 51117d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 511291bc56edSDimitry Andric TCK = CallInst::TCK_MustTail; 51137d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 51147d523365SDimitry Andric TCK = CallInst::TCK_NoTail; 511591bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 5116f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL); 51177d523365SDimitry Andric if (FMF.any()) { 51187d523365SDimitry Andric if (!isa<FPMathOperator>(I)) 51197d523365SDimitry Andric return error("Fast-math-flags specified for call without " 51207d523365SDimitry Andric "floating-point scalar or vector return type"); 51217d523365SDimitry Andric I->setFastMathFlags(FMF); 51227d523365SDimitry Andric } 5123f22ef01cSRoman Divacky break; 5124f22ef01cSRoman Divacky } 5125f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5126f22ef01cSRoman Divacky if (Record.size() < 3) 51278f0fd8f6SDimitry Andric return error("Invalid record"); 51286122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 51293861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy); 51306122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]); 5131f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy) 51328f0fd8f6SDimitry Andric return error("Invalid record"); 5133f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy); 5134f22ef01cSRoman Divacky InstructionList.push_back(I); 5135f22ef01cSRoman Divacky break; 5136f22ef01cSRoman Divacky } 51377d523365SDimitry Andric 51387d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 51397d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 51407d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into 51417d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 51427d523365SDimitry Andric 51437d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size()) 51447d523365SDimitry Andric return error("Invalid record"); 51457d523365SDimitry Andric 51467d523365SDimitry Andric std::vector<Value *> Inputs; 51477d523365SDimitry Andric 51487d523365SDimitry Andric unsigned OpNum = 1; 51497d523365SDimitry Andric while (OpNum != Record.size()) { 51507d523365SDimitry Andric Value *Op; 51517d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 51527d523365SDimitry Andric return error("Invalid record"); 51537d523365SDimitry Andric Inputs.push_back(Op); 51547d523365SDimitry Andric } 51557d523365SDimitry Andric 51567d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 51577d523365SDimitry Andric continue; 51587d523365SDimitry Andric } 5159f22ef01cSRoman Divacky } 5160f22ef01cSRoman Divacky 5161f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject 5162f22ef01cSRoman Divacky // this file. 516391bc56edSDimitry Andric if (!CurBB) { 5164f22ef01cSRoman Divacky delete I; 51658f0fd8f6SDimitry Andric return error("Invalid instruction with no BB"); 5166f22ef01cSRoman Divacky } 51677d523365SDimitry Andric if (!OperandBundles.empty()) { 51687d523365SDimitry Andric delete I; 51697d523365SDimitry Andric return error("Operand bundles found with no consumer"); 51707d523365SDimitry Andric } 5171f22ef01cSRoman Divacky CurBB->getInstList().push_back(I); 5172f22ef01cSRoman Divacky 5173f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block. 5174f22ef01cSRoman Divacky if (isa<TerminatorInst>(I)) { 5175f22ef01cSRoman Divacky ++CurBBNo; 517691bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5177f22ef01cSRoman Divacky } 5178f22ef01cSRoman Divacky 5179f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use. 5180f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy()) 51818f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++); 5182f22ef01cSRoman Divacky } 5183f22ef01cSRoman Divacky 5184139f7f9bSDimitry Andric OutOfRecordLoop: 5185139f7f9bSDimitry Andric 51867d523365SDimitry Andric if (!OperandBundles.empty()) 51877d523365SDimitry Andric return error("Operand bundles found with no consumer"); 51887d523365SDimitry Andric 5189f22ef01cSRoman Divacky // Check the function list for unresolved values. 5190f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 519191bc56edSDimitry Andric if (!A->getParent()) { 5192f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks. 5193f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 519491bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5195f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType())); 5196f22ef01cSRoman Divacky delete A; 5197f22ef01cSRoman Divacky } 5198f22ef01cSRoman Divacky } 51998f0fd8f6SDimitry Andric return error("Never resolved value found in function"); 5200f22ef01cSRoman Divacky } 5201f22ef01cSRoman Divacky } 5202f22ef01cSRoman Divacky 5203e580952dSDimitry Andric // FIXME: Check for unresolved forward-declared metadata references 5204e580952dSDimitry Andric // and clean up leaks. 5205e580952dSDimitry Andric 5206f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function. 5207f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize); 52087d523365SDimitry Andric MetadataList.shrinkTo(ModuleMetadataListSize); 5209f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 521091bc56edSDimitry Andric return std::error_code(); 5211f22ef01cSRoman Divacky } 5212f22ef01cSRoman Divacky 5213f785676fSDimitry Andric /// Find the function body in the bitcode stream 52148f0fd8f6SDimitry Andric std::error_code BitcodeReader::findFunctionInStream( 521591bc56edSDimitry Andric Function *F, 5216dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5217dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 52187d523365SDimitry Andric // This is the fallback handling for the old format bitcode that 52197d523365SDimitry Andric // didn't contain the function index in the VST, or when we have 52207d523365SDimitry Andric // an anonymous function which would not have a VST entry. 52217d523365SDimitry Andric // Assert that we have one of those two cases. 52227d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 52237d523365SDimitry Andric // Parse the next body in the stream and set its position in the 52247d523365SDimitry Andric // DeferredFunctionInfo map. 52257d523365SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBodies()) 5226f785676fSDimitry Andric return EC; 5227dff0c46cSDimitry Andric } 522891bc56edSDimitry Andric return std::error_code(); 5229dff0c46cSDimitry Andric } 5230dff0c46cSDimitry Andric 5231f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5232f22ef01cSRoman Divacky // GVMaterializer implementation 5233f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5234f22ef01cSRoman Divacky 523591bc56edSDimitry Andric void BitcodeReader::releaseBuffer() { Buffer.release(); } 5236f22ef01cSRoman Divacky 523739d628a0SDimitry Andric std::error_code BitcodeReader::materialize(GlobalValue *GV) { 52387d523365SDimitry Andric // In older bitcode we must materialize the metadata before parsing 52397d523365SDimitry Andric // any functions, in order to set up the MetadataList properly. 52407d523365SDimitry Andric if (!SeenModuleValuesRecord) { 5241ff0cc061SDimitry Andric if (std::error_code EC = materializeMetadata()) 5242ff0cc061SDimitry Andric return EC; 52437d523365SDimitry Andric } 5244ff0cc061SDimitry Andric 5245f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV); 5246f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request. 5247f785676fSDimitry Andric if (!F || !F->isMaterializable()) 524891bc56edSDimitry Andric return std::error_code(); 5249f22ef01cSRoman Divacky 5250f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5251f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5252dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 5253dff0c46cSDimitry Andric // but we haven't seen it yet. 52543dac3a9bSDimitry Andric if (DFII->second == 0) 52558f0fd8f6SDimitry Andric if (std::error_code EC = findFunctionInStream(F, DFII)) 5256f785676fSDimitry Andric return EC; 5257f22ef01cSRoman Divacky 5258f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body. 5259f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second); 5260f22ef01cSRoman Divacky 52618f0fd8f6SDimitry Andric if (std::error_code EC = parseFunctionBody(F)) 5262f785676fSDimitry Andric return EC; 526339d628a0SDimitry Andric F->setIsMaterializable(false); 5264f22ef01cSRoman Divacky 5265ff0cc061SDimitry Andric if (StripDebugInfo) 5266ff0cc061SDimitry Andric stripDebugInfo(*F); 5267ff0cc061SDimitry Andric 5268f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function. 52693dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 52707d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 52717d523365SDimitry Andric UI != UE;) { 52723dac3a9bSDimitry Andric User *U = *UI; 52733dac3a9bSDimitry Andric ++UI; 52743dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 52753dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 5276f22ef01cSRoman Divacky } 5277f22ef01cSRoman Divacky } 5278f22ef01cSRoman Divacky 52797d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 52807d523365SDimitry Andric if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 52817d523365SDimitry Andric F->setSubprogram(SP); 52827d523365SDimitry Andric 528339d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via 528439d628a0SDimitry Andric // blockaddresses. 528539d628a0SDimitry Andric return materializeForwardReferencedFunctions(); 5286f22ef01cSRoman Divacky } 5287f22ef01cSRoman Divacky 52887d523365SDimitry Andric std::error_code BitcodeReader::materializeModule() { 5289ff0cc061SDimitry Andric if (std::error_code EC = materializeMetadata()) 5290ff0cc061SDimitry Andric return EC; 5291ff0cc061SDimitry Andric 529239d628a0SDimitry Andric // Promise to materialize all forward references. 529339d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 529439d628a0SDimitry Andric 5295f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on 5296f22ef01cSRoman Divacky // disk. 52977d523365SDimitry Andric for (Function &F : *TheModule) { 52987d523365SDimitry Andric if (std::error_code EC = materialize(&F)) 5299f785676fSDimitry Andric return EC; 5300f785676fSDimitry Andric } 53017d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of 53027d523365SDimitry Andric // the bits in the module past the last function block we have recorded 53037d523365SDimitry Andric // through either lazy scanning or the VST. 53047d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 53057d523365SDimitry Andric parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit 53067d523365SDimitry Andric : NextUnreadBit); 5307dff0c46cSDimitry Andric 530839d628a0SDimitry Andric // Check that all block address forward references got resolved (as we 530939d628a0SDimitry Andric // promised above). 531039d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty()) 53118f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 531239d628a0SDimitry Andric 5313f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 5314f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire 5315f22ef01cSRoman Divacky // module is materialized because there could always be another function body 5316f22ef01cSRoman Divacky // with calls to the old function. 53173dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 53183dac3a9bSDimitry Andric for (auto *U : I.first->users()) { 53193dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 53203dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 5321f22ef01cSRoman Divacky } 53223dac3a9bSDimitry Andric if (!I.first->use_empty()) 53233dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second); 53243dac3a9bSDimitry Andric I.first->eraseFromParent(); 5325f22ef01cSRoman Divacky } 53263dac3a9bSDimitry Andric UpgradedIntrinsics.clear(); 5327f22ef01cSRoman Divacky 5328f785676fSDimitry Andric for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 5329f785676fSDimitry Andric UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 5330f785676fSDimitry Andric 53317d523365SDimitry Andric UpgradeDebugInfo(*TheModule); 533291bc56edSDimitry Andric return std::error_code(); 5333dff0c46cSDimitry Andric } 53346122f3e6SDimitry Andric 533539d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 533639d628a0SDimitry Andric return IdentifiedStructTypes; 533739d628a0SDimitry Andric } 533839d628a0SDimitry Andric 53398f0fd8f6SDimitry Andric std::error_code 53408f0fd8f6SDimitry Andric BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 53418f0fd8f6SDimitry Andric if (Streamer) 53428f0fd8f6SDimitry Andric return initLazyStream(std::move(Streamer)); 53438f0fd8f6SDimitry Andric return initStreamFromBuffer(); 5344dff0c46cSDimitry Andric } 5345dff0c46cSDimitry Andric 53468f0fd8f6SDimitry Andric std::error_code BitcodeReader::initStreamFromBuffer() { 53473861d79fSDimitry Andric const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 5348dff0c46cSDimitry Andric const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 5349dff0c46cSDimitry Andric 535039d628a0SDimitry Andric if (Buffer->getBufferSize() & 3) 53518f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5352dff0c46cSDimitry Andric 5353dff0c46cSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 5354dff0c46cSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 5355dff0c46cSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 5356dff0c46cSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 53578f0fd8f6SDimitry Andric return error("Invalid bitcode wrapper header"); 5358dff0c46cSDimitry Andric 5359dff0c46cSDimitry Andric StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 536039d628a0SDimitry Andric Stream.init(&*StreamFile); 5361f22ef01cSRoman Divacky 536291bc56edSDimitry Andric return std::error_code(); 5363f22ef01cSRoman Divacky } 5364f22ef01cSRoman Divacky 53658f0fd8f6SDimitry Andric std::error_code 53668f0fd8f6SDimitry Andric BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) { 5367dff0c46cSDimitry Andric // Check and strip off the bitcode wrapper; BitstreamReader expects never to 5368dff0c46cSDimitry Andric // see it. 53698f0fd8f6SDimitry Andric auto OwnedBytes = 53708f0fd8f6SDimitry Andric llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 537139d628a0SDimitry Andric StreamingMemoryObject &Bytes = *OwnedBytes; 537239d628a0SDimitry Andric StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 537339d628a0SDimitry Andric Stream.init(&*StreamFile); 5374dff0c46cSDimitry Andric 5375dff0c46cSDimitry Andric unsigned char buf[16]; 537639d628a0SDimitry Andric if (Bytes.readBytes(buf, 16, 0) != 16) 53778f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5378dff0c46cSDimitry Andric 5379dff0c46cSDimitry Andric if (!isBitcode(buf, buf + 16)) 53808f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5381dff0c46cSDimitry Andric 5382dff0c46cSDimitry Andric if (isBitcodeWrapper(buf, buf + 4)) { 5383dff0c46cSDimitry Andric const unsigned char *bitcodeStart = buf; 5384dff0c46cSDimitry Andric const unsigned char *bitcodeEnd = buf + 16; 5385dff0c46cSDimitry Andric SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 538639d628a0SDimitry Andric Bytes.dropLeadingBytes(bitcodeStart - buf); 538739d628a0SDimitry Andric Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 5388dff0c46cSDimitry Andric } 538991bc56edSDimitry Andric return std::error_code(); 5390f785676fSDimitry Andric } 5391f785676fSDimitry Andric 53927d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(BitcodeError E, 53937d523365SDimitry Andric const Twine &Message) { 53947d523365SDimitry Andric return ::error(DiagnosticHandler, make_error_code(E), Message); 53957d523365SDimitry Andric } 53967d523365SDimitry Andric 53977d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) { 53987d523365SDimitry Andric return ::error(DiagnosticHandler, 53997d523365SDimitry Andric make_error_code(BitcodeError::CorruptedBitcode), Message); 54007d523365SDimitry Andric } 54017d523365SDimitry Andric 54027d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) { 54037d523365SDimitry Andric return ::error(DiagnosticHandler, make_error_code(E)); 54047d523365SDimitry Andric } 54057d523365SDimitry Andric 54067d523365SDimitry Andric FunctionIndexBitcodeReader::FunctionIndexBitcodeReader( 54077d523365SDimitry Andric MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler, 54087d523365SDimitry Andric bool IsLazy, bool CheckFuncSummaryPresenceOnly) 54097d523365SDimitry Andric : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy), 54107d523365SDimitry Andric CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {} 54117d523365SDimitry Andric 54127d523365SDimitry Andric FunctionIndexBitcodeReader::FunctionIndexBitcodeReader( 54137d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy, 54147d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly) 54157d523365SDimitry Andric : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy), 54167d523365SDimitry Andric CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {} 54177d523365SDimitry Andric 54187d523365SDimitry Andric void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; } 54197d523365SDimitry Andric 54207d523365SDimitry Andric void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); } 54217d523365SDimitry Andric 54227d523365SDimitry Andric // Specialized value symbol table parser used when reading function index 54237d523365SDimitry Andric // blocks where we don't actually create global values. 54247d523365SDimitry Andric // At the end of this routine the function index is populated with a map 54257d523365SDimitry Andric // from function name to FunctionInfo. The function info contains 54267d523365SDimitry Andric // the function block's bitcode offset as well as the offset into the 54277d523365SDimitry Andric // function summary section. 54287d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() { 54297d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 54307d523365SDimitry Andric return error("Invalid record"); 54317d523365SDimitry Andric 54327d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 54337d523365SDimitry Andric 54347d523365SDimitry Andric // Read all the records for this value table. 54357d523365SDimitry Andric SmallString<128> ValueName; 54367d523365SDimitry Andric while (1) { 54377d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 54387d523365SDimitry Andric 54397d523365SDimitry Andric switch (Entry.Kind) { 54407d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 54417d523365SDimitry Andric case BitstreamEntry::Error: 54427d523365SDimitry Andric return error("Malformed block"); 54437d523365SDimitry Andric case BitstreamEntry::EndBlock: 54447d523365SDimitry Andric return std::error_code(); 54457d523365SDimitry Andric case BitstreamEntry::Record: 54467d523365SDimitry Andric // The interesting case. 54477d523365SDimitry Andric break; 54487d523365SDimitry Andric } 54497d523365SDimitry Andric 54507d523365SDimitry Andric // Read a record. 54517d523365SDimitry Andric Record.clear(); 54527d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 54537d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 54547d523365SDimitry Andric break; 54557d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 54567d523365SDimitry Andric // VST_FNENTRY: [valueid, offset, namechar x N] 54577d523365SDimitry Andric if (convertToString(Record, 2, ValueName)) 54587d523365SDimitry Andric return error("Invalid record"); 54597d523365SDimitry Andric unsigned ValueID = Record[0]; 54607d523365SDimitry Andric uint64_t FuncOffset = Record[1]; 54617d523365SDimitry Andric std::unique_ptr<FunctionInfo> FuncInfo = 54627d523365SDimitry Andric llvm::make_unique<FunctionInfo>(FuncOffset); 54637d523365SDimitry Andric if (foundFuncSummary() && !IsLazy) { 54647d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI = 54657d523365SDimitry Andric SummaryMap.find(ValueID); 54667d523365SDimitry Andric assert(SMI != SummaryMap.end() && "Summary info not found"); 54677d523365SDimitry Andric FuncInfo->setFunctionSummary(std::move(SMI->second)); 54687d523365SDimitry Andric } 54697d523365SDimitry Andric TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo)); 54707d523365SDimitry Andric 54717d523365SDimitry Andric ValueName.clear(); 54727d523365SDimitry Andric break; 54737d523365SDimitry Andric } 54747d523365SDimitry Andric case bitc::VST_CODE_COMBINED_FNENTRY: { 54757d523365SDimitry Andric // VST_FNENTRY: [offset, namechar x N] 54767d523365SDimitry Andric if (convertToString(Record, 1, ValueName)) 54777d523365SDimitry Andric return error("Invalid record"); 54787d523365SDimitry Andric uint64_t FuncSummaryOffset = Record[0]; 54797d523365SDimitry Andric std::unique_ptr<FunctionInfo> FuncInfo = 54807d523365SDimitry Andric llvm::make_unique<FunctionInfo>(FuncSummaryOffset); 54817d523365SDimitry Andric if (foundFuncSummary() && !IsLazy) { 54827d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI = 54837d523365SDimitry Andric SummaryMap.find(FuncSummaryOffset); 54847d523365SDimitry Andric assert(SMI != SummaryMap.end() && "Summary info not found"); 54857d523365SDimitry Andric FuncInfo->setFunctionSummary(std::move(SMI->second)); 54867d523365SDimitry Andric } 54877d523365SDimitry Andric TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo)); 54887d523365SDimitry Andric 54897d523365SDimitry Andric ValueName.clear(); 54907d523365SDimitry Andric break; 54917d523365SDimitry Andric } 54927d523365SDimitry Andric } 54937d523365SDimitry Andric } 54947d523365SDimitry Andric } 54957d523365SDimitry Andric 54967d523365SDimitry Andric // Parse just the blocks needed for function index building out of the module. 54977d523365SDimitry Andric // At the end of this routine the function Index is populated with a map 54987d523365SDimitry Andric // from function name to FunctionInfo. The function info contains 54997d523365SDimitry Andric // either the parsed function summary information (when parsing summaries 55007d523365SDimitry Andric // eagerly), or just to the function summary record's offset 55017d523365SDimitry Andric // if parsing lazily (IsLazy). 55027d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseModule() { 55037d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 55047d523365SDimitry Andric return error("Invalid record"); 55057d523365SDimitry Andric 55067d523365SDimitry Andric // Read the function index for this module. 55077d523365SDimitry Andric while (1) { 55087d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 55097d523365SDimitry Andric 55107d523365SDimitry Andric switch (Entry.Kind) { 55117d523365SDimitry Andric case BitstreamEntry::Error: 55127d523365SDimitry Andric return error("Malformed block"); 55137d523365SDimitry Andric case BitstreamEntry::EndBlock: 55147d523365SDimitry Andric return std::error_code(); 55157d523365SDimitry Andric 55167d523365SDimitry Andric case BitstreamEntry::SubBlock: 55177d523365SDimitry Andric if (CheckFuncSummaryPresenceOnly) { 55187d523365SDimitry Andric if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) { 55197d523365SDimitry Andric SeenFuncSummary = true; 55207d523365SDimitry Andric // No need to parse the rest since we found the summary. 55217d523365SDimitry Andric return std::error_code(); 55227d523365SDimitry Andric } 55237d523365SDimitry Andric if (Stream.SkipBlock()) 55247d523365SDimitry Andric return error("Invalid record"); 55257d523365SDimitry Andric continue; 55267d523365SDimitry Andric } 55277d523365SDimitry Andric switch (Entry.ID) { 55287d523365SDimitry Andric default: // Skip unknown content. 55297d523365SDimitry Andric if (Stream.SkipBlock()) 55307d523365SDimitry Andric return error("Invalid record"); 55317d523365SDimitry Andric break; 55327d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 55337d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 55347d523365SDimitry Andric if (Stream.ReadBlockInfoBlock()) 55357d523365SDimitry Andric return error("Malformed block"); 55367d523365SDimitry Andric break; 55377d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 55387d523365SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 55397d523365SDimitry Andric return EC; 55407d523365SDimitry Andric break; 55417d523365SDimitry Andric case bitc::FUNCTION_SUMMARY_BLOCK_ID: 55427d523365SDimitry Andric SeenFuncSummary = true; 55437d523365SDimitry Andric if (IsLazy) { 55447d523365SDimitry Andric // Lazy parsing of summary info, skip it. 55457d523365SDimitry Andric if (Stream.SkipBlock()) 55467d523365SDimitry Andric return error("Invalid record"); 55477d523365SDimitry Andric } else if (std::error_code EC = parseEntireSummary()) 55487d523365SDimitry Andric return EC; 55497d523365SDimitry Andric break; 55507d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 55517d523365SDimitry Andric if (std::error_code EC = parseModuleStringTable()) 55527d523365SDimitry Andric return EC; 55537d523365SDimitry Andric break; 55547d523365SDimitry Andric } 55557d523365SDimitry Andric continue; 55567d523365SDimitry Andric 55577d523365SDimitry Andric case BitstreamEntry::Record: 55587d523365SDimitry Andric Stream.skipRecord(Entry.ID); 55597d523365SDimitry Andric continue; 55607d523365SDimitry Andric } 55617d523365SDimitry Andric } 55627d523365SDimitry Andric } 55637d523365SDimitry Andric 55647d523365SDimitry Andric // Eagerly parse the entire function summary block (i.e. for all functions 55657d523365SDimitry Andric // in the index). This populates the FunctionSummary objects in 55667d523365SDimitry Andric // the index. 55677d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseEntireSummary() { 55687d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID)) 55697d523365SDimitry Andric return error("Invalid record"); 55707d523365SDimitry Andric 55717d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 55727d523365SDimitry Andric 55737d523365SDimitry Andric while (1) { 55747d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 55757d523365SDimitry Andric 55767d523365SDimitry Andric switch (Entry.Kind) { 55777d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 55787d523365SDimitry Andric case BitstreamEntry::Error: 55797d523365SDimitry Andric return error("Malformed block"); 55807d523365SDimitry Andric case BitstreamEntry::EndBlock: 55817d523365SDimitry Andric return std::error_code(); 55827d523365SDimitry Andric case BitstreamEntry::Record: 55837d523365SDimitry Andric // The interesting case. 55847d523365SDimitry Andric break; 55857d523365SDimitry Andric } 55867d523365SDimitry Andric 55877d523365SDimitry Andric // Read a record. The record format depends on whether this 55887d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module 55897d523365SDimitry Andric // case the records contain the associated value's ID for correlation 55907d523365SDimitry Andric // with VST entries. In the combined index the correlation is done 55917d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved 55927d523365SDimitry Andric // in the combined index VST entries). The records also contain 55937d523365SDimitry Andric // information used for ThinLTO renaming and importing. 55947d523365SDimitry Andric Record.clear(); 55957d523365SDimitry Andric uint64_t CurRecordBit = Stream.GetCurrentBitNo(); 55967d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 55977d523365SDimitry Andric default: // Default behavior: ignore. 55987d523365SDimitry Andric break; 55997d523365SDimitry Andric // FS_PERMODULE_ENTRY: [valueid, islocal, instcount] 56007d523365SDimitry Andric case bitc::FS_CODE_PERMODULE_ENTRY: { 56017d523365SDimitry Andric unsigned ValueID = Record[0]; 56027d523365SDimitry Andric bool IsLocal = Record[1]; 56037d523365SDimitry Andric unsigned InstCount = Record[2]; 56047d523365SDimitry Andric std::unique_ptr<FunctionSummary> FS = 56057d523365SDimitry Andric llvm::make_unique<FunctionSummary>(InstCount); 56067d523365SDimitry Andric FS->setLocalFunction(IsLocal); 56077d523365SDimitry Andric // The module path string ref set in the summary must be owned by the 56087d523365SDimitry Andric // index's module string table. Since we don't have a module path 56097d523365SDimitry Andric // string table section in the per-module index, we create a single 56107d523365SDimitry Andric // module path string table entry with an empty (0) ID to take 56117d523365SDimitry Andric // ownership. 56127d523365SDimitry Andric FS->setModulePath( 56137d523365SDimitry Andric TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)); 56147d523365SDimitry Andric SummaryMap[ValueID] = std::move(FS); 56157d523365SDimitry Andric } 56167d523365SDimitry Andric // FS_COMBINED_ENTRY: [modid, instcount] 56177d523365SDimitry Andric case bitc::FS_CODE_COMBINED_ENTRY: { 56187d523365SDimitry Andric uint64_t ModuleId = Record[0]; 56197d523365SDimitry Andric unsigned InstCount = Record[1]; 56207d523365SDimitry Andric std::unique_ptr<FunctionSummary> FS = 56217d523365SDimitry Andric llvm::make_unique<FunctionSummary>(InstCount); 56227d523365SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 56237d523365SDimitry Andric SummaryMap[CurRecordBit] = std::move(FS); 56247d523365SDimitry Andric } 56257d523365SDimitry Andric } 56267d523365SDimitry Andric } 56277d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 56287d523365SDimitry Andric } 56297d523365SDimitry Andric 56307d523365SDimitry Andric // Parse the module string table block into the Index. 56317d523365SDimitry Andric // This populates the ModulePathStringTable map in the index. 56327d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() { 56337d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 56347d523365SDimitry Andric return error("Invalid record"); 56357d523365SDimitry Andric 56367d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 56377d523365SDimitry Andric 56387d523365SDimitry Andric SmallString<128> ModulePath; 56397d523365SDimitry Andric while (1) { 56407d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 56417d523365SDimitry Andric 56427d523365SDimitry Andric switch (Entry.Kind) { 56437d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 56447d523365SDimitry Andric case BitstreamEntry::Error: 56457d523365SDimitry Andric return error("Malformed block"); 56467d523365SDimitry Andric case BitstreamEntry::EndBlock: 56477d523365SDimitry Andric return std::error_code(); 56487d523365SDimitry Andric case BitstreamEntry::Record: 56497d523365SDimitry Andric // The interesting case. 56507d523365SDimitry Andric break; 56517d523365SDimitry Andric } 56527d523365SDimitry Andric 56537d523365SDimitry Andric Record.clear(); 56547d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 56557d523365SDimitry Andric default: // Default behavior: ignore. 56567d523365SDimitry Andric break; 56577d523365SDimitry Andric case bitc::MST_CODE_ENTRY: { 56587d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N] 56597d523365SDimitry Andric if (convertToString(Record, 1, ModulePath)) 56607d523365SDimitry Andric return error("Invalid record"); 56617d523365SDimitry Andric uint64_t ModuleId = Record[0]; 56627d523365SDimitry Andric StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId); 56637d523365SDimitry Andric ModuleIdMap[ModuleId] = ModulePathInMap; 56647d523365SDimitry Andric ModulePath.clear(); 56657d523365SDimitry Andric break; 56667d523365SDimitry Andric } 56677d523365SDimitry Andric } 56687d523365SDimitry Andric } 56697d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 56707d523365SDimitry Andric } 56717d523365SDimitry Andric 56727d523365SDimitry Andric // Parse the function info index from the bitcode streamer into the given index. 56737d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto( 56747d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) { 56757d523365SDimitry Andric TheIndex = I; 56767d523365SDimitry Andric 56777d523365SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 56787d523365SDimitry Andric return EC; 56797d523365SDimitry Andric 56807d523365SDimitry Andric // Sniff for the signature. 56817d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 56827d523365SDimitry Andric return error("Invalid bitcode signature"); 56837d523365SDimitry Andric 56847d523365SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 56857d523365SDimitry Andric // need to understand them all. 56867d523365SDimitry Andric while (1) { 56877d523365SDimitry Andric if (Stream.AtEndOfStream()) { 56887d523365SDimitry Andric // We didn't really read a proper Module block. 56897d523365SDimitry Andric return error("Malformed block"); 56907d523365SDimitry Andric } 56917d523365SDimitry Andric 56927d523365SDimitry Andric BitstreamEntry Entry = 56937d523365SDimitry Andric Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 56947d523365SDimitry Andric 56957d523365SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock) 56967d523365SDimitry Andric return error("Malformed block"); 56977d523365SDimitry Andric 56987d523365SDimitry Andric // If we see a MODULE_BLOCK, parse it to find the blocks needed for 56997d523365SDimitry Andric // building the function summary index. 57007d523365SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 57017d523365SDimitry Andric return parseModule(); 57027d523365SDimitry Andric 57037d523365SDimitry Andric if (Stream.SkipBlock()) 57047d523365SDimitry Andric return error("Invalid record"); 57057d523365SDimitry Andric } 57067d523365SDimitry Andric } 57077d523365SDimitry Andric 57087d523365SDimitry Andric // Parse the function information at the given offset in the buffer into 57097d523365SDimitry Andric // the index. Used to support lazy parsing of function summaries from the 57107d523365SDimitry Andric // combined index during importing. 57117d523365SDimitry Andric // TODO: This function is not yet complete as it won't have a consumer 57127d523365SDimitry Andric // until ThinLTO function importing is added. 57137d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseFunctionSummary( 57147d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I, 57157d523365SDimitry Andric size_t FunctionSummaryOffset) { 57167d523365SDimitry Andric TheIndex = I; 57177d523365SDimitry Andric 57187d523365SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 57197d523365SDimitry Andric return EC; 57207d523365SDimitry Andric 57217d523365SDimitry Andric // Sniff for the signature. 57227d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 57237d523365SDimitry Andric return error("Invalid bitcode signature"); 57247d523365SDimitry Andric 57257d523365SDimitry Andric Stream.JumpToBit(FunctionSummaryOffset); 57267d523365SDimitry Andric 57277d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 57287d523365SDimitry Andric 57297d523365SDimitry Andric switch (Entry.Kind) { 57307d523365SDimitry Andric default: 57317d523365SDimitry Andric return error("Malformed block"); 57327d523365SDimitry Andric case BitstreamEntry::Record: 57337d523365SDimitry Andric // The expected case. 57347d523365SDimitry Andric break; 57357d523365SDimitry Andric } 57367d523365SDimitry Andric 57377d523365SDimitry Andric // TODO: Read a record. This interface will be completed when ThinLTO 57387d523365SDimitry Andric // importing is added so that it can be tested. 57397d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 57407d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 57417d523365SDimitry Andric case bitc::FS_CODE_COMBINED_ENTRY: 57427d523365SDimitry Andric default: 57437d523365SDimitry Andric return error("Invalid record"); 57447d523365SDimitry Andric } 57457d523365SDimitry Andric 57467d523365SDimitry Andric return std::error_code(); 57477d523365SDimitry Andric } 57487d523365SDimitry Andric 57497d523365SDimitry Andric std::error_code 57507d523365SDimitry Andric FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 57517d523365SDimitry Andric if (Streamer) 57527d523365SDimitry Andric return initLazyStream(std::move(Streamer)); 57537d523365SDimitry Andric return initStreamFromBuffer(); 57547d523365SDimitry Andric } 57557d523365SDimitry Andric 57567d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() { 57577d523365SDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart(); 57587d523365SDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize(); 57597d523365SDimitry Andric 57607d523365SDimitry Andric if (Buffer->getBufferSize() & 3) 57617d523365SDimitry Andric return error("Invalid bitcode signature"); 57627d523365SDimitry Andric 57637d523365SDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 57647d523365SDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 57657d523365SDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 57667d523365SDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 57677d523365SDimitry Andric return error("Invalid bitcode wrapper header"); 57687d523365SDimitry Andric 57697d523365SDimitry Andric StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 57707d523365SDimitry Andric Stream.init(&*StreamFile); 57717d523365SDimitry Andric 57727d523365SDimitry Andric return std::error_code(); 57737d523365SDimitry Andric } 57747d523365SDimitry Andric 57757d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::initLazyStream( 57767d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer) { 57777d523365SDimitry Andric // Check and strip off the bitcode wrapper; BitstreamReader expects never to 57787d523365SDimitry Andric // see it. 57797d523365SDimitry Andric auto OwnedBytes = 57807d523365SDimitry Andric llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 57817d523365SDimitry Andric StreamingMemoryObject &Bytes = *OwnedBytes; 57827d523365SDimitry Andric StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 57837d523365SDimitry Andric Stream.init(&*StreamFile); 57847d523365SDimitry Andric 57857d523365SDimitry Andric unsigned char buf[16]; 57867d523365SDimitry Andric if (Bytes.readBytes(buf, 16, 0) != 16) 57877d523365SDimitry Andric return error("Invalid bitcode signature"); 57887d523365SDimitry Andric 57897d523365SDimitry Andric if (!isBitcode(buf, buf + 16)) 57907d523365SDimitry Andric return error("Invalid bitcode signature"); 57917d523365SDimitry Andric 57927d523365SDimitry Andric if (isBitcodeWrapper(buf, buf + 4)) { 57937d523365SDimitry Andric const unsigned char *bitcodeStart = buf; 57947d523365SDimitry Andric const unsigned char *bitcodeEnd = buf + 16; 57957d523365SDimitry Andric SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 57967d523365SDimitry Andric Bytes.dropLeadingBytes(bitcodeStart - buf); 57977d523365SDimitry Andric Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 57987d523365SDimitry Andric } 57997d523365SDimitry Andric return std::error_code(); 58007d523365SDimitry Andric } 58017d523365SDimitry Andric 5802f785676fSDimitry Andric namespace { 580391bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 580491bc56edSDimitry Andric const char *name() const LLVM_NOEXCEPT override { 5805f785676fSDimitry Andric return "llvm.bitcode"; 5806f785676fSDimitry Andric } 580791bc56edSDimitry Andric std::string message(int IE) const override { 580839d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 5809f785676fSDimitry Andric switch (E) { 581039d628a0SDimitry Andric case BitcodeError::InvalidBitcodeSignature: 5811f785676fSDimitry Andric return "Invalid bitcode signature"; 581239d628a0SDimitry Andric case BitcodeError::CorruptedBitcode: 581339d628a0SDimitry Andric return "Corrupted bitcode"; 5814f785676fSDimitry Andric } 5815f785676fSDimitry Andric llvm_unreachable("Unknown error type!"); 5816f785676fSDimitry Andric } 5817f785676fSDimitry Andric }; 58183dac3a9bSDimitry Andric } 5819f785676fSDimitry Andric 582039d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 582139d628a0SDimitry Andric 582239d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 582339d628a0SDimitry Andric return *ErrorCategory; 5824dff0c46cSDimitry Andric } 5825f22ef01cSRoman Divacky 5826f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5827f22ef01cSRoman Divacky // External interface 5828f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5829f22ef01cSRoman Divacky 58308f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>> 58318f0fd8f6SDimitry Andric getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name, 58328f0fd8f6SDimitry Andric BitcodeReader *R, LLVMContext &Context, 58338f0fd8f6SDimitry Andric bool MaterializeAll, bool ShouldLazyLoadMetadata) { 58348f0fd8f6SDimitry Andric std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 58358f0fd8f6SDimitry Andric M->setMaterializer(R); 58368f0fd8f6SDimitry Andric 58378f0fd8f6SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 58388f0fd8f6SDimitry Andric R->releaseBuffer(); // Never take ownership on error. 58398f0fd8f6SDimitry Andric return EC; 58408f0fd8f6SDimitry Andric }; 58418f0fd8f6SDimitry Andric 58428f0fd8f6SDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 58438f0fd8f6SDimitry Andric if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(), 58448f0fd8f6SDimitry Andric ShouldLazyLoadMetadata)) 58458f0fd8f6SDimitry Andric return cleanupOnError(EC); 58468f0fd8f6SDimitry Andric 58478f0fd8f6SDimitry Andric if (MaterializeAll) { 58488f0fd8f6SDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 58497d523365SDimitry Andric if (std::error_code EC = M->materializeAll()) 58508f0fd8f6SDimitry Andric return cleanupOnError(EC); 58518f0fd8f6SDimitry Andric } else { 58528f0fd8f6SDimitry Andric // Resolve forward references from blockaddresses. 58538f0fd8f6SDimitry Andric if (std::error_code EC = R->materializeForwardReferencedFunctions()) 58548f0fd8f6SDimitry Andric return cleanupOnError(EC); 58558f0fd8f6SDimitry Andric } 58568f0fd8f6SDimitry Andric return std::move(M); 58578f0fd8f6SDimitry Andric } 58588f0fd8f6SDimitry Andric 585939d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode. 5860f22ef01cSRoman Divacky /// 586139d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 586239d628a0SDimitry Andric /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 586339d628a0SDimitry Andric /// in forward-referenced functions from block address references. 586439d628a0SDimitry Andric /// 58658f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 58668f0fd8f6SDimitry Andric /// everything. 58678f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>> 586839d628a0SDimitry Andric getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 58698f0fd8f6SDimitry Andric LLVMContext &Context, bool MaterializeAll, 5870ff0cc061SDimitry Andric bool ShouldLazyLoadMetadata = false) { 58717d523365SDimitry Andric BitcodeReader *R = new BitcodeReader(Buffer.get(), Context); 587239d628a0SDimitry Andric 58738f0fd8f6SDimitry Andric ErrorOr<std::unique_ptr<Module>> Ret = 58748f0fd8f6SDimitry Andric getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context, 58758f0fd8f6SDimitry Andric MaterializeAll, ShouldLazyLoadMetadata); 58768f0fd8f6SDimitry Andric if (!Ret) 58778f0fd8f6SDimitry Andric return Ret; 587839d628a0SDimitry Andric 587939d628a0SDimitry Andric Buffer.release(); // The BitcodeReader owns it now. 58808f0fd8f6SDimitry Andric return Ret; 5881dff0c46cSDimitry Andric } 5882dff0c46cSDimitry Andric 58837d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> 58847d523365SDimitry Andric llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 58857d523365SDimitry Andric LLVMContext &Context, bool ShouldLazyLoadMetadata) { 588639d628a0SDimitry Andric return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 58877d523365SDimitry Andric ShouldLazyLoadMetadata); 5888f22ef01cSRoman Divacky } 5889f22ef01cSRoman Divacky 58907d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> 58917d523365SDimitry Andric llvm::getStreamedBitcodeModule(StringRef Name, 58927d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, 58937d523365SDimitry Andric LLVMContext &Context) { 589439d628a0SDimitry Andric std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 58957d523365SDimitry Andric BitcodeReader *R = new BitcodeReader(Context); 58968f0fd8f6SDimitry Andric 58978f0fd8f6SDimitry Andric return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false, 58988f0fd8f6SDimitry Andric false); 589939d628a0SDimitry Andric } 590039d628a0SDimitry Andric 59017d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 59027d523365SDimitry Andric LLVMContext &Context) { 590339d628a0SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59047d523365SDimitry Andric return getLazyBitcodeModuleImpl(std::move(Buf), Context, true); 5905dff0c46cSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 5906dff0c46cSDimitry Andric // written. We must defer until the Module has been fully materialized. 5907f22ef01cSRoman Divacky } 59082754fe60SDimitry Andric 59097d523365SDimitry Andric std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, 59107d523365SDimitry Andric LLVMContext &Context) { 591139d628a0SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59127d523365SDimitry Andric auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context); 591391bc56edSDimitry Andric ErrorOr<std::string> Triple = R->parseTriple(); 591491bc56edSDimitry Andric if (Triple.getError()) 591591bc56edSDimitry Andric return ""; 591691bc56edSDimitry Andric return Triple.get(); 59172754fe60SDimitry Andric } 59187d523365SDimitry Andric 59197d523365SDimitry Andric std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer, 59207d523365SDimitry Andric LLVMContext &Context) { 59217d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59227d523365SDimitry Andric BitcodeReader R(Buf.release(), Context); 59237d523365SDimitry Andric ErrorOr<std::string> ProducerString = R.parseIdentificationBlock(); 59247d523365SDimitry Andric if (ProducerString.getError()) 59257d523365SDimitry Andric return ""; 59267d523365SDimitry Andric return ProducerString.get(); 59277d523365SDimitry Andric } 59287d523365SDimitry Andric 59297d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 59307d523365SDimitry Andric // If IsLazy is false, parse the entire function summary into 59317d523365SDimitry Andric // the index. Otherwise skip the function summary section, and only create 59327d523365SDimitry Andric // an index object with a map from function name to function summary offset. 59337d523365SDimitry Andric // The index is used to perform lazy function summary reading later. 59347d523365SDimitry Andric ErrorOr<std::unique_ptr<FunctionInfoIndex>> 59357d523365SDimitry Andric llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, 59367d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, 59377d523365SDimitry Andric bool IsLazy) { 59387d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59397d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy); 59407d523365SDimitry Andric 59417d523365SDimitry Andric auto Index = llvm::make_unique<FunctionInfoIndex>(); 59427d523365SDimitry Andric 59437d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59447d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59457d523365SDimitry Andric return EC; 59467d523365SDimitry Andric }; 59477d523365SDimitry Andric 59487d523365SDimitry Andric if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get())) 59497d523365SDimitry Andric return cleanupOnError(EC); 59507d523365SDimitry Andric 59517d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59527d523365SDimitry Andric return std::move(Index); 59537d523365SDimitry Andric } 59547d523365SDimitry Andric 59557d523365SDimitry Andric // Check if the given bitcode buffer contains a function summary block. 59567d523365SDimitry Andric bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, 59577d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler) { 59587d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59597d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true); 59607d523365SDimitry Andric 59617d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59627d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59637d523365SDimitry Andric return false; 59647d523365SDimitry Andric }; 59657d523365SDimitry Andric 59667d523365SDimitry Andric if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr)) 59677d523365SDimitry Andric return cleanupOnError(EC); 59687d523365SDimitry Andric 59697d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59707d523365SDimitry Andric return R.foundFuncSummary(); 59717d523365SDimitry Andric } 59727d523365SDimitry Andric 59737d523365SDimitry Andric // This method supports lazy reading of function summary data from the combined 59747d523365SDimitry Andric // index during ThinLTO function importing. When reading the combined index 59757d523365SDimitry Andric // file, getFunctionInfoIndex is first invoked with IsLazy=true. 59767d523365SDimitry Andric // Then this method is called for each function considered for importing, 59777d523365SDimitry Andric // to parse the summary information for the given function name into 59787d523365SDimitry Andric // the index. 59797d523365SDimitry Andric std::error_code llvm::readFunctionSummary( 59807d523365SDimitry Andric MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler, 59817d523365SDimitry Andric StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) { 59827d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59837d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler); 59847d523365SDimitry Andric 59857d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59867d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59877d523365SDimitry Andric return EC; 59887d523365SDimitry Andric }; 59897d523365SDimitry Andric 59907d523365SDimitry Andric // Lookup the given function name in the FunctionMap, which may 59917d523365SDimitry Andric // contain a list of function infos in the case of a COMDAT. Walk through 59927d523365SDimitry Andric // and parse each function summary info at the function summary offset 59937d523365SDimitry Andric // recorded when parsing the value symbol table. 59947d523365SDimitry Andric for (const auto &FI : Index->getFunctionInfoList(FunctionName)) { 59957d523365SDimitry Andric size_t FunctionSummaryOffset = FI->bitcodeIndex(); 59967d523365SDimitry Andric if (std::error_code EC = 59977d523365SDimitry Andric R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset)) 59987d523365SDimitry Andric return cleanupOnError(EC); 59997d523365SDimitry Andric } 60007d523365SDimitry Andric 60017d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 60027d523365SDimitry Andric return std::error_code(); 60037d523365SDimitry Andric } 6004