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 10d88c1a5aSDimitry Andric #include "llvm/Bitcode/BitcodeReader.h" 11d88c1a5aSDimitry Andric #include "MetadataLoader.h" 12d88c1a5aSDimitry Andric #include "ValueList.h" 13d88c1a5aSDimitry Andric #include "llvm/ADT/APFloat.h" 14d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h" 15d88c1a5aSDimitry Andric #include "llvm/ADT/ArrayRef.h" 16d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h" 172cab237bSDimitry Andric #include "llvm/ADT/Optional.h" 18ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h" 19f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h" 20f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h" 21d88c1a5aSDimitry Andric #include "llvm/ADT/StringRef.h" 22ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h" 23d88c1a5aSDimitry Andric #include "llvm/ADT/Twine.h" 24ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h" 25f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h" 26d88c1a5aSDimitry Andric #include "llvm/IR/Argument.h" 27d88c1a5aSDimitry Andric #include "llvm/IR/Attributes.h" 2891bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h" 29d88c1a5aSDimitry Andric #include "llvm/IR/BasicBlock.h" 303ca95b02SDimitry Andric #include "llvm/IR/CallSite.h" 31db17bf38SDimitry Andric #include "llvm/IR/CallingConv.h" 32d88c1a5aSDimitry Andric #include "llvm/IR/Comdat.h" 33d88c1a5aSDimitry Andric #include "llvm/IR/Constant.h" 34139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 352cab237bSDimitry Andric #include "llvm/IR/DataLayout.h" 36ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h" 37ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 38d88c1a5aSDimitry Andric #include "llvm/IR/DebugLoc.h" 39139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 40d88c1a5aSDimitry Andric #include "llvm/IR/Function.h" 41db17bf38SDimitry Andric #include "llvm/IR/GVMaterializer.h" 42d88c1a5aSDimitry Andric #include "llvm/IR/GlobalAlias.h" 43d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIFunc.h" 44d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIndirectSymbol.h" 45d88c1a5aSDimitry Andric #include "llvm/IR/GlobalObject.h" 46d88c1a5aSDimitry Andric #include "llvm/IR/GlobalValue.h" 47d88c1a5aSDimitry Andric #include "llvm/IR/GlobalVariable.h" 48139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h" 49d88c1a5aSDimitry Andric #include "llvm/IR/InstIterator.h" 50d88c1a5aSDimitry Andric #include "llvm/IR/InstrTypes.h" 51d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h" 52d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h" 53d88c1a5aSDimitry Andric #include "llvm/IR/Intrinsics.h" 54f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h" 552cab237bSDimitry Andric #include "llvm/IR/Metadata.h" 56139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 573ca95b02SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h" 58139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 59d88c1a5aSDimitry Andric #include "llvm/IR/Type.h" 602cab237bSDimitry Andric #include "llvm/IR/Value.h" 61d88c1a5aSDimitry Andric #include "llvm/IR/Verifier.h" 62d88c1a5aSDimitry Andric #include "llvm/Support/AtomicOrdering.h" 63d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h" 643ca95b02SDimitry Andric #include "llvm/Support/CommandLine.h" 65d88c1a5aSDimitry Andric #include "llvm/Support/Compiler.h" 663ca95b02SDimitry Andric #include "llvm/Support/Debug.h" 67d88c1a5aSDimitry Andric #include "llvm/Support/Error.h" 68d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h" 692cab237bSDimitry Andric #include "llvm/Support/ErrorOr.h" 7039d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h" 712cab237bSDimitry Andric #include "llvm/Support/MathExtras.h" 72f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h" 73f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h" 74d88c1a5aSDimitry Andric #include <algorithm> 75d88c1a5aSDimitry Andric #include <cassert> 76d88c1a5aSDimitry Andric #include <cstddef> 77d88c1a5aSDimitry Andric #include <cstdint> 78ff0cc061SDimitry Andric #include <deque> 79d88c1a5aSDimitry Andric #include <map> 80d88c1a5aSDimitry Andric #include <memory> 812cab237bSDimitry Andric #include <set> 82d88c1a5aSDimitry Andric #include <string> 83d88c1a5aSDimitry Andric #include <system_error> 84d88c1a5aSDimitry Andric #include <tuple> 853ca95b02SDimitry Andric #include <utility> 86d88c1a5aSDimitry Andric #include <vector> 873ca95b02SDimitry Andric 88f22ef01cSRoman Divacky using namespace llvm; 89f22ef01cSRoman Divacky 903ca95b02SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs( 913ca95b02SDimitry Andric "print-summary-global-ids", cl::init(false), cl::Hidden, 923ca95b02SDimitry Andric cl::desc( 933ca95b02SDimitry Andric "Print the global id for each value when reading the module summary")); 943ca95b02SDimitry Andric 95ff0cc061SDimitry Andric namespace { 96d88c1a5aSDimitry Andric 977ae0e2c9SDimitry Andric enum { 987ae0e2c9SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 997ae0e2c9SDimitry Andric }; 1007ae0e2c9SDimitry Andric 1012cab237bSDimitry Andric } // end anonymous namespace 1022cab237bSDimitry Andric 1032cab237bSDimitry Andric static Error error(const Twine &Message) { 104d88c1a5aSDimitry Andric return make_error<StringError>( 105d88c1a5aSDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode)); 106ff0cc061SDimitry Andric } 107ff0cc061SDimitry Andric 108d88c1a5aSDimitry Andric /// Helper to read the header common to all bitcode files. 1092cab237bSDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 110d88c1a5aSDimitry Andric // Sniff for the signature. 111d88c1a5aSDimitry Andric if (!Stream.canSkipToPos(4) || 112d88c1a5aSDimitry Andric Stream.Read(8) != 'B' || 113d88c1a5aSDimitry Andric Stream.Read(8) != 'C' || 114d88c1a5aSDimitry Andric Stream.Read(4) != 0x0 || 115d88c1a5aSDimitry Andric Stream.Read(4) != 0xC || 116d88c1a5aSDimitry Andric Stream.Read(4) != 0xE || 117d88c1a5aSDimitry Andric Stream.Read(4) != 0xD) 118d88c1a5aSDimitry Andric return false; 119d88c1a5aSDimitry Andric return true; 120ff0cc061SDimitry Andric } 121ff0cc061SDimitry Andric 1222cab237bSDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 123d88c1a5aSDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 124d88c1a5aSDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 125d88c1a5aSDimitry Andric 126d88c1a5aSDimitry Andric if (Buffer.getBufferSize() & 3) 127d88c1a5aSDimitry Andric return error("Invalid bitcode signature"); 128d88c1a5aSDimitry Andric 129d88c1a5aSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 130d88c1a5aSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 131d88c1a5aSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 132d88c1a5aSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 133d88c1a5aSDimitry Andric return error("Invalid bitcode wrapper header"); 134d88c1a5aSDimitry Andric 135d88c1a5aSDimitry Andric BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 136d88c1a5aSDimitry Andric if (!hasValidBitcodeHeader(Stream)) 137d88c1a5aSDimitry Andric return error("Invalid bitcode signature"); 138d88c1a5aSDimitry Andric 139d88c1a5aSDimitry Andric return std::move(Stream); 140ff0cc061SDimitry Andric } 141ff0cc061SDimitry Andric 142d88c1a5aSDimitry Andric /// Convert a string from a record into an std::string, return true on failure. 143d88c1a5aSDimitry Andric template <typename StrTy> 144d88c1a5aSDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 145d88c1a5aSDimitry Andric StrTy &Result) { 146d88c1a5aSDimitry Andric if (Idx > Record.size()) 147d88c1a5aSDimitry Andric return true; 148d88c1a5aSDimitry Andric 149d88c1a5aSDimitry Andric for (unsigned i = Idx, e = Record.size(); i != e; ++i) 150d88c1a5aSDimitry Andric Result += (char)Record[i]; 151d88c1a5aSDimitry Andric return false; 152ff0cc061SDimitry Andric } 153ff0cc061SDimitry Andric 154d88c1a5aSDimitry Andric // Strip all the TBAA attachment for the module. 1552cab237bSDimitry Andric static void stripTBAA(Module *M) { 156d88c1a5aSDimitry Andric for (auto &F : *M) { 157d88c1a5aSDimitry Andric if (F.isMaterializable()) 158d88c1a5aSDimitry Andric continue; 159d88c1a5aSDimitry Andric for (auto &I : instructions(F)) 160d88c1a5aSDimitry Andric I.setMetadata(LLVMContext::MD_tbaa, nullptr); 161d88c1a5aSDimitry Andric } 162d88c1a5aSDimitry Andric } 163ff0cc061SDimitry Andric 164d88c1a5aSDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 165d88c1a5aSDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any. 1662cab237bSDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 167d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 168d88c1a5aSDimitry Andric return error("Invalid record"); 169ff0cc061SDimitry Andric 170d88c1a5aSDimitry Andric // Read all the records. 171d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 172d88c1a5aSDimitry Andric 173d88c1a5aSDimitry Andric std::string ProducerIdentification; 174d88c1a5aSDimitry Andric 175d88c1a5aSDimitry Andric while (true) { 176d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 177d88c1a5aSDimitry Andric 178d88c1a5aSDimitry Andric switch (Entry.Kind) { 179d88c1a5aSDimitry Andric default: 180d88c1a5aSDimitry Andric case BitstreamEntry::Error: 181d88c1a5aSDimitry Andric return error("Malformed block"); 182d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 183d88c1a5aSDimitry Andric return ProducerIdentification; 184d88c1a5aSDimitry Andric case BitstreamEntry::Record: 185d88c1a5aSDimitry Andric // The interesting case. 186d88c1a5aSDimitry Andric break; 187d88c1a5aSDimitry Andric } 188d88c1a5aSDimitry Andric 189d88c1a5aSDimitry Andric // Read a record. 190d88c1a5aSDimitry Andric Record.clear(); 191d88c1a5aSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 192d88c1a5aSDimitry Andric switch (BitCode) { 193d88c1a5aSDimitry Andric default: // Default behavior: reject 194d88c1a5aSDimitry Andric return error("Invalid value"); 195d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 196d88c1a5aSDimitry Andric convertToString(Record, 0, ProducerIdentification); 197d88c1a5aSDimitry Andric break; 198d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 199d88c1a5aSDimitry Andric unsigned epoch = (unsigned)Record[0]; 200d88c1a5aSDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 201d88c1a5aSDimitry Andric return error( 202d88c1a5aSDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 203d88c1a5aSDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 204d88c1a5aSDimitry Andric } 205d88c1a5aSDimitry Andric } 206d88c1a5aSDimitry Andric } 207d88c1a5aSDimitry Andric } 208d88c1a5aSDimitry Andric } 209d88c1a5aSDimitry Andric 2102cab237bSDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 211d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 212d88c1a5aSDimitry Andric // need to understand them all. 213d88c1a5aSDimitry Andric while (true) { 214d88c1a5aSDimitry Andric if (Stream.AtEndOfStream()) 215d88c1a5aSDimitry Andric return ""; 216d88c1a5aSDimitry Andric 217d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 218d88c1a5aSDimitry Andric switch (Entry.Kind) { 219d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 220d88c1a5aSDimitry Andric case BitstreamEntry::Error: 221d88c1a5aSDimitry Andric return error("Malformed block"); 222d88c1a5aSDimitry Andric 223d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 224d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 225d88c1a5aSDimitry Andric return readIdentificationBlock(Stream); 226d88c1a5aSDimitry Andric 227d88c1a5aSDimitry Andric // Ignore other sub-blocks. 228d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 229d88c1a5aSDimitry Andric return error("Malformed block"); 230d88c1a5aSDimitry Andric continue; 231d88c1a5aSDimitry Andric case BitstreamEntry::Record: 232d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 233d88c1a5aSDimitry Andric continue; 234d88c1a5aSDimitry Andric } 235d88c1a5aSDimitry Andric } 236d88c1a5aSDimitry Andric } 237d88c1a5aSDimitry Andric 2382cab237bSDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 239d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 240d88c1a5aSDimitry Andric return error("Invalid record"); 241d88c1a5aSDimitry Andric 242d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 243d88c1a5aSDimitry Andric // Read all the records for this module. 244d88c1a5aSDimitry Andric 245d88c1a5aSDimitry Andric while (true) { 246d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 247d88c1a5aSDimitry Andric 248d88c1a5aSDimitry Andric switch (Entry.Kind) { 249d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 250d88c1a5aSDimitry Andric case BitstreamEntry::Error: 251d88c1a5aSDimitry Andric return error("Malformed block"); 252d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 253d88c1a5aSDimitry Andric return false; 254d88c1a5aSDimitry Andric case BitstreamEntry::Record: 255d88c1a5aSDimitry Andric // The interesting case. 256d88c1a5aSDimitry Andric break; 257d88c1a5aSDimitry Andric } 258d88c1a5aSDimitry Andric 259d88c1a5aSDimitry Andric // Read a record. 260d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 261d88c1a5aSDimitry Andric default: 262d88c1a5aSDimitry Andric break; // Default behavior, ignore unknown content. 263d88c1a5aSDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 264d88c1a5aSDimitry Andric std::string S; 265d88c1a5aSDimitry Andric if (convertToString(Record, 0, S)) 266d88c1a5aSDimitry Andric return error("Invalid record"); 267d88c1a5aSDimitry Andric // Check for the i386 and other (x86_64, ARM) conventions 268d88c1a5aSDimitry Andric if (S.find("__DATA,__objc_catlist") != std::string::npos || 269d88c1a5aSDimitry Andric S.find("__OBJC,__category") != std::string::npos) 270d88c1a5aSDimitry Andric return true; 271d88c1a5aSDimitry Andric break; 272d88c1a5aSDimitry Andric } 273d88c1a5aSDimitry Andric } 274d88c1a5aSDimitry Andric Record.clear(); 275d88c1a5aSDimitry Andric } 276d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop"); 277d88c1a5aSDimitry Andric } 278d88c1a5aSDimitry Andric 2792cab237bSDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 280d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 281d88c1a5aSDimitry Andric // need to understand them all. 282d88c1a5aSDimitry Andric while (true) { 283d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 284d88c1a5aSDimitry Andric 285d88c1a5aSDimitry Andric switch (Entry.Kind) { 286d88c1a5aSDimitry Andric case BitstreamEntry::Error: 287d88c1a5aSDimitry Andric return error("Malformed block"); 288d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 289d88c1a5aSDimitry Andric return false; 290d88c1a5aSDimitry Andric 291d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 292d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 293d88c1a5aSDimitry Andric return hasObjCCategoryInModule(Stream); 294d88c1a5aSDimitry Andric 295d88c1a5aSDimitry Andric // Ignore other sub-blocks. 296d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 297d88c1a5aSDimitry Andric return error("Malformed block"); 298d88c1a5aSDimitry Andric continue; 299d88c1a5aSDimitry Andric 300d88c1a5aSDimitry Andric case BitstreamEntry::Record: 301d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 302d88c1a5aSDimitry Andric continue; 303d88c1a5aSDimitry Andric } 304d88c1a5aSDimitry Andric } 305d88c1a5aSDimitry Andric } 306d88c1a5aSDimitry Andric 3072cab237bSDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 308d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 309d88c1a5aSDimitry Andric return error("Invalid record"); 310d88c1a5aSDimitry Andric 311d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record; 312d88c1a5aSDimitry Andric 313d88c1a5aSDimitry Andric std::string Triple; 314d88c1a5aSDimitry Andric 315d88c1a5aSDimitry Andric // Read all the records for this module. 316d88c1a5aSDimitry Andric while (true) { 317d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 318d88c1a5aSDimitry Andric 319d88c1a5aSDimitry Andric switch (Entry.Kind) { 320d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 321d88c1a5aSDimitry Andric case BitstreamEntry::Error: 322d88c1a5aSDimitry Andric return error("Malformed block"); 323d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 324d88c1a5aSDimitry Andric return Triple; 325d88c1a5aSDimitry Andric case BitstreamEntry::Record: 326d88c1a5aSDimitry Andric // The interesting case. 327d88c1a5aSDimitry Andric break; 328d88c1a5aSDimitry Andric } 329d88c1a5aSDimitry Andric 330d88c1a5aSDimitry Andric // Read a record. 331d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 332d88c1a5aSDimitry Andric default: break; // Default behavior, ignore unknown content. 333d88c1a5aSDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 334d88c1a5aSDimitry Andric std::string S; 335d88c1a5aSDimitry Andric if (convertToString(Record, 0, S)) 336d88c1a5aSDimitry Andric return error("Invalid record"); 337d88c1a5aSDimitry Andric Triple = S; 338d88c1a5aSDimitry Andric break; 339d88c1a5aSDimitry Andric } 340d88c1a5aSDimitry Andric } 341d88c1a5aSDimitry Andric Record.clear(); 342d88c1a5aSDimitry Andric } 343d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop"); 344d88c1a5aSDimitry Andric } 345d88c1a5aSDimitry Andric 3462cab237bSDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) { 347d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 348d88c1a5aSDimitry Andric // need to understand them all. 349d88c1a5aSDimitry Andric while (true) { 350d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 351d88c1a5aSDimitry Andric 352d88c1a5aSDimitry Andric switch (Entry.Kind) { 353d88c1a5aSDimitry Andric case BitstreamEntry::Error: 354d88c1a5aSDimitry Andric return error("Malformed block"); 355d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 356d88c1a5aSDimitry Andric return ""; 357d88c1a5aSDimitry Andric 358d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 359d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 360d88c1a5aSDimitry Andric return readModuleTriple(Stream); 361d88c1a5aSDimitry Andric 362d88c1a5aSDimitry Andric // Ignore other sub-blocks. 363d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 364d88c1a5aSDimitry Andric return error("Malformed block"); 365d88c1a5aSDimitry Andric continue; 366d88c1a5aSDimitry Andric 367d88c1a5aSDimitry Andric case BitstreamEntry::Record: 368d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 369d88c1a5aSDimitry Andric continue; 370d88c1a5aSDimitry Andric } 371d88c1a5aSDimitry Andric } 372d88c1a5aSDimitry Andric } 373d88c1a5aSDimitry Andric 3742cab237bSDimitry Andric namespace { 3752cab237bSDimitry Andric 376d88c1a5aSDimitry Andric class BitcodeReaderBase { 377d88c1a5aSDimitry Andric protected: 3786bc11b14SDimitry Andric BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) 3796bc11b14SDimitry Andric : Stream(std::move(Stream)), Strtab(Strtab) { 380d88c1a5aSDimitry Andric this->Stream.setBlockInfo(&BlockInfo); 381d88c1a5aSDimitry Andric } 382d88c1a5aSDimitry Andric 383d88c1a5aSDimitry Andric BitstreamBlockInfo BlockInfo; 384d88c1a5aSDimitry Andric BitstreamCursor Stream; 3856bc11b14SDimitry Andric StringRef Strtab; 3866bc11b14SDimitry Andric 3876bc11b14SDimitry Andric /// In version 2 of the bitcode we store names of global values and comdats in 3886bc11b14SDimitry Andric /// a string table rather than in the VST. 3896bc11b14SDimitry Andric bool UseStrtab = false; 390d88c1a5aSDimitry Andric 3917a7e6055SDimitry Andric Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); 3927a7e6055SDimitry Andric 3936bc11b14SDimitry Andric /// If this module uses a string table, pop the reference to the string table 3946bc11b14SDimitry Andric /// and return the referenced string and the rest of the record. Otherwise 3956bc11b14SDimitry Andric /// just return the record itself. 3966bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 3976bc11b14SDimitry Andric readNameFromStrtab(ArrayRef<uint64_t> Record); 3986bc11b14SDimitry Andric 399d88c1a5aSDimitry Andric bool readBlockInfo(); 400d88c1a5aSDimitry Andric 401d88c1a5aSDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer 402d88c1a5aSDimitry Andric std::string ProducerIdentification; 403d88c1a5aSDimitry Andric 404d88c1a5aSDimitry Andric Error error(const Twine &Message); 405ff0cc061SDimitry Andric }; 406ff0cc061SDimitry Andric 4072cab237bSDimitry Andric } // end anonymous namespace 4082cab237bSDimitry Andric 409d88c1a5aSDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) { 410d88c1a5aSDimitry Andric std::string FullMsg = Message.str(); 411d88c1a5aSDimitry Andric if (!ProducerIdentification.empty()) 412d88c1a5aSDimitry Andric FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 413d88c1a5aSDimitry Andric LLVM_VERSION_STRING "')"; 414d88c1a5aSDimitry Andric return ::error(FullMsg); 415ff0cc061SDimitry Andric } 416ff0cc061SDimitry Andric 4177a7e6055SDimitry Andric Expected<unsigned> 4187a7e6055SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { 4192cab237bSDimitry Andric if (Record.empty()) 4207a7e6055SDimitry Andric return error("Invalid record"); 4217a7e6055SDimitry Andric unsigned ModuleVersion = Record[0]; 4226bc11b14SDimitry Andric if (ModuleVersion > 2) 4237a7e6055SDimitry Andric return error("Invalid value"); 4246bc11b14SDimitry Andric UseStrtab = ModuleVersion >= 2; 4257a7e6055SDimitry Andric return ModuleVersion; 4267a7e6055SDimitry Andric } 4277a7e6055SDimitry Andric 4286bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>> 4296bc11b14SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { 4306bc11b14SDimitry Andric if (!UseStrtab) 4316bc11b14SDimitry Andric return {"", Record}; 4326bc11b14SDimitry Andric // Invalid reference. Let the caller complain about the record being empty. 4336bc11b14SDimitry Andric if (Record[0] + Record[1] > Strtab.size()) 4346bc11b14SDimitry Andric return {"", {}}; 4356bc11b14SDimitry Andric return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; 4366bc11b14SDimitry Andric } 4376bc11b14SDimitry Andric 4382cab237bSDimitry Andric namespace { 4392cab237bSDimitry Andric 440d88c1a5aSDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 441ff0cc061SDimitry Andric LLVMContext &Context; 4428f0fd8f6SDimitry Andric Module *TheModule = nullptr; 4437d523365SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies. 4448f0fd8f6SDimitry Andric uint64_t NextUnreadBit = 0; 4457d523365SDimitry Andric // Last function offset found in the VST. 4467d523365SDimitry Andric uint64_t LastFunctionBlockBit = 0; 4478f0fd8f6SDimitry Andric bool SeenValueSymbolTable = false; 4487d523365SDimitry Andric uint64_t VSTOffset = 0; 449ff0cc061SDimitry Andric 4507a7e6055SDimitry Andric std::vector<std::string> SectionTable; 4517a7e6055SDimitry Andric std::vector<std::string> GCTable; 4527a7e6055SDimitry Andric 453ff0cc061SDimitry Andric std::vector<Type*> TypeList; 454ff0cc061SDimitry Andric BitcodeReaderValueList ValueList; 455d88c1a5aSDimitry Andric Optional<MetadataLoader> MDLoader; 456ff0cc061SDimitry Andric std::vector<Comdat *> ComdatList; 457ff0cc061SDimitry Andric SmallVector<Instruction *, 64> InstructionList; 458ff0cc061SDimitry Andric 459ff0cc061SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; 4603ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits; 461ff0cc061SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrefixes; 462ff0cc061SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrologues; 4638f0fd8f6SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns; 464ff0cc061SDimitry Andric 4658f0fd8f6SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and 4668f0fd8f6SDimitry Andric /// is thus not represented here. As such all indices are off by one. 4677a7e6055SDimitry Andric std::vector<AttributeList> MAttributes; 468ff0cc061SDimitry Andric 4697d523365SDimitry Andric /// The set of attribute groups. 4707a7e6055SDimitry Andric std::map<unsigned, AttributeList> MAttributeGroups; 471ff0cc061SDimitry Andric 4728f0fd8f6SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the 4738f0fd8f6SDimitry Andric /// function. 474ff0cc061SDimitry Andric std::vector<BasicBlock*> FunctionBBs; 475ff0cc061SDimitry Andric 476ff0cc061SDimitry Andric // When reading the module header, this list is populated with functions that 477ff0cc061SDimitry Andric // have bodies later in the file. 478ff0cc061SDimitry Andric std::vector<Function*> FunctionsWithBodies; 479ff0cc061SDimitry Andric 480ff0cc061SDimitry Andric // When intrinsic functions are encountered which require upgrading they are 481ff0cc061SDimitry Andric // stored here with their replacement function. 4822cab237bSDimitry Andric using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; 4833ca95b02SDimitry Andric UpdatedIntrinsicMap UpgradedIntrinsics; 4843ca95b02SDimitry Andric // Intrinsics which were remangled because of types rename 4853ca95b02SDimitry Andric UpdatedIntrinsicMap RemangledIntrinsics; 486ff0cc061SDimitry Andric 487ff0cc061SDimitry Andric // Several operations happen after the module header has been read, but 488ff0cc061SDimitry Andric // before function bodies are processed. This keeps track of whether 489ff0cc061SDimitry Andric // we've done this yet. 4908f0fd8f6SDimitry Andric bool SeenFirstFunctionBody = false; 491ff0cc061SDimitry Andric 4928f0fd8f6SDimitry Andric /// When function bodies are initially scanned, this map contains info about 4938f0fd8f6SDimitry Andric /// where to find deferred function body in the stream. 494ff0cc061SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo; 495ff0cc061SDimitry Andric 496ff0cc061SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may 497ff0cc061SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about 498ff0cc061SDimitry Andric /// which Metadata blocks are deferred. 499ff0cc061SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo; 500ff0cc061SDimitry Andric 501ff0cc061SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are 502ff0cc061SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is 503ff0cc061SDimitry Andric /// its index into the vector. 504ff0cc061SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 505ff0cc061SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue; 506ff0cc061SDimitry Andric 5078f0fd8f6SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where 5088f0fd8f6SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the 5098f0fd8f6SDimitry Andric /// instruction number, for a more compact encoding. Some instruction 5108f0fd8f6SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and 5118f0fd8f6SDimitry Andric /// types. Once the old style function blocks have been phased out, we would 512ff0cc061SDimitry Andric /// not need this flag. 5138f0fd8f6SDimitry Andric bool UseRelativeIDs = false; 514ff0cc061SDimitry Andric 515ff0cc061SDimitry Andric /// True if all functions will be materialized, negating the need to process 516ff0cc061SDimitry Andric /// (e.g.) blockaddress forward references. 5178f0fd8f6SDimitry Andric bool WillMaterializeAllForwardRefs = false; 518ff0cc061SDimitry Andric 519ff0cc061SDimitry Andric bool StripDebugInfo = false; 520d88c1a5aSDimitry Andric TBAAVerifier TBAAVerifyHelper; 5217d523365SDimitry Andric 5227d523365SDimitry Andric std::vector<std::string> BundleTags; 523c4394386SDimitry Andric SmallVector<SyncScope::ID, 8> SSIDs; 5247d523365SDimitry Andric 525ff0cc061SDimitry Andric public: 5266bc11b14SDimitry Andric BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 5276bc11b14SDimitry Andric StringRef ProducerIdentification, LLVMContext &Context); 528ff0cc061SDimitry Andric 529d88c1a5aSDimitry Andric Error materializeForwardReferencedFunctions(); 530ff0cc061SDimitry Andric 531d88c1a5aSDimitry Andric Error materialize(GlobalValue *GV) override; 532d88c1a5aSDimitry Andric Error materializeModule() override; 533ff0cc061SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override; 534ff0cc061SDimitry Andric 5358f0fd8f6SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 5368f0fd8f6SDimitry Andric /// \returns true if an error occurred. 537d88c1a5aSDimitry Andric Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false, 538d88c1a5aSDimitry Andric bool IsImporting = false); 5393ca95b02SDimitry Andric 540ff0cc061SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V); 541ff0cc061SDimitry Andric 542ff0cc061SDimitry Andric /// Materialize any deferred Metadata block. 543d88c1a5aSDimitry Andric Error materializeMetadata() override; 544ff0cc061SDimitry Andric 545ff0cc061SDimitry Andric void setStripDebugInfo() override; 546ff0cc061SDimitry Andric 547ff0cc061SDimitry Andric private: 548ff0cc061SDimitry Andric std::vector<StructType *> IdentifiedStructTypes; 549ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 550ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context); 551ff0cc061SDimitry Andric 552ff0cc061SDimitry Andric Type *getTypeByID(unsigned ID); 553d88c1a5aSDimitry Andric 554ff0cc061SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty) { 555ff0cc061SDimitry Andric if (Ty && Ty->isMetadataTy()) 556ff0cc061SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 557ff0cc061SDimitry Andric return ValueList.getValueFwdRef(ID, Ty); 558ff0cc061SDimitry Andric } 559d88c1a5aSDimitry Andric 560ff0cc061SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) { 561f8496407SDimitry Andric return MDLoader->getMetadataFwdRefOrLoad(ID); 562ff0cc061SDimitry Andric } 563d88c1a5aSDimitry Andric 564ff0cc061SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const { 565ff0cc061SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 566ff0cc061SDimitry Andric return FunctionBBs[ID]; 567ff0cc061SDimitry Andric } 568d88c1a5aSDimitry Andric 5697a7e6055SDimitry Andric AttributeList getAttributes(unsigned i) const { 570ff0cc061SDimitry Andric if (i-1 < MAttributes.size()) 571ff0cc061SDimitry Andric return MAttributes[i-1]; 5727a7e6055SDimitry Andric return AttributeList(); 573ff0cc061SDimitry Andric } 574ff0cc061SDimitry Andric 5758f0fd8f6SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'. 5768f0fd8f6SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on 5778f0fd8f6SDimitry Andric /// failure. 578ff0cc061SDimitry Andric bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 579ff0cc061SDimitry Andric unsigned InstNum, Value *&ResVal) { 580ff0cc061SDimitry Andric if (Slot == Record.size()) return true; 581ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++]; 582ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 583ff0cc061SDimitry Andric if (UseRelativeIDs) 584ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 585ff0cc061SDimitry Andric if (ValNo < InstNum) { 586ff0cc061SDimitry Andric // If this is not a forward reference, just return the value we already 587ff0cc061SDimitry Andric // have. 588ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr); 589ff0cc061SDimitry Andric return ResVal == nullptr; 590ff0cc061SDimitry Andric } 591ff0cc061SDimitry Andric if (Slot == Record.size()) 592ff0cc061SDimitry Andric return true; 593ff0cc061SDimitry Andric 594ff0cc061SDimitry Andric unsigned TypeNo = (unsigned)Record[Slot++]; 595ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 596ff0cc061SDimitry Andric return ResVal == nullptr; 597ff0cc061SDimitry Andric } 598ff0cc061SDimitry Andric 5998f0fd8f6SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot 6008f0fd8f6SDimitry Andric /// past the number of slots used by the value in the record. Return true if 6018f0fd8f6SDimitry Andric /// there is an error. 602ff0cc061SDimitry Andric bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 603ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 604ff0cc061SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, ResVal)) 605ff0cc061SDimitry Andric return true; 606ff0cc061SDimitry Andric // All values currently take a single record slot. 607ff0cc061SDimitry Andric ++Slot; 608ff0cc061SDimitry Andric return false; 609ff0cc061SDimitry Andric } 610ff0cc061SDimitry Andric 6118f0fd8f6SDimitry Andric /// Like popValue, but does not increment the Slot number. 612ff0cc061SDimitry Andric bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 613ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 614ff0cc061SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty); 615ff0cc061SDimitry Andric return ResVal == nullptr; 616ff0cc061SDimitry Andric } 617ff0cc061SDimitry Andric 6188f0fd8f6SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an 6198f0fd8f6SDimitry Andric /// error. 620ff0cc061SDimitry Andric Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 621ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 622ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 623ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot]; 624ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 625ff0cc061SDimitry Andric if (UseRelativeIDs) 626ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 627ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 628ff0cc061SDimitry Andric } 629ff0cc061SDimitry Andric 6308f0fd8f6SDimitry Andric /// Like getValue, but decodes signed VBRs. 631ff0cc061SDimitry Andric Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 632ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 633ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 634ff0cc061SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 635ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 636ff0cc061SDimitry Andric if (UseRelativeIDs) 637ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 638ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 639ff0cc061SDimitry Andric } 640ff0cc061SDimitry Andric 641ff0cc061SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the 642ff0cc061SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns 643ff0cc061SDimitry Andric /// a corresponding error code. 644d88c1a5aSDimitry Andric Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 645d88c1a5aSDimitry Andric Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 646d88c1a5aSDimitry Andric Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false); 6477a7e6055SDimitry Andric 6487a7e6055SDimitry Andric Error parseComdatRecord(ArrayRef<uint64_t> Record); 6497a7e6055SDimitry Andric Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); 6507a7e6055SDimitry Andric Error parseFunctionRecord(ArrayRef<uint64_t> Record); 6517a7e6055SDimitry Andric Error parseGlobalIndirectSymbolRecord(unsigned BitCode, 6527a7e6055SDimitry Andric ArrayRef<uint64_t> Record); 6537a7e6055SDimitry Andric 654d88c1a5aSDimitry Andric Error parseAttributeBlock(); 655d88c1a5aSDimitry Andric Error parseAttributeGroupBlock(); 656d88c1a5aSDimitry Andric Error parseTypeTable(); 657d88c1a5aSDimitry Andric Error parseTypeTableBody(); 658d88c1a5aSDimitry Andric Error parseOperandBundleTags(); 659c4394386SDimitry Andric Error parseSyncScopeNames(); 660ff0cc061SDimitry Andric 661d88c1a5aSDimitry Andric Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 6627d523365SDimitry Andric unsigned NameIndex, Triple &TT); 6636bc11b14SDimitry Andric void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, 6646bc11b14SDimitry Andric ArrayRef<uint64_t> Record); 665d88c1a5aSDimitry Andric Error parseValueSymbolTable(uint64_t Offset = 0); 6666bc11b14SDimitry Andric Error parseGlobalValueSymbolTable(); 667d88c1a5aSDimitry Andric Error parseConstants(); 668d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBodies(); 669d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBody(); 670ff0cc061SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks. 671d88c1a5aSDimitry Andric Error rememberAndSkipMetadata(); 672d88c1a5aSDimitry Andric Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 673d88c1a5aSDimitry Andric Error parseFunctionBody(Function *F); 674d88c1a5aSDimitry Andric Error globalCleanup(); 675d88c1a5aSDimitry Andric Error resolveGlobalAndIndirectSymbolInits(); 676d88c1a5aSDimitry Andric Error parseUseLists(); 677d88c1a5aSDimitry Andric Error findFunctionInStream( 678ff0cc061SDimitry Andric Function *F, 679ff0cc061SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 680c4394386SDimitry Andric 681c4394386SDimitry Andric SyncScope::ID getDecodedSyncScopeID(unsigned Val); 682ff0cc061SDimitry Andric }; 6837d523365SDimitry Andric 6847d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode 6857d523365SDimitry Andric /// files/sections. 686d88c1a5aSDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 687d88c1a5aSDimitry Andric /// The module index built during parsing. 688d88c1a5aSDimitry Andric ModuleSummaryIndex &TheIndex; 6897d523365SDimitry Andric 6903ca95b02SDimitry Andric /// Indicates whether we have encountered a global value summary section 691d88c1a5aSDimitry Andric /// yet during parsing. 6923ca95b02SDimitry Andric bool SeenGlobalValSummary = false; 6937d523365SDimitry Andric 6943ca95b02SDimitry Andric /// Indicates whether we have already parsed the VST, used for error checking. 6953ca95b02SDimitry Andric bool SeenValueSymbolTable = false; 6963ca95b02SDimitry Andric 6973ca95b02SDimitry Andric /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 6983ca95b02SDimitry Andric /// Used to enable on-demand parsing of the VST. 6993ca95b02SDimitry Andric uint64_t VSTOffset = 0; 7003ca95b02SDimitry Andric 7010f5676f4SDimitry Andric // Map to save ValueId to ValueInfo association that was recorded in the 7023ca95b02SDimitry Andric // ValueSymbolTable. It is used after the VST is parsed to convert 7033ca95b02SDimitry Andric // call graph edges read from the function summary from referencing 7040f5676f4SDimitry Andric // callees by their ValueId to using the ValueInfo instead, which is how 7053ca95b02SDimitry Andric // they are recorded in the summary index being built. 7060f5676f4SDimitry Andric // We save a GUID which refers to the same global as the ValueInfo, but 7070f5676f4SDimitry Andric // ignoring the linkage, i.e. for values other than local linkage they are 7080f5676f4SDimitry Andric // identical. 7090f5676f4SDimitry Andric DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>> 7100f5676f4SDimitry Andric ValueIdToValueInfoMap; 7117d523365SDimitry Andric 7127d523365SDimitry Andric /// Map populated during module path string table parsing, from the 7137d523365SDimitry Andric /// module ID to a string reference owned by the index's module 7143ca95b02SDimitry Andric /// path string table, used to correlate with combined index 7157d523365SDimitry Andric /// summary records. 7167d523365SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap; 7177d523365SDimitry Andric 7183ca95b02SDimitry Andric /// Original source file name recorded in a bitcode record. 7193ca95b02SDimitry Andric std::string SourceFileName; 7203ca95b02SDimitry Andric 721f37b6182SDimitry Andric /// The string identifier given to this module by the client, normally the 722f37b6182SDimitry Andric /// path to the bitcode file. 723f37b6182SDimitry Andric StringRef ModulePath; 724f37b6182SDimitry Andric 725f37b6182SDimitry Andric /// For per-module summary indexes, the unique numerical identifier given to 726f37b6182SDimitry Andric /// this module by the client. 727f37b6182SDimitry Andric unsigned ModuleId; 728f37b6182SDimitry Andric 7297d523365SDimitry Andric public: 7306bc11b14SDimitry Andric ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab, 731f37b6182SDimitry Andric ModuleSummaryIndex &TheIndex, 732f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId); 7337d523365SDimitry Andric 734f37b6182SDimitry Andric Error parseModule(); 7357d523365SDimitry Andric 7367d523365SDimitry Andric private: 7376bc11b14SDimitry Andric void setValueGUID(uint64_t ValueID, StringRef ValueName, 7386bc11b14SDimitry Andric GlobalValue::LinkageTypes Linkage, 7396bc11b14SDimitry Andric StringRef SourceFileName); 740d88c1a5aSDimitry Andric Error parseValueSymbolTable( 7413ca95b02SDimitry Andric uint64_t Offset, 7423ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 743d88c1a5aSDimitry Andric std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); 744d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, 745d88c1a5aSDimitry Andric bool IsOldProfileFormat, 746d88c1a5aSDimitry Andric bool HasProfile); 74724d58133SDimitry Andric Error parseEntireSummary(unsigned ID); 748d88c1a5aSDimitry Andric Error parseModuleStringTable(); 749d88c1a5aSDimitry Andric 7500f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID> 7510f5676f4SDimitry Andric getValueInfoFromValueId(unsigned ValueId); 752f37b6182SDimitry Andric 75324d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *addThisModule(); 7547d523365SDimitry Andric }; 755d88c1a5aSDimitry Andric 7563ca95b02SDimitry Andric } // end anonymous namespace 757ff0cc061SDimitry Andric 758d88c1a5aSDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 759d88c1a5aSDimitry Andric Error Err) { 760d88c1a5aSDimitry Andric if (Err) { 761d88c1a5aSDimitry Andric std::error_code EC; 762d88c1a5aSDimitry Andric handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 763d88c1a5aSDimitry Andric EC = EIB.convertToErrorCode(); 764d88c1a5aSDimitry Andric Ctx.emitError(EIB.message()); 765d88c1a5aSDimitry Andric }); 76639d628a0SDimitry Andric return EC; 767dff0c46cSDimitry Andric } 76839d628a0SDimitry Andric return std::error_code(); 769d88c1a5aSDimitry Andric } 770d88c1a5aSDimitry Andric 7716bc11b14SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 772d88c1a5aSDimitry Andric StringRef ProducerIdentification, 773d88c1a5aSDimitry Andric LLVMContext &Context) 7746bc11b14SDimitry Andric : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), 775d88c1a5aSDimitry Andric ValueList(Context) { 776d88c1a5aSDimitry Andric this->ProducerIdentification = ProducerIdentification; 777d88c1a5aSDimitry Andric } 778d88c1a5aSDimitry Andric 779d88c1a5aSDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() { 780d88c1a5aSDimitry Andric if (WillMaterializeAllForwardRefs) 781d88c1a5aSDimitry Andric return Error::success(); 78239d628a0SDimitry Andric 78339d628a0SDimitry Andric // Prevent recursion. 78439d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 78539d628a0SDimitry Andric 78639d628a0SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) { 78739d628a0SDimitry Andric Function *F = BasicBlockFwdRefQueue.front(); 78839d628a0SDimitry Andric BasicBlockFwdRefQueue.pop_front(); 78939d628a0SDimitry Andric assert(F && "Expected valid function"); 79039d628a0SDimitry Andric if (!BasicBlockFwdRefs.count(F)) 79139d628a0SDimitry Andric // Already materialized. 79239d628a0SDimitry Andric continue; 79339d628a0SDimitry Andric 79439d628a0SDimitry Andric // Check for a function that isn't materializable to prevent an infinite 79539d628a0SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there 79639d628a0SDimitry Andric // isn't a trivial way to check if a function will have a body without a 79739d628a0SDimitry Andric // linear search through FunctionsWithBodies, so just check it here. 79839d628a0SDimitry Andric if (!F->isMaterializable()) 7998f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 80039d628a0SDimitry Andric 80139d628a0SDimitry Andric // Try to materialize F. 802d88c1a5aSDimitry Andric if (Error Err = materialize(F)) 803d88c1a5aSDimitry Andric return Err; 80439d628a0SDimitry Andric } 80539d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 80639d628a0SDimitry Andric 80739d628a0SDimitry Andric // Reset state. 80839d628a0SDimitry Andric WillMaterializeAllForwardRefs = false; 809d88c1a5aSDimitry Andric return Error::success(); 810f22ef01cSRoman Divacky } 811f22ef01cSRoman Divacky 812f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 813f22ef01cSRoman Divacky // Helper functions to implement forward reference resolution, etc. 814f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 815f22ef01cSRoman Divacky 816ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) { 817ff0cc061SDimitry Andric switch (Val) { 818ff0cc061SDimitry Andric default: 819ff0cc061SDimitry Andric return false; 820ff0cc061SDimitry Andric case 1: // Old WeakAnyLinkage 821ff0cc061SDimitry Andric case 4: // Old LinkOnceAnyLinkage 822ff0cc061SDimitry Andric case 10: // Old WeakODRLinkage 823ff0cc061SDimitry Andric case 11: // Old LinkOnceODRLinkage 824ff0cc061SDimitry Andric return true; 825ff0cc061SDimitry Andric } 826ff0cc061SDimitry Andric } 827ff0cc061SDimitry Andric 82839d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 829f22ef01cSRoman Divacky switch (Val) { 830f22ef01cSRoman Divacky default: // Map unknown/new linkages to external 83139d628a0SDimitry Andric case 0: 83239d628a0SDimitry Andric return GlobalValue::ExternalLinkage; 83339d628a0SDimitry Andric case 2: 83439d628a0SDimitry Andric return GlobalValue::AppendingLinkage; 83539d628a0SDimitry Andric case 3: 83639d628a0SDimitry Andric return GlobalValue::InternalLinkage; 83739d628a0SDimitry Andric case 5: 83839d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 83939d628a0SDimitry Andric case 6: 84039d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 84139d628a0SDimitry Andric case 7: 84239d628a0SDimitry Andric return GlobalValue::ExternalWeakLinkage; 84339d628a0SDimitry Andric case 8: 84439d628a0SDimitry Andric return GlobalValue::CommonLinkage; 84539d628a0SDimitry Andric case 9: 84639d628a0SDimitry Andric return GlobalValue::PrivateLinkage; 84739d628a0SDimitry Andric case 12: 84839d628a0SDimitry Andric return GlobalValue::AvailableExternallyLinkage; 84991bc56edSDimitry Andric case 13: 85091bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 85191bc56edSDimitry Andric case 14: 85291bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 85339d628a0SDimitry Andric case 15: 85439d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 855ff0cc061SDimitry Andric case 1: // Old value with implicit comdat. 856ff0cc061SDimitry Andric case 16: 857ff0cc061SDimitry Andric return GlobalValue::WeakAnyLinkage; 858ff0cc061SDimitry Andric case 10: // Old value with implicit comdat. 859ff0cc061SDimitry Andric case 17: 860ff0cc061SDimitry Andric return GlobalValue::WeakODRLinkage; 861ff0cc061SDimitry Andric case 4: // Old value with implicit comdat. 862ff0cc061SDimitry Andric case 18: 863ff0cc061SDimitry Andric return GlobalValue::LinkOnceAnyLinkage; 864ff0cc061SDimitry Andric case 11: // Old value with implicit comdat. 865ff0cc061SDimitry Andric case 19: 866ff0cc061SDimitry Andric return GlobalValue::LinkOnceODRLinkage; 867f22ef01cSRoman Divacky } 868f22ef01cSRoman Divacky } 869f22ef01cSRoman Divacky 8702cab237bSDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { 8712cab237bSDimitry Andric FunctionSummary::FFlags Flags; 8722cab237bSDimitry Andric Flags.ReadNone = RawFlags & 0x1; 8732cab237bSDimitry Andric Flags.ReadOnly = (RawFlags >> 1) & 0x1; 8742cab237bSDimitry Andric Flags.NoRecurse = (RawFlags >> 2) & 0x1; 8752cab237bSDimitry Andric Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; 8762cab237bSDimitry Andric return Flags; 8772cab237bSDimitry Andric } 8782cab237bSDimitry Andric 879d88c1a5aSDimitry Andric /// Decode the flags for GlobalValue in the summary. 8803ca95b02SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 8813ca95b02SDimitry Andric uint64_t Version) { 8823ca95b02SDimitry Andric // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 8833ca95b02SDimitry Andric // like getDecodedLinkage() above. Any future change to the linkage enum and 8843ca95b02SDimitry Andric // to getDecodedLinkage() will need to be taken into account here as above. 8853ca95b02SDimitry Andric auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 8863ca95b02SDimitry Andric RawFlags = RawFlags >> 4; 88795ec533aSDimitry Andric bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; 8886d97bb29SDimitry Andric // The Live flag wasn't introduced until version 3. For dead stripping 88995ec533aSDimitry Andric // to work correctly on earlier versions, we must conservatively treat all 89095ec533aSDimitry Andric // values as live. 8916d97bb29SDimitry Andric bool Live = (RawFlags & 0x2) || Version < 3; 8922cab237bSDimitry Andric bool Local = (RawFlags & 0x4); 8932cab237bSDimitry Andric 8942cab237bSDimitry Andric return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local); 8953ca95b02SDimitry Andric } 8963ca95b02SDimitry Andric 8978f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 898f22ef01cSRoman Divacky switch (Val) { 899f22ef01cSRoman Divacky default: // Map unknown visibilities to default. 900f22ef01cSRoman Divacky case 0: return GlobalValue::DefaultVisibility; 901f22ef01cSRoman Divacky case 1: return GlobalValue::HiddenVisibility; 902f22ef01cSRoman Divacky case 2: return GlobalValue::ProtectedVisibility; 903f22ef01cSRoman Divacky } 904f22ef01cSRoman Divacky } 905f22ef01cSRoman Divacky 90691bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes 9078f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) { 90891bc56edSDimitry Andric switch (Val) { 90991bc56edSDimitry Andric default: // Map unknown values to default. 91091bc56edSDimitry Andric case 0: return GlobalValue::DefaultStorageClass; 91191bc56edSDimitry Andric case 1: return GlobalValue::DLLImportStorageClass; 91291bc56edSDimitry Andric case 2: return GlobalValue::DLLExportStorageClass; 91391bc56edSDimitry Andric } 91491bc56edSDimitry Andric } 91591bc56edSDimitry Andric 9162cab237bSDimitry Andric static bool getDecodedDSOLocal(unsigned Val) { 9172cab237bSDimitry Andric switch(Val) { 9182cab237bSDimitry Andric default: // Map unknown values to preemptable. 9192cab237bSDimitry Andric case 0: return false; 9202cab237bSDimitry Andric case 1: return true; 9212cab237bSDimitry Andric } 9222cab237bSDimitry Andric } 9232cab237bSDimitry Andric 9248f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 9257ae0e2c9SDimitry Andric switch (Val) { 9267ae0e2c9SDimitry Andric case 0: return GlobalVariable::NotThreadLocal; 9277ae0e2c9SDimitry Andric default: // Map unknown non-zero value to general dynamic. 9287ae0e2c9SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel; 9297ae0e2c9SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel; 9307ae0e2c9SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel; 9317ae0e2c9SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel; 9327ae0e2c9SDimitry Andric } 9337ae0e2c9SDimitry Andric } 9347ae0e2c9SDimitry Andric 9353ca95b02SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 9363ca95b02SDimitry Andric switch (Val) { 9373ca95b02SDimitry Andric default: // Map unknown to UnnamedAddr::None. 9383ca95b02SDimitry Andric case 0: return GlobalVariable::UnnamedAddr::None; 9393ca95b02SDimitry Andric case 1: return GlobalVariable::UnnamedAddr::Global; 9403ca95b02SDimitry Andric case 2: return GlobalVariable::UnnamedAddr::Local; 9413ca95b02SDimitry Andric } 9423ca95b02SDimitry Andric } 9433ca95b02SDimitry Andric 9448f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) { 945f22ef01cSRoman Divacky switch (Val) { 946f22ef01cSRoman Divacky default: return -1; 947f22ef01cSRoman Divacky case bitc::CAST_TRUNC : return Instruction::Trunc; 948f22ef01cSRoman Divacky case bitc::CAST_ZEXT : return Instruction::ZExt; 949f22ef01cSRoman Divacky case bitc::CAST_SEXT : return Instruction::SExt; 950f22ef01cSRoman Divacky case bitc::CAST_FPTOUI : return Instruction::FPToUI; 951f22ef01cSRoman Divacky case bitc::CAST_FPTOSI : return Instruction::FPToSI; 952f22ef01cSRoman Divacky case bitc::CAST_UITOFP : return Instruction::UIToFP; 953f22ef01cSRoman Divacky case bitc::CAST_SITOFP : return Instruction::SIToFP; 954f22ef01cSRoman Divacky case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 955f22ef01cSRoman Divacky case bitc::CAST_FPEXT : return Instruction::FPExt; 956f22ef01cSRoman Divacky case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 957f22ef01cSRoman Divacky case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 958f22ef01cSRoman Divacky case bitc::CAST_BITCAST : return Instruction::BitCast; 959f785676fSDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 960f22ef01cSRoman Divacky } 961f22ef01cSRoman Divacky } 962ff0cc061SDimitry Andric 9638f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 964ff0cc061SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 965ff0cc061SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types 966ff0cc061SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 967ff0cc061SDimitry Andric return -1; 968ff0cc061SDimitry Andric 969f22ef01cSRoman Divacky switch (Val) { 970ff0cc061SDimitry Andric default: 971ff0cc061SDimitry Andric return -1; 972f22ef01cSRoman Divacky case bitc::BINOP_ADD: 973ff0cc061SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add; 974f22ef01cSRoman Divacky case bitc::BINOP_SUB: 975ff0cc061SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub; 976f22ef01cSRoman Divacky case bitc::BINOP_MUL: 977ff0cc061SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul; 978ff0cc061SDimitry Andric case bitc::BINOP_UDIV: 979ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::UDiv; 980f22ef01cSRoman Divacky case bitc::BINOP_SDIV: 981ff0cc061SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv; 982ff0cc061SDimitry Andric case bitc::BINOP_UREM: 983ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::URem; 984f22ef01cSRoman Divacky case bitc::BINOP_SREM: 985ff0cc061SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem; 986ff0cc061SDimitry Andric case bitc::BINOP_SHL: 987ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Shl; 988ff0cc061SDimitry Andric case bitc::BINOP_LSHR: 989ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::LShr; 990ff0cc061SDimitry Andric case bitc::BINOP_ASHR: 991ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::AShr; 992ff0cc061SDimitry Andric case bitc::BINOP_AND: 993ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::And; 994ff0cc061SDimitry Andric case bitc::BINOP_OR: 995ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Or; 996ff0cc061SDimitry Andric case bitc::BINOP_XOR: 997ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Xor; 998f22ef01cSRoman Divacky } 999f22ef01cSRoman Divacky } 1000f22ef01cSRoman Divacky 10018f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 10026122f3e6SDimitry Andric switch (Val) { 10036122f3e6SDimitry Andric default: return AtomicRMWInst::BAD_BINOP; 10046122f3e6SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 10056122f3e6SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add; 10066122f3e6SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub; 10076122f3e6SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And; 10086122f3e6SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand; 10096122f3e6SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or; 10106122f3e6SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor; 10116122f3e6SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max; 10126122f3e6SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min; 10136122f3e6SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 10146122f3e6SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 10156122f3e6SDimitry Andric } 10166122f3e6SDimitry Andric } 10176122f3e6SDimitry Andric 10188f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) { 10196122f3e6SDimitry Andric switch (Val) { 10203ca95b02SDimitry Andric case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 10213ca95b02SDimitry Andric case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 10223ca95b02SDimitry Andric case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 10233ca95b02SDimitry Andric case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 10243ca95b02SDimitry Andric case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 10253ca95b02SDimitry Andric case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 10266122f3e6SDimitry Andric default: // Map unknown orderings to sequentially-consistent. 10273ca95b02SDimitry Andric case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 10286122f3e6SDimitry Andric } 10296122f3e6SDimitry Andric } 10306122f3e6SDimitry Andric 103191bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 103291bc56edSDimitry Andric switch (Val) { 103391bc56edSDimitry Andric default: // Map unknown selection kinds to any. 103491bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY: 103591bc56edSDimitry Andric return Comdat::Any; 103691bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 103791bc56edSDimitry Andric return Comdat::ExactMatch; 103891bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST: 103991bc56edSDimitry Andric return Comdat::Largest; 104091bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 104191bc56edSDimitry Andric return Comdat::NoDuplicates; 104291bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 104391bc56edSDimitry Andric return Comdat::SameSize; 104491bc56edSDimitry Andric } 104591bc56edSDimitry Andric } 104691bc56edSDimitry Andric 1047875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 1048875ed548SDimitry Andric FastMathFlags FMF; 10492cab237bSDimitry Andric if (0 != (Val & FastMathFlags::AllowReassoc)) 10502cab237bSDimitry Andric FMF.setAllowReassoc(); 1051875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoNaNs)) 1052875ed548SDimitry Andric FMF.setNoNaNs(); 1053875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoInfs)) 1054875ed548SDimitry Andric FMF.setNoInfs(); 1055875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoSignedZeros)) 1056875ed548SDimitry Andric FMF.setNoSignedZeros(); 1057875ed548SDimitry Andric if (0 != (Val & FastMathFlags::AllowReciprocal)) 1058875ed548SDimitry Andric FMF.setAllowReciprocal(); 10597a7e6055SDimitry Andric if (0 != (Val & FastMathFlags::AllowContract)) 10607a7e6055SDimitry Andric FMF.setAllowContract(true); 10612cab237bSDimitry Andric if (0 != (Val & FastMathFlags::ApproxFunc)) 10622cab237bSDimitry Andric FMF.setApproxFunc(); 1063875ed548SDimitry Andric return FMF; 1064875ed548SDimitry Andric } 1065875ed548SDimitry Andric 1066d88c1a5aSDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 106791bc56edSDimitry Andric switch (Val) { 106891bc56edSDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 106991bc56edSDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 107091bc56edSDimitry Andric } 107191bc56edSDimitry Andric } 107291bc56edSDimitry Andric 107317a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) { 107417a519f9SDimitry Andric // The type table size is always specified correctly. 107517a519f9SDimitry Andric if (ID >= TypeList.size()) 107691bc56edSDimitry Andric return nullptr; 1077f22ef01cSRoman Divacky 107817a519f9SDimitry Andric if (Type *Ty = TypeList[ID]) 107917a519f9SDimitry Andric return Ty; 108017a519f9SDimitry Andric 108117a519f9SDimitry Andric // If we have a forward reference, the only possible case is when it is to a 108217a519f9SDimitry Andric // named struct. Just create a placeholder for now. 108339d628a0SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context); 108439d628a0SDimitry Andric } 108539d628a0SDimitry Andric 108639d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 108739d628a0SDimitry Andric StringRef Name) { 108839d628a0SDimitry Andric auto *Ret = StructType::create(Context, Name); 108939d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 109039d628a0SDimitry Andric return Ret; 109139d628a0SDimitry Andric } 109239d628a0SDimitry Andric 109339d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 109439d628a0SDimitry Andric auto *Ret = StructType::create(Context); 109539d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 109639d628a0SDimitry Andric return Ret; 1097f22ef01cSRoman Divacky } 1098f22ef01cSRoman Divacky 1099f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1100f22ef01cSRoman Divacky // Functions for parsing blocks from the bitcode file 1101f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1102f22ef01cSRoman Divacky 1103d88c1a5aSDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 1104d88c1a5aSDimitry Andric switch (Val) { 1105d88c1a5aSDimitry Andric case Attribute::EndAttrKinds: 1106d88c1a5aSDimitry Andric llvm_unreachable("Synthetic enumerators which should never get here"); 1107d88c1a5aSDimitry Andric 1108d88c1a5aSDimitry Andric case Attribute::None: return 0; 1109d88c1a5aSDimitry Andric case Attribute::ZExt: return 1 << 0; 1110d88c1a5aSDimitry Andric case Attribute::SExt: return 1 << 1; 1111d88c1a5aSDimitry Andric case Attribute::NoReturn: return 1 << 2; 1112d88c1a5aSDimitry Andric case Attribute::InReg: return 1 << 3; 1113d88c1a5aSDimitry Andric case Attribute::StructRet: return 1 << 4; 1114d88c1a5aSDimitry Andric case Attribute::NoUnwind: return 1 << 5; 1115d88c1a5aSDimitry Andric case Attribute::NoAlias: return 1 << 6; 1116d88c1a5aSDimitry Andric case Attribute::ByVal: return 1 << 7; 1117d88c1a5aSDimitry Andric case Attribute::Nest: return 1 << 8; 1118d88c1a5aSDimitry Andric case Attribute::ReadNone: return 1 << 9; 1119d88c1a5aSDimitry Andric case Attribute::ReadOnly: return 1 << 10; 1120d88c1a5aSDimitry Andric case Attribute::NoInline: return 1 << 11; 1121d88c1a5aSDimitry Andric case Attribute::AlwaysInline: return 1 << 12; 1122d88c1a5aSDimitry Andric case Attribute::OptimizeForSize: return 1 << 13; 1123d88c1a5aSDimitry Andric case Attribute::StackProtect: return 1 << 14; 1124d88c1a5aSDimitry Andric case Attribute::StackProtectReq: return 1 << 15; 1125d88c1a5aSDimitry Andric case Attribute::Alignment: return 31 << 16; 1126d88c1a5aSDimitry Andric case Attribute::NoCapture: return 1 << 21; 1127d88c1a5aSDimitry Andric case Attribute::NoRedZone: return 1 << 22; 1128d88c1a5aSDimitry Andric case Attribute::NoImplicitFloat: return 1 << 23; 1129d88c1a5aSDimitry Andric case Attribute::Naked: return 1 << 24; 1130d88c1a5aSDimitry Andric case Attribute::InlineHint: return 1 << 25; 1131d88c1a5aSDimitry Andric case Attribute::StackAlignment: return 7 << 26; 1132d88c1a5aSDimitry Andric case Attribute::ReturnsTwice: return 1 << 29; 1133d88c1a5aSDimitry Andric case Attribute::UWTable: return 1 << 30; 1134d88c1a5aSDimitry Andric case Attribute::NonLazyBind: return 1U << 31; 1135d88c1a5aSDimitry Andric case Attribute::SanitizeAddress: return 1ULL << 32; 1136d88c1a5aSDimitry Andric case Attribute::MinSize: return 1ULL << 33; 1137d88c1a5aSDimitry Andric case Attribute::NoDuplicate: return 1ULL << 34; 1138d88c1a5aSDimitry Andric case Attribute::StackProtectStrong: return 1ULL << 35; 1139d88c1a5aSDimitry Andric case Attribute::SanitizeThread: return 1ULL << 36; 1140d88c1a5aSDimitry Andric case Attribute::SanitizeMemory: return 1ULL << 37; 1141d88c1a5aSDimitry Andric case Attribute::NoBuiltin: return 1ULL << 38; 1142d88c1a5aSDimitry Andric case Attribute::Returned: return 1ULL << 39; 1143d88c1a5aSDimitry Andric case Attribute::Cold: return 1ULL << 40; 1144d88c1a5aSDimitry Andric case Attribute::Builtin: return 1ULL << 41; 1145d88c1a5aSDimitry Andric case Attribute::OptimizeNone: return 1ULL << 42; 1146d88c1a5aSDimitry Andric case Attribute::InAlloca: return 1ULL << 43; 1147d88c1a5aSDimitry Andric case Attribute::NonNull: return 1ULL << 44; 1148d88c1a5aSDimitry Andric case Attribute::JumpTable: return 1ULL << 45; 1149d88c1a5aSDimitry Andric case Attribute::Convergent: return 1ULL << 46; 1150d88c1a5aSDimitry Andric case Attribute::SafeStack: return 1ULL << 47; 1151d88c1a5aSDimitry Andric case Attribute::NoRecurse: return 1ULL << 48; 1152d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOnly: return 1ULL << 49; 1153d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; 1154d88c1a5aSDimitry Andric case Attribute::SwiftSelf: return 1ULL << 51; 1155d88c1a5aSDimitry Andric case Attribute::SwiftError: return 1ULL << 52; 1156d88c1a5aSDimitry Andric case Attribute::WriteOnly: return 1ULL << 53; 1157f37b6182SDimitry Andric case Attribute::Speculatable: return 1ULL << 54; 11582cab237bSDimitry Andric case Attribute::StrictFP: return 1ULL << 55; 11592cab237bSDimitry Andric case Attribute::SanitizeHWAddress: return 1ULL << 56; 1160d88c1a5aSDimitry Andric case Attribute::Dereferenceable: 1161d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable attribute not supported in raw format"); 1162d88c1a5aSDimitry Andric break; 1163d88c1a5aSDimitry Andric case Attribute::DereferenceableOrNull: 1164d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable_or_null attribute not supported in raw " 1165d88c1a5aSDimitry Andric "format"); 1166d88c1a5aSDimitry Andric break; 1167d88c1a5aSDimitry Andric case Attribute::ArgMemOnly: 1168d88c1a5aSDimitry Andric llvm_unreachable("argmemonly attribute not supported in raw format"); 1169d88c1a5aSDimitry Andric break; 1170d88c1a5aSDimitry Andric case Attribute::AllocSize: 1171d88c1a5aSDimitry Andric llvm_unreachable("allocsize not supported in raw format"); 1172d88c1a5aSDimitry Andric break; 1173d88c1a5aSDimitry Andric } 1174d88c1a5aSDimitry Andric llvm_unreachable("Unsupported attribute type"); 1175d88c1a5aSDimitry Andric } 1176d88c1a5aSDimitry Andric 1177d88c1a5aSDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 1178d88c1a5aSDimitry Andric if (!Val) return; 1179d88c1a5aSDimitry Andric 1180d88c1a5aSDimitry Andric for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 1181d88c1a5aSDimitry Andric I = Attribute::AttrKind(I + 1)) { 1182d88c1a5aSDimitry Andric if (I == Attribute::Dereferenceable || 1183d88c1a5aSDimitry Andric I == Attribute::DereferenceableOrNull || 1184d88c1a5aSDimitry Andric I == Attribute::ArgMemOnly || 1185d88c1a5aSDimitry Andric I == Attribute::AllocSize) 1186d88c1a5aSDimitry Andric continue; 1187d88c1a5aSDimitry Andric if (uint64_t A = (Val & getRawAttributeMask(I))) { 1188d88c1a5aSDimitry Andric if (I == Attribute::Alignment) 1189d88c1a5aSDimitry Andric B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 1190d88c1a5aSDimitry Andric else if (I == Attribute::StackAlignment) 1191d88c1a5aSDimitry Andric B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1192d88c1a5aSDimitry Andric else 1193d88c1a5aSDimitry Andric B.addAttribute(I); 1194d88c1a5aSDimitry Andric } 1195d88c1a5aSDimitry Andric } 1196d88c1a5aSDimitry Andric } 1197139f7f9bSDimitry Andric 1198139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1199139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with 1200139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'. 1201139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1202139f7f9bSDimitry Andric uint64_t EncodedAttrs) { 1203139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1204139f7f9bSDimitry Andric 1205139f7f9bSDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1206139f7f9bSDimitry Andric // the bits above 31 down by 11 bits. 1207139f7f9bSDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1208139f7f9bSDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) && 1209139f7f9bSDimitry Andric "Alignment must be a power of two."); 1210139f7f9bSDimitry Andric 1211139f7f9bSDimitry Andric if (Alignment) 1212139f7f9bSDimitry Andric B.addAlignmentAttr(Alignment); 1213d88c1a5aSDimitry Andric addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1214139f7f9bSDimitry Andric (EncodedAttrs & 0xffff)); 1215139f7f9bSDimitry Andric } 1216139f7f9bSDimitry Andric 1217d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeBlock() { 1218f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 12198f0fd8f6SDimitry Andric return error("Invalid record"); 1220f22ef01cSRoman Divacky 1221f22ef01cSRoman Divacky if (!MAttributes.empty()) 12228f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1223f22ef01cSRoman Divacky 1224f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1225f22ef01cSRoman Divacky 12267a7e6055SDimitry Andric SmallVector<AttributeList, 8> Attrs; 1227f22ef01cSRoman Divacky 1228f22ef01cSRoman Divacky // Read all the records. 1229d88c1a5aSDimitry Andric while (true) { 1230139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1231139f7f9bSDimitry Andric 1232139f7f9bSDimitry Andric switch (Entry.Kind) { 1233139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1234139f7f9bSDimitry Andric case BitstreamEntry::Error: 12358f0fd8f6SDimitry Andric return error("Malformed block"); 1236139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1237d88c1a5aSDimitry Andric return Error::success(); 1238139f7f9bSDimitry Andric case BitstreamEntry::Record: 1239139f7f9bSDimitry Andric // The interesting case. 1240139f7f9bSDimitry Andric break; 1241f22ef01cSRoman Divacky } 1242f22ef01cSRoman Divacky 1243f22ef01cSRoman Divacky // Read a record. 1244f22ef01cSRoman Divacky Record.clear(); 1245139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1246f22ef01cSRoman Divacky default: // Default behavior: ignore. 1247f22ef01cSRoman Divacky break; 12482cab237bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] 1249139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1250f22ef01cSRoman Divacky if (Record.size() & 1) 12518f0fd8f6SDimitry Andric return error("Invalid record"); 1252f22ef01cSRoman Divacky 1253f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1254139f7f9bSDimitry Andric AttrBuilder B; 1255139f7f9bSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1]); 12567a7e6055SDimitry Andric Attrs.push_back(AttributeList::get(Context, Record[i], B)); 1257f22ef01cSRoman Divacky } 1258f22ef01cSRoman Divacky 12597a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 1260f22ef01cSRoman Divacky Attrs.clear(); 1261f22ef01cSRoman Divacky break; 12622cab237bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] 1263139f7f9bSDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i) 1264139f7f9bSDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]); 1265139f7f9bSDimitry Andric 12667a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs)); 1267139f7f9bSDimitry Andric Attrs.clear(); 1268139f7f9bSDimitry Andric break; 1269139f7f9bSDimitry Andric } 1270139f7f9bSDimitry Andric } 1271139f7f9bSDimitry Andric } 1272139f7f9bSDimitry Andric 1273f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes. 12748f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1275f785676fSDimitry Andric switch (Code) { 1276f785676fSDimitry Andric default: 1277f785676fSDimitry Andric return Attribute::None; 1278f785676fSDimitry Andric case bitc::ATTR_KIND_ALIGNMENT: 1279f785676fSDimitry Andric return Attribute::Alignment; 1280f785676fSDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE: 1281f785676fSDimitry Andric return Attribute::AlwaysInline; 1282875ed548SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY: 1283875ed548SDimitry Andric return Attribute::ArgMemOnly; 1284f785676fSDimitry Andric case bitc::ATTR_KIND_BUILTIN: 1285f785676fSDimitry Andric return Attribute::Builtin; 1286f785676fSDimitry Andric case bitc::ATTR_KIND_BY_VAL: 1287f785676fSDimitry Andric return Attribute::ByVal; 128891bc56edSDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA: 128991bc56edSDimitry Andric return Attribute::InAlloca; 1290f785676fSDimitry Andric case bitc::ATTR_KIND_COLD: 1291f785676fSDimitry Andric return Attribute::Cold; 1292ff0cc061SDimitry Andric case bitc::ATTR_KIND_CONVERGENT: 1293ff0cc061SDimitry Andric return Attribute::Convergent; 12947d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 12957d523365SDimitry Andric return Attribute::InaccessibleMemOnly; 12967d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 12977d523365SDimitry Andric return Attribute::InaccessibleMemOrArgMemOnly; 1298f785676fSDimitry Andric case bitc::ATTR_KIND_INLINE_HINT: 1299f785676fSDimitry Andric return Attribute::InlineHint; 1300f785676fSDimitry Andric case bitc::ATTR_KIND_IN_REG: 1301f785676fSDimitry Andric return Attribute::InReg; 130291bc56edSDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE: 130391bc56edSDimitry Andric return Attribute::JumpTable; 1304f785676fSDimitry Andric case bitc::ATTR_KIND_MIN_SIZE: 1305f785676fSDimitry Andric return Attribute::MinSize; 1306f785676fSDimitry Andric case bitc::ATTR_KIND_NAKED: 1307f785676fSDimitry Andric return Attribute::Naked; 1308f785676fSDimitry Andric case bitc::ATTR_KIND_NEST: 1309f785676fSDimitry Andric return Attribute::Nest; 1310f785676fSDimitry Andric case bitc::ATTR_KIND_NO_ALIAS: 1311f785676fSDimitry Andric return Attribute::NoAlias; 1312f785676fSDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN: 1313f785676fSDimitry Andric return Attribute::NoBuiltin; 1314f785676fSDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE: 1315f785676fSDimitry Andric return Attribute::NoCapture; 1316f785676fSDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE: 1317f785676fSDimitry Andric return Attribute::NoDuplicate; 1318f785676fSDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1319f785676fSDimitry Andric return Attribute::NoImplicitFloat; 1320f785676fSDimitry Andric case bitc::ATTR_KIND_NO_INLINE: 1321f785676fSDimitry Andric return Attribute::NoInline; 13227d523365SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE: 13237d523365SDimitry Andric return Attribute::NoRecurse; 1324f785676fSDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND: 1325f785676fSDimitry Andric return Attribute::NonLazyBind; 132691bc56edSDimitry Andric case bitc::ATTR_KIND_NON_NULL: 132791bc56edSDimitry Andric return Attribute::NonNull; 132891bc56edSDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE: 132991bc56edSDimitry Andric return Attribute::Dereferenceable; 1330ff0cc061SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1331ff0cc061SDimitry Andric return Attribute::DereferenceableOrNull; 13323ca95b02SDimitry Andric case bitc::ATTR_KIND_ALLOC_SIZE: 13333ca95b02SDimitry Andric return Attribute::AllocSize; 1334f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE: 1335f785676fSDimitry Andric return Attribute::NoRedZone; 1336f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RETURN: 1337f785676fSDimitry Andric return Attribute::NoReturn; 1338f785676fSDimitry Andric case bitc::ATTR_KIND_NO_UNWIND: 1339f785676fSDimitry Andric return Attribute::NoUnwind; 1340f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1341f785676fSDimitry Andric return Attribute::OptimizeForSize; 1342f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE: 1343f785676fSDimitry Andric return Attribute::OptimizeNone; 1344f785676fSDimitry Andric case bitc::ATTR_KIND_READ_NONE: 1345f785676fSDimitry Andric return Attribute::ReadNone; 1346f785676fSDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 1347f785676fSDimitry Andric return Attribute::ReadOnly; 1348f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNED: 1349f785676fSDimitry Andric return Attribute::Returned; 1350f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE: 1351f785676fSDimitry Andric return Attribute::ReturnsTwice; 1352f785676fSDimitry Andric case bitc::ATTR_KIND_S_EXT: 1353f785676fSDimitry Andric return Attribute::SExt; 1354f37b6182SDimitry Andric case bitc::ATTR_KIND_SPECULATABLE: 1355f37b6182SDimitry Andric return Attribute::Speculatable; 1356f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT: 1357f785676fSDimitry Andric return Attribute::StackAlignment; 1358f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT: 1359f785676fSDimitry Andric return Attribute::StackProtect; 1360f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1361f785676fSDimitry Andric return Attribute::StackProtectReq; 1362f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1363f785676fSDimitry Andric return Attribute::StackProtectStrong; 13648f0fd8f6SDimitry Andric case bitc::ATTR_KIND_SAFESTACK: 13658f0fd8f6SDimitry Andric return Attribute::SafeStack; 13662cab237bSDimitry Andric case bitc::ATTR_KIND_STRICT_FP: 13672cab237bSDimitry Andric return Attribute::StrictFP; 1368f785676fSDimitry Andric case bitc::ATTR_KIND_STRUCT_RET: 1369f785676fSDimitry Andric return Attribute::StructRet; 1370f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1371f785676fSDimitry Andric return Attribute::SanitizeAddress; 13722cab237bSDimitry Andric case bitc::ATTR_KIND_SANITIZE_HWADDRESS: 13732cab237bSDimitry Andric return Attribute::SanitizeHWAddress; 1374f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD: 1375f785676fSDimitry Andric return Attribute::SanitizeThread; 1376f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY: 1377f785676fSDimitry Andric return Attribute::SanitizeMemory; 13783ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_ERROR: 13793ca95b02SDimitry Andric return Attribute::SwiftError; 13803ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_SELF: 13813ca95b02SDimitry Andric return Attribute::SwiftSelf; 1382f785676fSDimitry Andric case bitc::ATTR_KIND_UW_TABLE: 1383f785676fSDimitry Andric return Attribute::UWTable; 13843ca95b02SDimitry Andric case bitc::ATTR_KIND_WRITEONLY: 13853ca95b02SDimitry Andric return Attribute::WriteOnly; 1386f785676fSDimitry Andric case bitc::ATTR_KIND_Z_EXT: 1387f785676fSDimitry Andric return Attribute::ZExt; 1388f785676fSDimitry Andric } 1389f785676fSDimitry Andric } 1390f785676fSDimitry Andric 1391d88c1a5aSDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1392ff0cc061SDimitry Andric unsigned &Alignment) { 1393ff0cc061SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero 1394ff0cc061SDimitry Andric // can be used for default alignment. 1395ff0cc061SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1) 13968f0fd8f6SDimitry Andric return error("Invalid alignment value"); 1397ff0cc061SDimitry Andric Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1398d88c1a5aSDimitry Andric return Error::success(); 1399ff0cc061SDimitry Andric } 1400ff0cc061SDimitry Andric 1401d88c1a5aSDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 14028f0fd8f6SDimitry Andric *Kind = getAttrFromCode(Code); 1403f785676fSDimitry Andric if (*Kind == Attribute::None) 1404d88c1a5aSDimitry Andric return error("Unknown attribute kind (" + Twine(Code) + ")"); 1405d88c1a5aSDimitry Andric return Error::success(); 1406f785676fSDimitry Andric } 1407f785676fSDimitry Andric 1408d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() { 1409139f7f9bSDimitry Andric if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 14108f0fd8f6SDimitry Andric return error("Invalid record"); 1411139f7f9bSDimitry Andric 1412139f7f9bSDimitry Andric if (!MAttributeGroups.empty()) 14138f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1414139f7f9bSDimitry Andric 1415139f7f9bSDimitry Andric SmallVector<uint64_t, 64> Record; 1416139f7f9bSDimitry Andric 1417139f7f9bSDimitry Andric // Read all the records. 1418d88c1a5aSDimitry Andric while (true) { 1419139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1420139f7f9bSDimitry Andric 1421139f7f9bSDimitry Andric switch (Entry.Kind) { 1422139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1423139f7f9bSDimitry Andric case BitstreamEntry::Error: 14248f0fd8f6SDimitry Andric return error("Malformed block"); 1425139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1426d88c1a5aSDimitry Andric return Error::success(); 1427139f7f9bSDimitry Andric case BitstreamEntry::Record: 1428139f7f9bSDimitry Andric // The interesting case. 1429139f7f9bSDimitry Andric break; 1430139f7f9bSDimitry Andric } 1431139f7f9bSDimitry Andric 1432139f7f9bSDimitry Andric // Read a record. 1433139f7f9bSDimitry Andric Record.clear(); 1434139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1435139f7f9bSDimitry Andric default: // Default behavior: ignore. 1436139f7f9bSDimitry Andric break; 1437139f7f9bSDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1438139f7f9bSDimitry Andric if (Record.size() < 3) 14398f0fd8f6SDimitry Andric return error("Invalid record"); 1440139f7f9bSDimitry Andric 1441139f7f9bSDimitry Andric uint64_t GrpID = Record[0]; 1442139f7f9bSDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1443139f7f9bSDimitry Andric 1444139f7f9bSDimitry Andric AttrBuilder B; 1445139f7f9bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1446139f7f9bSDimitry Andric if (Record[i] == 0) { // Enum attribute 1447f785676fSDimitry Andric Attribute::AttrKind Kind; 1448d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 1449d88c1a5aSDimitry Andric return Err; 1450f785676fSDimitry Andric 1451f785676fSDimitry Andric B.addAttribute(Kind); 145291bc56edSDimitry Andric } else if (Record[i] == 1) { // Integer attribute 1453f785676fSDimitry Andric Attribute::AttrKind Kind; 1454d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind)) 1455d88c1a5aSDimitry Andric return Err; 1456f785676fSDimitry Andric if (Kind == Attribute::Alignment) 1457139f7f9bSDimitry Andric B.addAlignmentAttr(Record[++i]); 145891bc56edSDimitry Andric else if (Kind == Attribute::StackAlignment) 1459139f7f9bSDimitry Andric B.addStackAlignmentAttr(Record[++i]); 146091bc56edSDimitry Andric else if (Kind == Attribute::Dereferenceable) 146191bc56edSDimitry Andric B.addDereferenceableAttr(Record[++i]); 1462ff0cc061SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull) 1463ff0cc061SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]); 14643ca95b02SDimitry Andric else if (Kind == Attribute::AllocSize) 14653ca95b02SDimitry Andric B.addAllocSizeAttrFromRawRepr(Record[++i]); 1466139f7f9bSDimitry Andric } else { // String attribute 1467139f7f9bSDimitry Andric assert((Record[i] == 3 || Record[i] == 4) && 1468139f7f9bSDimitry Andric "Invalid attribute group entry"); 1469139f7f9bSDimitry Andric bool HasValue = (Record[i++] == 4); 1470139f7f9bSDimitry Andric SmallString<64> KindStr; 1471139f7f9bSDimitry Andric SmallString<64> ValStr; 1472139f7f9bSDimitry Andric 1473139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1474139f7f9bSDimitry Andric KindStr += Record[i++]; 1475139f7f9bSDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated"); 1476139f7f9bSDimitry Andric 1477139f7f9bSDimitry Andric if (HasValue) { 1478139f7f9bSDimitry Andric // Has a value associated with it. 1479139f7f9bSDimitry Andric ++i; // Skip the '0' that terminates the "kind" string. 1480139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1481139f7f9bSDimitry Andric ValStr += Record[i++]; 1482139f7f9bSDimitry Andric assert(Record[i] == 0 && "Value string not null terminated"); 1483139f7f9bSDimitry Andric } 1484139f7f9bSDimitry Andric 1485139f7f9bSDimitry Andric B.addAttribute(KindStr.str(), ValStr.str()); 1486139f7f9bSDimitry Andric } 1487139f7f9bSDimitry Andric } 1488139f7f9bSDimitry Andric 14897a7e6055SDimitry Andric MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); 1490139f7f9bSDimitry Andric break; 1491139f7f9bSDimitry Andric } 1492f22ef01cSRoman Divacky } 1493f22ef01cSRoman Divacky } 1494f22ef01cSRoman Divacky } 1495f22ef01cSRoman Divacky 1496d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTable() { 149717a519f9SDimitry Andric if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 14988f0fd8f6SDimitry Andric return error("Invalid record"); 1499f22ef01cSRoman Divacky 15008f0fd8f6SDimitry Andric return parseTypeTableBody(); 150117a519f9SDimitry Andric } 150217a519f9SDimitry Andric 1503d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTableBody() { 1504f22ef01cSRoman Divacky if (!TypeList.empty()) 15058f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1506f22ef01cSRoman Divacky 1507f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1508f22ef01cSRoman Divacky unsigned NumRecords = 0; 1509f22ef01cSRoman Divacky 151017a519f9SDimitry Andric SmallString<64> TypeName; 151117a519f9SDimitry Andric 1512f22ef01cSRoman Divacky // Read all the records for this type table. 1513d88c1a5aSDimitry Andric while (true) { 1514139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1515139f7f9bSDimitry Andric 1516139f7f9bSDimitry Andric switch (Entry.Kind) { 1517139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1518139f7f9bSDimitry Andric case BitstreamEntry::Error: 15198f0fd8f6SDimitry Andric return error("Malformed block"); 1520139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1521f22ef01cSRoman Divacky if (NumRecords != TypeList.size()) 15228f0fd8f6SDimitry Andric return error("Malformed block"); 1523d88c1a5aSDimitry Andric return Error::success(); 1524139f7f9bSDimitry Andric case BitstreamEntry::Record: 1525139f7f9bSDimitry Andric // The interesting case. 1526139f7f9bSDimitry Andric break; 1527f22ef01cSRoman Divacky } 1528f22ef01cSRoman Divacky 1529f22ef01cSRoman Divacky // Read a record. 1530f22ef01cSRoman Divacky Record.clear(); 153191bc56edSDimitry Andric Type *ResultTy = nullptr; 1532139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1533f785676fSDimitry Andric default: 15348f0fd8f6SDimitry Andric return error("Invalid value"); 1535f22ef01cSRoman Divacky case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1536f22ef01cSRoman Divacky // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1537f22ef01cSRoman Divacky // type list. This allows us to reserve space. 1538f22ef01cSRoman Divacky if (Record.size() < 1) 15398f0fd8f6SDimitry Andric return error("Invalid record"); 154017a519f9SDimitry Andric TypeList.resize(Record[0]); 1541f22ef01cSRoman Divacky continue; 1542f22ef01cSRoman Divacky case bitc::TYPE_CODE_VOID: // VOID 1543f22ef01cSRoman Divacky ResultTy = Type::getVoidTy(Context); 1544f22ef01cSRoman Divacky break; 1545dff0c46cSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF 1546dff0c46cSDimitry Andric ResultTy = Type::getHalfTy(Context); 1547dff0c46cSDimitry Andric break; 1548f22ef01cSRoman Divacky case bitc::TYPE_CODE_FLOAT: // FLOAT 1549f22ef01cSRoman Divacky ResultTy = Type::getFloatTy(Context); 1550f22ef01cSRoman Divacky break; 1551f22ef01cSRoman Divacky case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1552f22ef01cSRoman Divacky ResultTy = Type::getDoubleTy(Context); 1553f22ef01cSRoman Divacky break; 1554f22ef01cSRoman Divacky case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1555f22ef01cSRoman Divacky ResultTy = Type::getX86_FP80Ty(Context); 1556f22ef01cSRoman Divacky break; 1557f22ef01cSRoman Divacky case bitc::TYPE_CODE_FP128: // FP128 1558f22ef01cSRoman Divacky ResultTy = Type::getFP128Ty(Context); 1559f22ef01cSRoman Divacky break; 1560f22ef01cSRoman Divacky case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1561f22ef01cSRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context); 1562f22ef01cSRoman Divacky break; 1563f22ef01cSRoman Divacky case bitc::TYPE_CODE_LABEL: // LABEL 1564f22ef01cSRoman Divacky ResultTy = Type::getLabelTy(Context); 1565f22ef01cSRoman Divacky break; 1566f22ef01cSRoman Divacky case bitc::TYPE_CODE_METADATA: // METADATA 1567f22ef01cSRoman Divacky ResultTy = Type::getMetadataTy(Context); 1568f22ef01cSRoman Divacky break; 15692754fe60SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX 15702754fe60SDimitry Andric ResultTy = Type::getX86_MMXTy(Context); 15712754fe60SDimitry Andric break; 15727d523365SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN 15737d523365SDimitry Andric ResultTy = Type::getTokenTy(Context); 15747d523365SDimitry Andric break; 1575ff0cc061SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1576f22ef01cSRoman Divacky if (Record.size() < 1) 15778f0fd8f6SDimitry Andric return error("Invalid record"); 1578f22ef01cSRoman Divacky 1579ff0cc061SDimitry Andric uint64_t NumBits = Record[0]; 1580ff0cc061SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS || 1581ff0cc061SDimitry Andric NumBits > IntegerType::MAX_INT_BITS) 15828f0fd8f6SDimitry Andric return error("Bitwidth for integer type out of range"); 1583ff0cc061SDimitry Andric ResultTy = IntegerType::get(Context, NumBits); 1584f22ef01cSRoman Divacky break; 1585ff0cc061SDimitry Andric } 1586f22ef01cSRoman Divacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1587f22ef01cSRoman Divacky // [pointee type, address space] 1588f22ef01cSRoman Divacky if (Record.size() < 1) 15898f0fd8f6SDimitry Andric return error("Invalid record"); 1590f22ef01cSRoman Divacky unsigned AddressSpace = 0; 1591f22ef01cSRoman Divacky if (Record.size() == 2) 1592f22ef01cSRoman Divacky AddressSpace = Record[1]; 159317a519f9SDimitry Andric ResultTy = getTypeByID(Record[0]); 1594ff0cc061SDimitry Andric if (!ResultTy || 1595ff0cc061SDimitry Andric !PointerType::isValidElementType(ResultTy)) 15968f0fd8f6SDimitry Andric return error("Invalid type"); 159717a519f9SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace); 1598f22ef01cSRoman Divacky break; 1599f22ef01cSRoman Divacky } 1600dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: { 16017ae0e2c9SDimitry Andric // FIXME: attrid is dead, remove it in LLVM 4.0 1602f22ef01cSRoman Divacky // FUNCTION: [vararg, attrid, retty, paramty x N] 1603f22ef01cSRoman Divacky if (Record.size() < 3) 16048f0fd8f6SDimitry Andric return error("Invalid record"); 1605dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 160617a519f9SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) { 160717a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 160817a519f9SDimitry Andric ArgTys.push_back(T); 160917a519f9SDimitry Andric else 1610f22ef01cSRoman Divacky break; 1611f22ef01cSRoman Divacky } 161217a519f9SDimitry Andric 161317a519f9SDimitry Andric ResultTy = getTypeByID(Record[2]); 161491bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3) 16158f0fd8f6SDimitry Andric return error("Invalid type"); 161617a519f9SDimitry Andric 161717a519f9SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 161817a519f9SDimitry Andric break; 161917a519f9SDimitry Andric } 1620dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION: { 1621dff0c46cSDimitry Andric // FUNCTION: [vararg, retty, paramty x N] 1622dff0c46cSDimitry Andric if (Record.size() < 2) 16238f0fd8f6SDimitry Andric return error("Invalid record"); 1624dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 1625dff0c46cSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1626ff0cc061SDimitry Andric if (Type *T = getTypeByID(Record[i])) { 1627ff0cc061SDimitry Andric if (!FunctionType::isValidArgumentType(T)) 16288f0fd8f6SDimitry Andric return error("Invalid function argument type"); 1629dff0c46cSDimitry Andric ArgTys.push_back(T); 1630ff0cc061SDimitry Andric } 1631dff0c46cSDimitry Andric else 1632dff0c46cSDimitry Andric break; 1633dff0c46cSDimitry Andric } 1634dff0c46cSDimitry Andric 1635dff0c46cSDimitry Andric ResultTy = getTypeByID(Record[1]); 163691bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2) 16378f0fd8f6SDimitry Andric return error("Invalid type"); 1638dff0c46cSDimitry Andric 1639dff0c46cSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1640dff0c46cSDimitry Andric break; 1641dff0c46cSDimitry Andric } 164217a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1643f22ef01cSRoman Divacky if (Record.size() < 1) 16448f0fd8f6SDimitry Andric return error("Invalid record"); 1645dff0c46cSDimitry Andric SmallVector<Type*, 8> EltTys; 164617a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 164717a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 164817a519f9SDimitry Andric EltTys.push_back(T); 164917a519f9SDimitry Andric else 165017a519f9SDimitry Andric break; 165117a519f9SDimitry Andric } 165217a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16538f0fd8f6SDimitry Andric return error("Invalid type"); 1654f22ef01cSRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]); 1655f22ef01cSRoman Divacky break; 1656f22ef01cSRoman Divacky } 165717a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 16588f0fd8f6SDimitry Andric if (convertToString(Record, 0, TypeName)) 16598f0fd8f6SDimitry Andric return error("Invalid record"); 166017a519f9SDimitry Andric continue; 166117a519f9SDimitry Andric 166217a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 166317a519f9SDimitry Andric if (Record.size() < 1) 16648f0fd8f6SDimitry Andric return error("Invalid record"); 166517a519f9SDimitry Andric 166617a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16678f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 166817a519f9SDimitry Andric 166917a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 167017a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 167117a519f9SDimitry Andric if (Res) { 167217a519f9SDimitry Andric Res->setName(TypeName); 167391bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 167417a519f9SDimitry Andric } else // Otherwise, create a new struct. 167539d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 167617a519f9SDimitry Andric TypeName.clear(); 167717a519f9SDimitry Andric 167817a519f9SDimitry Andric SmallVector<Type*, 8> EltTys; 167917a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 168017a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 168117a519f9SDimitry Andric EltTys.push_back(T); 168217a519f9SDimitry Andric else 168317a519f9SDimitry Andric break; 168417a519f9SDimitry Andric } 168517a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16868f0fd8f6SDimitry Andric return error("Invalid record"); 168717a519f9SDimitry Andric Res->setBody(EltTys, Record[0]); 168817a519f9SDimitry Andric ResultTy = Res; 168917a519f9SDimitry Andric break; 169017a519f9SDimitry Andric } 169117a519f9SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 169217a519f9SDimitry Andric if (Record.size() != 1) 16938f0fd8f6SDimitry Andric return error("Invalid record"); 169417a519f9SDimitry Andric 169517a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16968f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 169717a519f9SDimitry Andric 169817a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 169917a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 170017a519f9SDimitry Andric if (Res) { 170117a519f9SDimitry Andric Res->setName(TypeName); 170291bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 170317a519f9SDimitry Andric } else // Otherwise, create a new struct with no body. 170439d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 170517a519f9SDimitry Andric TypeName.clear(); 170617a519f9SDimitry Andric ResultTy = Res; 170717a519f9SDimitry Andric break; 170817a519f9SDimitry Andric } 1709f22ef01cSRoman Divacky case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1710f22ef01cSRoman Divacky if (Record.size() < 2) 17118f0fd8f6SDimitry Andric return error("Invalid record"); 1712ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1713ff0cc061SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 17148f0fd8f6SDimitry Andric return error("Invalid type"); 1715ff0cc061SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]); 1716f22ef01cSRoman Divacky break; 1717f22ef01cSRoman Divacky case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1718f22ef01cSRoman Divacky if (Record.size() < 2) 17198f0fd8f6SDimitry Andric return error("Invalid record"); 172097bc6c73SDimitry Andric if (Record[0] == 0) 17218f0fd8f6SDimitry Andric return error("Invalid vector length"); 1722ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1723ff0cc061SDimitry Andric if (!ResultTy || !StructType::isValidElementType(ResultTy)) 17248f0fd8f6SDimitry Andric return error("Invalid type"); 1725ff0cc061SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0]); 1726f22ef01cSRoman Divacky break; 1727f22ef01cSRoman Divacky } 1728f22ef01cSRoman Divacky 172917a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 17308f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 1731ff0cc061SDimitry Andric if (TypeList[NumRecords]) 17328f0fd8f6SDimitry Andric return error( 1733ff0cc061SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced"); 173417a519f9SDimitry Andric assert(ResultTy && "Didn't read a type?"); 173517a519f9SDimitry Andric TypeList[NumRecords++] = ResultTy; 1736f22ef01cSRoman Divacky } 1737f22ef01cSRoman Divacky } 173817a519f9SDimitry Andric 1739d88c1a5aSDimitry Andric Error BitcodeReader::parseOperandBundleTags() { 17407d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 17417d523365SDimitry Andric return error("Invalid record"); 17427d523365SDimitry Andric 17437d523365SDimitry Andric if (!BundleTags.empty()) 17447d523365SDimitry Andric return error("Invalid multiple blocks"); 17457d523365SDimitry Andric 17467d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 17477d523365SDimitry Andric 1748d88c1a5aSDimitry Andric while (true) { 17497d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 17507d523365SDimitry Andric 17517d523365SDimitry Andric switch (Entry.Kind) { 17527d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 17537d523365SDimitry Andric case BitstreamEntry::Error: 17547d523365SDimitry Andric return error("Malformed block"); 17557d523365SDimitry Andric case BitstreamEntry::EndBlock: 1756d88c1a5aSDimitry Andric return Error::success(); 17577d523365SDimitry Andric case BitstreamEntry::Record: 17587d523365SDimitry Andric // The interesting case. 17597d523365SDimitry Andric break; 17607d523365SDimitry Andric } 17617d523365SDimitry Andric 17627d523365SDimitry Andric // Tags are implicitly mapped to integers by their order. 17637d523365SDimitry Andric 17647d523365SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 17657d523365SDimitry Andric return error("Invalid record"); 17667d523365SDimitry Andric 17677d523365SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N] 17687d523365SDimitry Andric BundleTags.emplace_back(); 17697d523365SDimitry Andric if (convertToString(Record, 0, BundleTags.back())) 17707d523365SDimitry Andric return error("Invalid record"); 17717d523365SDimitry Andric Record.clear(); 17727d523365SDimitry Andric } 17737d523365SDimitry Andric } 17747d523365SDimitry Andric 1775c4394386SDimitry Andric Error BitcodeReader::parseSyncScopeNames() { 1776c4394386SDimitry Andric if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) 1777c4394386SDimitry Andric return error("Invalid record"); 1778c4394386SDimitry Andric 1779c4394386SDimitry Andric if (!SSIDs.empty()) 1780c4394386SDimitry Andric return error("Invalid multiple synchronization scope names blocks"); 1781c4394386SDimitry Andric 1782c4394386SDimitry Andric SmallVector<uint64_t, 64> Record; 1783c4394386SDimitry Andric while (true) { 1784c4394386SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1785c4394386SDimitry Andric switch (Entry.Kind) { 1786c4394386SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1787c4394386SDimitry Andric case BitstreamEntry::Error: 1788c4394386SDimitry Andric return error("Malformed block"); 1789c4394386SDimitry Andric case BitstreamEntry::EndBlock: 1790c4394386SDimitry Andric if (SSIDs.empty()) 1791c4394386SDimitry Andric return error("Invalid empty synchronization scope names block"); 1792c4394386SDimitry Andric return Error::success(); 1793c4394386SDimitry Andric case BitstreamEntry::Record: 1794c4394386SDimitry Andric // The interesting case. 1795c4394386SDimitry Andric break; 1796c4394386SDimitry Andric } 1797c4394386SDimitry Andric 1798c4394386SDimitry Andric // Synchronization scope names are implicitly mapped to synchronization 1799c4394386SDimitry Andric // scope IDs by their order. 1800c4394386SDimitry Andric 1801c4394386SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME) 1802c4394386SDimitry Andric return error("Invalid record"); 1803c4394386SDimitry Andric 1804c4394386SDimitry Andric SmallString<16> SSN; 1805c4394386SDimitry Andric if (convertToString(Record, 0, SSN)) 1806c4394386SDimitry Andric return error("Invalid record"); 1807c4394386SDimitry Andric 1808c4394386SDimitry Andric SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); 1809c4394386SDimitry Andric Record.clear(); 1810c4394386SDimitry Andric } 1811c4394386SDimitry Andric } 1812c4394386SDimitry Andric 18137d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record. 1814d88c1a5aSDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 18157d523365SDimitry Andric unsigned NameIndex, Triple &TT) { 18167d523365SDimitry Andric SmallString<128> ValueName; 18177d523365SDimitry Andric if (convertToString(Record, NameIndex, ValueName)) 18187d523365SDimitry Andric return error("Invalid record"); 18197d523365SDimitry Andric unsigned ValueID = Record[0]; 18207d523365SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 18217d523365SDimitry Andric return error("Invalid record"); 18227d523365SDimitry Andric Value *V = ValueList[ValueID]; 18237d523365SDimitry Andric 18247d523365SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size()); 18257d523365SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos) 18267d523365SDimitry Andric return error("Invalid value name"); 18277d523365SDimitry Andric V->setName(NameStr); 18287d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 18297d523365SDimitry Andric if (GO) { 18307d523365SDimitry Andric if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 18312cab237bSDimitry Andric if (TT.supportsCOMDAT()) 18327d523365SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 18332cab237bSDimitry Andric else 18342cab237bSDimitry Andric GO->setComdat(nullptr); 18357d523365SDimitry Andric } 18367d523365SDimitry Andric } 18377d523365SDimitry Andric return V; 18387d523365SDimitry Andric } 18397d523365SDimitry Andric 18403ca95b02SDimitry Andric /// Helper to note and return the current location, and jump to the given 18413ca95b02SDimitry Andric /// offset. 18423ca95b02SDimitry Andric static uint64_t jumpToValueSymbolTable(uint64_t Offset, 18433ca95b02SDimitry Andric BitstreamCursor &Stream) { 18447d523365SDimitry Andric // Save the current parsing location so we can jump back at the end 18457d523365SDimitry Andric // of the VST read. 18463ca95b02SDimitry Andric uint64_t CurrentBit = Stream.GetCurrentBitNo(); 18477d523365SDimitry Andric Stream.JumpToBit(Offset * 32); 18487d523365SDimitry Andric #ifndef NDEBUG 18497d523365SDimitry Andric // Do some checking if we are in debug mode. 18507d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 18517d523365SDimitry Andric assert(Entry.Kind == BitstreamEntry::SubBlock); 18527d523365SDimitry Andric assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 18537d523365SDimitry Andric #else 18547d523365SDimitry Andric // In NDEBUG mode ignore the output so we don't get an unused variable 18557d523365SDimitry Andric // warning. 18567d523365SDimitry Andric Stream.advance(); 18577d523365SDimitry Andric #endif 18583ca95b02SDimitry Andric return CurrentBit; 18597d523365SDimitry Andric } 18607d523365SDimitry Andric 18616bc11b14SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, 18626bc11b14SDimitry Andric Function *F, 18636bc11b14SDimitry Andric ArrayRef<uint64_t> Record) { 18646bc11b14SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 18656bc11b14SDimitry Andric // before the start of the identification or module block, which was 18666bc11b14SDimitry Andric // historically always the start of the regular bitcode header. 18676bc11b14SDimitry Andric uint64_t FuncWordOffset = Record[1] - 1; 18686bc11b14SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32; 18696bc11b14SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 18706bc11b14SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block. 18716bc11b14SDimitry Andric // Later when parsing is resumed after function materialization, 18726bc11b14SDimitry Andric // we can simply skip that last function block. 18736bc11b14SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit) 18746bc11b14SDimitry Andric LastFunctionBlockBit = FuncBitOffset; 18756bc11b14SDimitry Andric } 18766bc11b14SDimitry Andric 18776bc11b14SDimitry Andric /// Read a new-style GlobalValue symbol table. 18786bc11b14SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() { 18796bc11b14SDimitry Andric unsigned FuncBitcodeOffsetDelta = 18806bc11b14SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 18816bc11b14SDimitry Andric 18826bc11b14SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 18836bc11b14SDimitry Andric return error("Invalid record"); 18846bc11b14SDimitry Andric 18856bc11b14SDimitry Andric SmallVector<uint64_t, 64> Record; 18866bc11b14SDimitry Andric while (true) { 18876bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 18886bc11b14SDimitry Andric 18896bc11b14SDimitry Andric switch (Entry.Kind) { 18906bc11b14SDimitry Andric case BitstreamEntry::SubBlock: 18916bc11b14SDimitry Andric case BitstreamEntry::Error: 18926bc11b14SDimitry Andric return error("Malformed block"); 18936bc11b14SDimitry Andric case BitstreamEntry::EndBlock: 18946bc11b14SDimitry Andric return Error::success(); 18956bc11b14SDimitry Andric case BitstreamEntry::Record: 18966bc11b14SDimitry Andric break; 18976bc11b14SDimitry Andric } 18986bc11b14SDimitry Andric 18996bc11b14SDimitry Andric Record.clear(); 19006bc11b14SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 19016bc11b14SDimitry Andric case bitc::VST_CODE_FNENTRY: // [valueid, offset] 19026bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, 19036bc11b14SDimitry Andric cast<Function>(ValueList[Record[0]]), Record); 19046bc11b14SDimitry Andric break; 19056bc11b14SDimitry Andric } 19066bc11b14SDimitry Andric } 19076bc11b14SDimitry Andric } 19086bc11b14SDimitry Andric 19093ca95b02SDimitry Andric /// Parse the value symbol table at either the current parsing location or 19103ca95b02SDimitry Andric /// at the given bit offset if provided. 1911d88c1a5aSDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 19123ca95b02SDimitry Andric uint64_t CurrentBit; 19133ca95b02SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level 19143ca95b02SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level 19153ca95b02SDimitry Andric // VST (where we don't). 19166bc11b14SDimitry Andric if (Offset > 0) { 19173ca95b02SDimitry Andric CurrentBit = jumpToValueSymbolTable(Offset, Stream); 19186bc11b14SDimitry Andric // If this module uses a string table, read this as a module-level VST. 19196bc11b14SDimitry Andric if (UseStrtab) { 19206bc11b14SDimitry Andric if (Error Err = parseGlobalValueSymbolTable()) 19216bc11b14SDimitry Andric return Err; 19226bc11b14SDimitry Andric Stream.JumpToBit(CurrentBit); 19236bc11b14SDimitry Andric return Error::success(); 19246bc11b14SDimitry Andric } 19256bc11b14SDimitry Andric // Otherwise, the VST will be in a similar format to a function-level VST, 19266bc11b14SDimitry Andric // and will contain symbol names. 19276bc11b14SDimitry Andric } 19283ca95b02SDimitry Andric 19297d523365SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset 19307d523365SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that 19317d523365SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have 19327d523365SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 19337d523365SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 19347d523365SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock 19357d523365SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same 19367d523365SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 19377d523365SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to 19387d523365SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want 19397d523365SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 19407d523365SDimitry Andric unsigned FuncBitcodeOffsetDelta = 19417d523365SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 19427d523365SDimitry Andric 1943f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 19448f0fd8f6SDimitry Andric return error("Invalid record"); 1945f22ef01cSRoman Divacky 1946f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1947f22ef01cSRoman Divacky 1948ff0cc061SDimitry Andric Triple TT(TheModule->getTargetTriple()); 1949ff0cc061SDimitry Andric 1950f22ef01cSRoman Divacky // Read all the records for this value table. 1951f22ef01cSRoman Divacky SmallString<128> ValueName; 1952d88c1a5aSDimitry Andric 1953d88c1a5aSDimitry Andric while (true) { 1954139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1955f22ef01cSRoman Divacky 1956139f7f9bSDimitry Andric switch (Entry.Kind) { 1957139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1958139f7f9bSDimitry Andric case BitstreamEntry::Error: 19598f0fd8f6SDimitry Andric return error("Malformed block"); 1960139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 19617d523365SDimitry Andric if (Offset > 0) 19627d523365SDimitry Andric Stream.JumpToBit(CurrentBit); 1963d88c1a5aSDimitry Andric return Error::success(); 1964139f7f9bSDimitry Andric case BitstreamEntry::Record: 1965139f7f9bSDimitry Andric // The interesting case. 1966139f7f9bSDimitry Andric break; 1967f22ef01cSRoman Divacky } 1968f22ef01cSRoman Divacky 1969f22ef01cSRoman Divacky // Read a record. 1970f22ef01cSRoman Divacky Record.clear(); 1971139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1972f22ef01cSRoman Divacky default: // Default behavior: unknown type. 1973f22ef01cSRoman Divacky break; 19743ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 1975d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 1976d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError()) 1977d88c1a5aSDimitry Andric return Err; 19787d523365SDimitry Andric ValOrErr.get(); 19797d523365SDimitry Andric break; 19807d523365SDimitry Andric } 19817d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 19823ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 1983d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 1984d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError()) 1985d88c1a5aSDimitry Andric return Err; 19867d523365SDimitry Andric Value *V = ValOrErr.get(); 1987f22ef01cSRoman Divacky 19887a7e6055SDimitry Andric // Ignore function offsets emitted for aliases of functions in older 19897a7e6055SDimitry Andric // versions of LLVM. 19906bc11b14SDimitry Andric if (auto *F = dyn_cast<Function>(V)) 19916bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); 1992f22ef01cSRoman Divacky break; 1993f22ef01cSRoman Divacky } 1994f22ef01cSRoman Divacky case bitc::VST_CODE_BBENTRY: { 19958f0fd8f6SDimitry Andric if (convertToString(Record, 1, ValueName)) 19968f0fd8f6SDimitry Andric return error("Invalid record"); 1997f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[0]); 199891bc56edSDimitry Andric if (!BB) 19998f0fd8f6SDimitry Andric return error("Invalid record"); 2000f22ef01cSRoman Divacky 2001f22ef01cSRoman Divacky BB->setName(StringRef(ValueName.data(), ValueName.size())); 2002f22ef01cSRoman Divacky ValueName.clear(); 2003f22ef01cSRoman Divacky break; 2004f22ef01cSRoman Divacky } 2005f22ef01cSRoman Divacky } 2006f22ef01cSRoman Divacky } 2007f22ef01cSRoman Divacky } 2008f22ef01cSRoman Divacky 20098f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR 20108f0fd8f6SDimitry Andric /// encoding. 20113861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2012f22ef01cSRoman Divacky if ((V & 1) == 0) 2013f22ef01cSRoman Divacky return V >> 1; 2014f22ef01cSRoman Divacky if (V != 1) 2015f22ef01cSRoman Divacky return -(V >> 1); 2016f22ef01cSRoman Divacky // There is no such thing as -0 with integers. "-0" really means MININT. 2017f22ef01cSRoman Divacky return 1ULL << 63; 2018f22ef01cSRoman Divacky } 2019f22ef01cSRoman Divacky 20208f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can. 2021d88c1a5aSDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 2022f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; 20233ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> 20243ca95b02SDimitry Andric IndirectSymbolInitWorklist; 2025f785676fSDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist; 202639d628a0SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist; 20278f0fd8f6SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist; 2028f22ef01cSRoman Divacky 2029f22ef01cSRoman Divacky GlobalInitWorklist.swap(GlobalInits); 20303ca95b02SDimitry Andric IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2031f785676fSDimitry Andric FunctionPrefixWorklist.swap(FunctionPrefixes); 203239d628a0SDimitry Andric FunctionPrologueWorklist.swap(FunctionPrologues); 20338f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2034f22ef01cSRoman Divacky 2035f22ef01cSRoman Divacky while (!GlobalInitWorklist.empty()) { 2036f22ef01cSRoman Divacky unsigned ValID = GlobalInitWorklist.back().second; 2037f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2038f22ef01cSRoman Divacky // Not ready to resolve this yet, it requires something later in the file. 2039f22ef01cSRoman Divacky GlobalInits.push_back(GlobalInitWorklist.back()); 2040f22ef01cSRoman Divacky } else { 204191bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2042f22ef01cSRoman Divacky GlobalInitWorklist.back().first->setInitializer(C); 2043f22ef01cSRoman Divacky else 20448f0fd8f6SDimitry Andric return error("Expected a constant"); 2045f22ef01cSRoman Divacky } 2046f22ef01cSRoman Divacky GlobalInitWorklist.pop_back(); 2047f22ef01cSRoman Divacky } 2048f22ef01cSRoman Divacky 20493ca95b02SDimitry Andric while (!IndirectSymbolInitWorklist.empty()) { 20503ca95b02SDimitry Andric unsigned ValID = IndirectSymbolInitWorklist.back().second; 2051f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 20523ca95b02SDimitry Andric IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 2053f22ef01cSRoman Divacky } else { 205497bc6c73SDimitry Andric Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 205597bc6c73SDimitry Andric if (!C) 20568f0fd8f6SDimitry Andric return error("Expected a constant"); 20573ca95b02SDimitry Andric GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first; 20583ca95b02SDimitry Andric if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType()) 20598f0fd8f6SDimitry Andric return error("Alias and aliasee types don't match"); 20603ca95b02SDimitry Andric GIS->setIndirectSymbol(C); 2061f22ef01cSRoman Divacky } 20623ca95b02SDimitry Andric IndirectSymbolInitWorklist.pop_back(); 2063f22ef01cSRoman Divacky } 2064f785676fSDimitry Andric 2065f785676fSDimitry Andric while (!FunctionPrefixWorklist.empty()) { 2066f785676fSDimitry Andric unsigned ValID = FunctionPrefixWorklist.back().second; 2067f785676fSDimitry Andric if (ValID >= ValueList.size()) { 2068f785676fSDimitry Andric FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2069f785676fSDimitry Andric } else { 207091bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2071f785676fSDimitry Andric FunctionPrefixWorklist.back().first->setPrefixData(C); 2072f785676fSDimitry Andric else 20738f0fd8f6SDimitry Andric return error("Expected a constant"); 2074f785676fSDimitry Andric } 2075f785676fSDimitry Andric FunctionPrefixWorklist.pop_back(); 2076f785676fSDimitry Andric } 2077f785676fSDimitry Andric 207839d628a0SDimitry Andric while (!FunctionPrologueWorklist.empty()) { 207939d628a0SDimitry Andric unsigned ValID = FunctionPrologueWorklist.back().second; 208039d628a0SDimitry Andric if (ValID >= ValueList.size()) { 208139d628a0SDimitry Andric FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 208239d628a0SDimitry Andric } else { 208339d628a0SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 208439d628a0SDimitry Andric FunctionPrologueWorklist.back().first->setPrologueData(C); 208539d628a0SDimitry Andric else 20868f0fd8f6SDimitry Andric return error("Expected a constant"); 208739d628a0SDimitry Andric } 208839d628a0SDimitry Andric FunctionPrologueWorklist.pop_back(); 208939d628a0SDimitry Andric } 209039d628a0SDimitry Andric 20918f0fd8f6SDimitry Andric while (!FunctionPersonalityFnWorklist.empty()) { 20928f0fd8f6SDimitry Andric unsigned ValID = FunctionPersonalityFnWorklist.back().second; 20938f0fd8f6SDimitry Andric if (ValID >= ValueList.size()) { 20948f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 20958f0fd8f6SDimitry Andric } else { 20968f0fd8f6SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 20978f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 20988f0fd8f6SDimitry Andric else 20998f0fd8f6SDimitry Andric return error("Expected a constant"); 21008f0fd8f6SDimitry Andric } 21018f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.pop_back(); 21028f0fd8f6SDimitry Andric } 21038f0fd8f6SDimitry Andric 2104d88c1a5aSDimitry Andric return Error::success(); 2105f22ef01cSRoman Divacky } 2106f22ef01cSRoman Divacky 21078f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 21087ae0e2c9SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size()); 2109d88c1a5aSDimitry Andric transform(Vals, Words.begin(), 21103861d79fSDimitry Andric BitcodeReader::decodeSignRotatedValue); 21117ae0e2c9SDimitry Andric 21127ae0e2c9SDimitry Andric return APInt(TypeBits, Words); 21137ae0e2c9SDimitry Andric } 21147ae0e2c9SDimitry Andric 2115d88c1a5aSDimitry Andric Error BitcodeReader::parseConstants() { 2116f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 21178f0fd8f6SDimitry Andric return error("Invalid record"); 2118f22ef01cSRoman Divacky 2119f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 2120f22ef01cSRoman Divacky 2121f22ef01cSRoman Divacky // Read all the records for this value table. 21226122f3e6SDimitry Andric Type *CurTy = Type::getInt32Ty(Context); 2123f22ef01cSRoman Divacky unsigned NextCstNo = ValueList.size(); 2124d88c1a5aSDimitry Andric 2125d88c1a5aSDimitry Andric while (true) { 2126139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2127139f7f9bSDimitry Andric 2128139f7f9bSDimitry Andric switch (Entry.Kind) { 2129139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2130139f7f9bSDimitry Andric case BitstreamEntry::Error: 21318f0fd8f6SDimitry Andric return error("Malformed block"); 2132139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2133139f7f9bSDimitry Andric if (NextCstNo != ValueList.size()) 21343ca95b02SDimitry Andric return error("Invalid constant reference"); 2135139f7f9bSDimitry Andric 2136139f7f9bSDimitry Andric // Once all the constants have been read, go through and resolve forward 2137139f7f9bSDimitry Andric // references. 21388f0fd8f6SDimitry Andric ValueList.resolveConstantForwardRefs(); 2139d88c1a5aSDimitry Andric return Error::success(); 2140139f7f9bSDimitry Andric case BitstreamEntry::Record: 2141139f7f9bSDimitry Andric // The interesting case. 2142f22ef01cSRoman Divacky break; 2143f22ef01cSRoman Divacky } 2144f22ef01cSRoman Divacky 2145f22ef01cSRoman Divacky // Read a record. 2146f22ef01cSRoman Divacky Record.clear(); 21473ca95b02SDimitry Andric Type *VoidType = Type::getVoidTy(Context); 214891bc56edSDimitry Andric Value *V = nullptr; 2149139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2150f22ef01cSRoman Divacky switch (BitCode) { 2151f22ef01cSRoman Divacky default: // Default behavior: unknown constant 2152f22ef01cSRoman Divacky case bitc::CST_CODE_UNDEF: // UNDEF 2153f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2154f22ef01cSRoman Divacky break; 2155f22ef01cSRoman Divacky case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2156f22ef01cSRoman Divacky if (Record.empty()) 21578f0fd8f6SDimitry Andric return error("Invalid record"); 215891bc56edSDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 21598f0fd8f6SDimitry Andric return error("Invalid record"); 21603ca95b02SDimitry Andric if (TypeList[Record[0]] == VoidType) 21613ca95b02SDimitry Andric return error("Invalid constant type"); 2162f22ef01cSRoman Divacky CurTy = TypeList[Record[0]]; 2163f22ef01cSRoman Divacky continue; // Skip the ValueList manipulation. 2164f22ef01cSRoman Divacky case bitc::CST_CODE_NULL: // NULL 2165f22ef01cSRoman Divacky V = Constant::getNullValue(CurTy); 2166f22ef01cSRoman Divacky break; 2167f22ef01cSRoman Divacky case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2168f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 21698f0fd8f6SDimitry Andric return error("Invalid record"); 21703861d79fSDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2171f22ef01cSRoman Divacky break; 2172f22ef01cSRoman Divacky case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2173f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 21748f0fd8f6SDimitry Andric return error("Invalid record"); 2175f22ef01cSRoman Divacky 21768f0fd8f6SDimitry Andric APInt VInt = 21778f0fd8f6SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 21787ae0e2c9SDimitry Andric V = ConstantInt::get(Context, VInt); 21797ae0e2c9SDimitry Andric 2180f22ef01cSRoman Divacky break; 2181f22ef01cSRoman Divacky } 2182f22ef01cSRoman Divacky case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2183f22ef01cSRoman Divacky if (Record.empty()) 21848f0fd8f6SDimitry Andric return error("Invalid record"); 2185dff0c46cSDimitry Andric if (CurTy->isHalfTy()) 2186d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(), 2187139f7f9bSDimitry Andric APInt(16, (uint16_t)Record[0]))); 2188dff0c46cSDimitry Andric else if (CurTy->isFloatTy()) 2189d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), 2190139f7f9bSDimitry Andric APInt(32, (uint32_t)Record[0]))); 2191f22ef01cSRoman Divacky else if (CurTy->isDoubleTy()) 2192d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), 2193139f7f9bSDimitry Andric APInt(64, Record[0]))); 2194f22ef01cSRoman Divacky else if (CurTy->isX86_FP80Ty()) { 2195f22ef01cSRoman Divacky // Bits are not stored the same way as a normal i80 APInt, compensate. 2196f22ef01cSRoman Divacky uint64_t Rearrange[2]; 2197f22ef01cSRoman Divacky Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2198f22ef01cSRoman Divacky Rearrange[1] = Record[0] >> 48; 2199d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), 2200139f7f9bSDimitry Andric APInt(80, Rearrange))); 2201f22ef01cSRoman Divacky } else if (CurTy->isFP128Ty()) 2202d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), 2203139f7f9bSDimitry Andric APInt(128, Record))); 2204f22ef01cSRoman Divacky else if (CurTy->isPPC_FP128Ty()) 2205d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), 2206139f7f9bSDimitry Andric APInt(128, Record))); 2207f22ef01cSRoman Divacky else 2208f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2209f22ef01cSRoman Divacky break; 2210f22ef01cSRoman Divacky } 2211f22ef01cSRoman Divacky 2212f22ef01cSRoman Divacky case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2213f22ef01cSRoman Divacky if (Record.empty()) 22148f0fd8f6SDimitry Andric return error("Invalid record"); 2215f22ef01cSRoman Divacky 2216f22ef01cSRoman Divacky unsigned Size = Record.size(); 2217dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 2218f22ef01cSRoman Divacky 22196122f3e6SDimitry Andric if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2220f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2221f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2222f22ef01cSRoman Divacky STy->getElementType(i))); 2223f22ef01cSRoman Divacky V = ConstantStruct::get(STy, Elts); 22246122f3e6SDimitry Andric } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 22256122f3e6SDimitry Andric Type *EltTy = ATy->getElementType(); 2226f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2227f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2228f22ef01cSRoman Divacky V = ConstantArray::get(ATy, Elts); 22296122f3e6SDimitry Andric } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 22306122f3e6SDimitry Andric Type *EltTy = VTy->getElementType(); 2231f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2232f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2233f22ef01cSRoman Divacky V = ConstantVector::get(Elts); 2234f22ef01cSRoman Divacky } else { 2235f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2236f22ef01cSRoman Divacky } 2237f22ef01cSRoman Divacky break; 2238f22ef01cSRoman Divacky } 2239dff0c46cSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values] 2240f22ef01cSRoman Divacky case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2241f22ef01cSRoman Divacky if (Record.empty()) 22428f0fd8f6SDimitry Andric return error("Invalid record"); 2243f22ef01cSRoman Divacky 22447ae0e2c9SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end()); 2245dff0c46cSDimitry Andric V = ConstantDataArray::getString(Context, Elts, 2246dff0c46cSDimitry Andric BitCode == bitc::CST_CODE_CSTRING); 2247f22ef01cSRoman Divacky break; 2248f22ef01cSRoman Divacky } 2249dff0c46cSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value] 2250dff0c46cSDimitry Andric if (Record.empty()) 22518f0fd8f6SDimitry Andric return error("Invalid record"); 2252dff0c46cSDimitry Andric 2253dff0c46cSDimitry Andric Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2254dff0c46cSDimitry Andric if (EltTy->isIntegerTy(8)) { 2255dff0c46cSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2256dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2257dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2258dff0c46cSDimitry Andric else 2259dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2260dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(16)) { 2261dff0c46cSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2262dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2263dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2264dff0c46cSDimitry Andric else 2265dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2266dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(32)) { 2267dff0c46cSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2268dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2269dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2270dff0c46cSDimitry Andric else 2271dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2272dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(64)) { 2273dff0c46cSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2274dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2275dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2276dff0c46cSDimitry Andric else 2277dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2278444ed5c5SDimitry Andric } else if (EltTy->isHalfTy()) { 2279444ed5c5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2280444ed5c5SDimitry Andric if (isa<VectorType>(CurTy)) 2281444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2282444ed5c5SDimitry Andric else 2283444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2284dff0c46cSDimitry Andric } else if (EltTy->isFloatTy()) { 2285444ed5c5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2286dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2287444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2288dff0c46cSDimitry Andric else 2289444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2290dff0c46cSDimitry Andric } else if (EltTy->isDoubleTy()) { 2291444ed5c5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2292dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2293444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts); 2294dff0c46cSDimitry Andric else 2295444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts); 2296dff0c46cSDimitry Andric } else { 22978f0fd8f6SDimitry Andric return error("Invalid type for value"); 2298dff0c46cSDimitry Andric } 2299dff0c46cSDimitry Andric break; 2300dff0c46cSDimitry Andric } 2301f22ef01cSRoman Divacky case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2302f785676fSDimitry Andric if (Record.size() < 3) 23038f0fd8f6SDimitry Andric return error("Invalid record"); 23048f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2305f22ef01cSRoman Divacky if (Opc < 0) { 2306f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown binop. 2307f22ef01cSRoman Divacky } else { 2308f22ef01cSRoman Divacky Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2309f22ef01cSRoman Divacky Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2310f22ef01cSRoman Divacky unsigned Flags = 0; 2311f22ef01cSRoman Divacky if (Record.size() >= 4) { 2312f22ef01cSRoman Divacky if (Opc == Instruction::Add || 2313f22ef01cSRoman Divacky Opc == Instruction::Sub || 23142754fe60SDimitry Andric Opc == Instruction::Mul || 23152754fe60SDimitry Andric Opc == Instruction::Shl) { 2316f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2317f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap; 2318f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2319f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 23202754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 23212754fe60SDimitry Andric Opc == Instruction::UDiv || 23222754fe60SDimitry Andric Opc == Instruction::LShr || 23232754fe60SDimitry Andric Opc == Instruction::AShr) { 23242754fe60SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT)) 2325f22ef01cSRoman Divacky Flags |= SDivOperator::IsExact; 2326f22ef01cSRoman Divacky } 2327f22ef01cSRoman Divacky } 2328f22ef01cSRoman Divacky V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2329f22ef01cSRoman Divacky } 2330f22ef01cSRoman Divacky break; 2331f22ef01cSRoman Divacky } 2332f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2333f785676fSDimitry Andric if (Record.size() < 3) 23348f0fd8f6SDimitry Andric return error("Invalid record"); 23358f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]); 2336f22ef01cSRoman Divacky if (Opc < 0) { 2337f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown cast. 2338f22ef01cSRoman Divacky } else { 23396122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 2340f785676fSDimitry Andric if (!OpTy) 23418f0fd8f6SDimitry Andric return error("Invalid record"); 2342f22ef01cSRoman Divacky Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2343f785676fSDimitry Andric V = UpgradeBitCastExpr(Opc, Op, CurTy); 2344f785676fSDimitry Andric if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2345f22ef01cSRoman Divacky } 2346f22ef01cSRoman Divacky break; 2347f22ef01cSRoman Divacky } 2348d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 2349d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 2350d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 2351d88c1a5aSDimitry Andric // operands] 2352ff0cc061SDimitry Andric unsigned OpNum = 0; 2353ff0cc061SDimitry Andric Type *PointeeType = nullptr; 2354d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 2355d88c1a5aSDimitry Andric Record.size() % 2) 2356ff0cc061SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]); 2357d88c1a5aSDimitry Andric 2358d88c1a5aSDimitry Andric bool InBounds = false; 2359d88c1a5aSDimitry Andric Optional<unsigned> InRangeIndex; 2360d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 2361d88c1a5aSDimitry Andric uint64_t Op = Record[OpNum++]; 2362d88c1a5aSDimitry Andric InBounds = Op & 1; 2363d88c1a5aSDimitry Andric InRangeIndex = Op >> 1; 2364d88c1a5aSDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 2365d88c1a5aSDimitry Andric InBounds = true; 2366d88c1a5aSDimitry Andric 2367f22ef01cSRoman Divacky SmallVector<Constant*, 16> Elts; 2368ff0cc061SDimitry Andric while (OpNum != Record.size()) { 2369ff0cc061SDimitry Andric Type *ElTy = getTypeByID(Record[OpNum++]); 2370f785676fSDimitry Andric if (!ElTy) 23718f0fd8f6SDimitry Andric return error("Invalid record"); 2372ff0cc061SDimitry Andric Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2373f22ef01cSRoman Divacky } 2374ff0cc061SDimitry Andric 2375ff0cc061SDimitry Andric if (PointeeType && 2376ff0cc061SDimitry Andric PointeeType != 2377d88c1a5aSDimitry Andric cast<PointerType>(Elts[0]->getType()->getScalarType()) 2378ff0cc061SDimitry Andric ->getElementType()) 23798f0fd8f6SDimitry Andric return error("Explicit gep operator type does not match pointee type " 2380ff0cc061SDimitry Andric "of pointer operand"); 2381ff0cc061SDimitry Andric 23823ca95b02SDimitry Andric if (Elts.size() < 1) 23833ca95b02SDimitry Andric return error("Invalid gep with no operands"); 23843ca95b02SDimitry Andric 23856122f3e6SDimitry Andric ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2386ff0cc061SDimitry Andric V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 2387d88c1a5aSDimitry Andric InBounds, InRangeIndex); 2388f22ef01cSRoman Divacky break; 2389f22ef01cSRoman Divacky } 2390f785676fSDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2391f785676fSDimitry Andric if (Record.size() < 3) 23928f0fd8f6SDimitry Andric return error("Invalid record"); 2393f785676fSDimitry Andric 2394f785676fSDimitry Andric Type *SelectorTy = Type::getInt1Ty(Context); 2395f785676fSDimitry Andric 23967d523365SDimitry Andric // The selector might be an i1 or an <n x i1> 23977d523365SDimitry Andric // Get the type from the ValueList before getting a forward ref. 2398f785676fSDimitry Andric if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 23997d523365SDimitry Andric if (Value *V = ValueList[Record[0]]) 24007d523365SDimitry Andric if (SelectorTy != V->getType()) 24017d523365SDimitry Andric SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2402f785676fSDimitry Andric 2403f785676fSDimitry Andric V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2404f785676fSDimitry Andric SelectorTy), 2405f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[1],CurTy), 2406f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[2],CurTy)); 2407f22ef01cSRoman Divacky break; 2408f785676fSDimitry Andric } 240991bc56edSDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT 241091bc56edSDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2411f785676fSDimitry Andric if (Record.size() < 3) 24128f0fd8f6SDimitry Andric return error("Invalid record"); 24136122f3e6SDimitry Andric VectorType *OpTy = 2414f22ef01cSRoman Divacky dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 241591bc56edSDimitry Andric if (!OpTy) 24168f0fd8f6SDimitry Andric return error("Invalid record"); 2417f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 241891bc56edSDimitry Andric Constant *Op1 = nullptr; 241991bc56edSDimitry Andric if (Record.size() == 4) { 242091bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 242191bc56edSDimitry Andric if (!IdxTy) 24228f0fd8f6SDimitry Andric return error("Invalid record"); 242391bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 242491bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 242591bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 242691bc56edSDimitry Andric if (!Op1) 24278f0fd8f6SDimitry Andric return error("Invalid record"); 2428f22ef01cSRoman Divacky V = ConstantExpr::getExtractElement(Op0, Op1); 2429f22ef01cSRoman Divacky break; 2430f22ef01cSRoman Divacky } 243191bc56edSDimitry Andric case bitc::CST_CODE_CE_INSERTELT 243291bc56edSDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval] 24336122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 243491bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 24358f0fd8f6SDimitry Andric return error("Invalid record"); 2436f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2437f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2438f22ef01cSRoman Divacky OpTy->getElementType()); 243991bc56edSDimitry Andric Constant *Op2 = nullptr; 244091bc56edSDimitry Andric if (Record.size() == 4) { 244191bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 244291bc56edSDimitry Andric if (!IdxTy) 24438f0fd8f6SDimitry Andric return error("Invalid record"); 244491bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 244591bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 244691bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 244791bc56edSDimitry Andric if (!Op2) 24488f0fd8f6SDimitry Andric return error("Invalid record"); 2449f22ef01cSRoman Divacky V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2450f22ef01cSRoman Divacky break; 2451f22ef01cSRoman Divacky } 2452f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 24536122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 245491bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 24558f0fd8f6SDimitry Andric return error("Invalid record"); 2456f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2457f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 24586122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2459f22ef01cSRoman Divacky OpTy->getNumElements()); 2460f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2461f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2462f22ef01cSRoman Divacky break; 2463f22ef01cSRoman Divacky } 2464f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 24656122f3e6SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy); 24666122f3e6SDimitry Andric VectorType *OpTy = 24672754fe60SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 246891bc56edSDimitry Andric if (Record.size() < 4 || !RTy || !OpTy) 24698f0fd8f6SDimitry Andric return error("Invalid record"); 2470f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2471f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 24726122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2473f22ef01cSRoman Divacky RTy->getNumElements()); 2474f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2475f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2476f22ef01cSRoman Divacky break; 2477f22ef01cSRoman Divacky } 2478f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2479f785676fSDimitry Andric if (Record.size() < 4) 24808f0fd8f6SDimitry Andric return error("Invalid record"); 24816122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 248291bc56edSDimitry Andric if (!OpTy) 24838f0fd8f6SDimitry Andric return error("Invalid record"); 2484f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2485f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2486f22ef01cSRoman Divacky 2487f22ef01cSRoman Divacky if (OpTy->isFPOrFPVectorTy()) 2488f22ef01cSRoman Divacky V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2489f22ef01cSRoman Divacky else 2490f22ef01cSRoman Divacky V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2491f22ef01cSRoman Divacky break; 2492f22ef01cSRoman Divacky } 24933861d79fSDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords. 24943861d79fSDimitry Andric // FIXME: Remove with the 4.0 release. 24953861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: { 2496f785676fSDimitry Andric if (Record.size() < 2) 24978f0fd8f6SDimitry Andric return error("Invalid record"); 2498f22ef01cSRoman Divacky std::string AsmStr, ConstrStr; 2499f22ef01cSRoman Divacky bool HasSideEffects = Record[0] & 1; 2500f22ef01cSRoman Divacky bool IsAlignStack = Record[0] >> 1; 2501f22ef01cSRoman Divacky unsigned AsmStrSize = Record[1]; 2502f22ef01cSRoman Divacky if (2+AsmStrSize >= Record.size()) 25038f0fd8f6SDimitry Andric return error("Invalid record"); 2504f22ef01cSRoman Divacky unsigned ConstStrSize = Record[2+AsmStrSize]; 2505f22ef01cSRoman Divacky if (3+AsmStrSize+ConstStrSize > Record.size()) 25068f0fd8f6SDimitry Andric return error("Invalid record"); 2507f22ef01cSRoman Divacky 2508f22ef01cSRoman Divacky for (unsigned i = 0; i != AsmStrSize; ++i) 2509f22ef01cSRoman Divacky AsmStr += (char)Record[2+i]; 2510f22ef01cSRoman Divacky for (unsigned i = 0; i != ConstStrSize; ++i) 2511f22ef01cSRoman Divacky ConstrStr += (char)Record[3+AsmStrSize+i]; 25126122f3e6SDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 2513f22ef01cSRoman Divacky V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2514f22ef01cSRoman Divacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2515f22ef01cSRoman Divacky break; 2516f22ef01cSRoman Divacky } 25173861d79fSDimitry Andric // This version adds support for the asm dialect keywords (e.g., 25183861d79fSDimitry Andric // inteldialect). 25193861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM: { 2520f785676fSDimitry Andric if (Record.size() < 2) 25218f0fd8f6SDimitry Andric return error("Invalid record"); 25223861d79fSDimitry Andric std::string AsmStr, ConstrStr; 25233861d79fSDimitry Andric bool HasSideEffects = Record[0] & 1; 25243861d79fSDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1; 25253861d79fSDimitry Andric unsigned AsmDialect = Record[0] >> 2; 25263861d79fSDimitry Andric unsigned AsmStrSize = Record[1]; 25273861d79fSDimitry Andric if (2+AsmStrSize >= Record.size()) 25288f0fd8f6SDimitry Andric return error("Invalid record"); 25293861d79fSDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 25303861d79fSDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 25318f0fd8f6SDimitry Andric return error("Invalid record"); 25323861d79fSDimitry Andric 25333861d79fSDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 25343861d79fSDimitry Andric AsmStr += (char)Record[2+i]; 25353861d79fSDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 25363861d79fSDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 25373861d79fSDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 25383861d79fSDimitry Andric V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 25393861d79fSDimitry Andric AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 25403861d79fSDimitry Andric InlineAsm::AsmDialect(AsmDialect)); 25413861d79fSDimitry Andric break; 25423861d79fSDimitry Andric } 2543f22ef01cSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{ 2544f785676fSDimitry Andric if (Record.size() < 3) 25458f0fd8f6SDimitry Andric return error("Invalid record"); 25466122f3e6SDimitry Andric Type *FnTy = getTypeByID(Record[0]); 254791bc56edSDimitry Andric if (!FnTy) 25488f0fd8f6SDimitry Andric return error("Invalid record"); 2549f22ef01cSRoman Divacky Function *Fn = 2550f22ef01cSRoman Divacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 255191bc56edSDimitry Andric if (!Fn) 25528f0fd8f6SDimitry Andric return error("Invalid record"); 255339d628a0SDimitry Andric 25543861d79fSDimitry Andric // If the function is already parsed we can insert the block address right 25553861d79fSDimitry Andric // away. 255639d628a0SDimitry Andric BasicBlock *BB; 255739d628a0SDimitry Andric unsigned BBID = Record[2]; 255839d628a0SDimitry Andric if (!BBID) 255939d628a0SDimitry Andric // Invalid reference to entry block. 25608f0fd8f6SDimitry Andric return error("Invalid ID"); 25613861d79fSDimitry Andric if (!Fn->empty()) { 25623861d79fSDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 256339d628a0SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) { 25643861d79fSDimitry Andric if (BBI == BBE) 25658f0fd8f6SDimitry Andric return error("Invalid ID"); 25663861d79fSDimitry Andric ++BBI; 25673861d79fSDimitry Andric } 25687d523365SDimitry Andric BB = &*BBI; 25693861d79fSDimitry Andric } else { 25703861d79fSDimitry Andric // Otherwise insert a placeholder and remember it so it can be inserted 25713861d79fSDimitry Andric // when the function is parsed. 257239d628a0SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn]; 257339d628a0SDimitry Andric if (FwdBBs.empty()) 257439d628a0SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn); 257539d628a0SDimitry Andric if (FwdBBs.size() < BBID + 1) 257639d628a0SDimitry Andric FwdBBs.resize(BBID + 1); 257739d628a0SDimitry Andric if (!FwdBBs[BBID]) 257839d628a0SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context); 257939d628a0SDimitry Andric BB = FwdBBs[BBID]; 25803861d79fSDimitry Andric } 258139d628a0SDimitry Andric V = BlockAddress::get(Fn, BB); 2582f22ef01cSRoman Divacky break; 2583f22ef01cSRoman Divacky } 2584f22ef01cSRoman Divacky } 2585f22ef01cSRoman Divacky 25868f0fd8f6SDimitry Andric ValueList.assignValue(V, NextCstNo); 2587f22ef01cSRoman Divacky ++NextCstNo; 2588f22ef01cSRoman Divacky } 2589f22ef01cSRoman Divacky } 2590f22ef01cSRoman Divacky 2591d88c1a5aSDimitry Andric Error BitcodeReader::parseUseLists() { 2592dff0c46cSDimitry Andric if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 25938f0fd8f6SDimitry Andric return error("Invalid record"); 2594dff0c46cSDimitry Andric 2595dff0c46cSDimitry Andric // Read all the records. 259639d628a0SDimitry Andric SmallVector<uint64_t, 64> Record; 2597d88c1a5aSDimitry Andric 2598d88c1a5aSDimitry Andric while (true) { 2599139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2600139f7f9bSDimitry Andric 2601139f7f9bSDimitry Andric switch (Entry.Kind) { 2602139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2603139f7f9bSDimitry Andric case BitstreamEntry::Error: 26048f0fd8f6SDimitry Andric return error("Malformed block"); 2605139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2606d88c1a5aSDimitry Andric return Error::success(); 2607139f7f9bSDimitry Andric case BitstreamEntry::Record: 2608139f7f9bSDimitry Andric // The interesting case. 2609139f7f9bSDimitry Andric break; 2610dff0c46cSDimitry Andric } 2611dff0c46cSDimitry Andric 2612dff0c46cSDimitry Andric // Read a use list record. 2613dff0c46cSDimitry Andric Record.clear(); 261439d628a0SDimitry Andric bool IsBB = false; 2615139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 2616dff0c46cSDimitry Andric default: // Default behavior: unknown type. 2617dff0c46cSDimitry Andric break; 261839d628a0SDimitry Andric case bitc::USELIST_CODE_BB: 261939d628a0SDimitry Andric IsBB = true; 2620d88c1a5aSDimitry Andric LLVM_FALLTHROUGH; 262139d628a0SDimitry Andric case bitc::USELIST_CODE_DEFAULT: { 2622dff0c46cSDimitry Andric unsigned RecordLength = Record.size(); 262339d628a0SDimitry Andric if (RecordLength < 3) 262439d628a0SDimitry Andric // Records should have at least an ID and two indexes. 26258f0fd8f6SDimitry Andric return error("Invalid record"); 262639d628a0SDimitry Andric unsigned ID = Record.back(); 262739d628a0SDimitry Andric Record.pop_back(); 262839d628a0SDimitry Andric 262939d628a0SDimitry Andric Value *V; 263039d628a0SDimitry Andric if (IsBB) { 263139d628a0SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found"); 263239d628a0SDimitry Andric V = FunctionBBs[ID]; 263339d628a0SDimitry Andric } else 263439d628a0SDimitry Andric V = ValueList[ID]; 263539d628a0SDimitry Andric unsigned NumUses = 0; 263639d628a0SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order; 26377d523365SDimitry Andric for (const Use &U : V->materialized_uses()) { 263839d628a0SDimitry Andric if (++NumUses > Record.size()) 263939d628a0SDimitry Andric break; 264039d628a0SDimitry Andric Order[&U] = Record[NumUses - 1]; 264139d628a0SDimitry Andric } 264239d628a0SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size()) 264339d628a0SDimitry Andric // Mismatches can happen if the functions are being materialized lazily 264439d628a0SDimitry Andric // (out-of-order), or a value has been upgraded. 264539d628a0SDimitry Andric break; 264639d628a0SDimitry Andric 264739d628a0SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) { 264839d628a0SDimitry Andric return Order.lookup(&L) < Order.lookup(&R); 264939d628a0SDimitry Andric }); 2650dff0c46cSDimitry Andric break; 2651dff0c46cSDimitry Andric } 2652dff0c46cSDimitry Andric } 2653dff0c46cSDimitry Andric } 2654dff0c46cSDimitry Andric } 2655dff0c46cSDimitry Andric 2656ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it. 2657ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata. 2658d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() { 2659ff0cc061SDimitry Andric // Save the current stream state. 2660ff0cc061SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 2661ff0cc061SDimitry Andric DeferredMetadataInfo.push_back(CurBit); 2662ff0cc061SDimitry Andric 2663ff0cc061SDimitry Andric // Skip over the block for now. 2664ff0cc061SDimitry Andric if (Stream.SkipBlock()) 26658f0fd8f6SDimitry Andric return error("Invalid record"); 2666d88c1a5aSDimitry Andric return Error::success(); 2667ff0cc061SDimitry Andric } 2668ff0cc061SDimitry Andric 2669d88c1a5aSDimitry Andric Error BitcodeReader::materializeMetadata() { 2670ff0cc061SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) { 2671ff0cc061SDimitry Andric // Move the bit stream to the saved position. 2672ff0cc061SDimitry Andric Stream.JumpToBit(BitPos); 2673d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 2674d88c1a5aSDimitry Andric return Err; 2675ff0cc061SDimitry Andric } 267624d58133SDimitry Andric 267724d58133SDimitry Andric // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 267824d58133SDimitry Andric // metadata. 267924d58133SDimitry Andric if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 268024d58133SDimitry Andric NamedMDNode *LinkerOpts = 268124d58133SDimitry Andric TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 268224d58133SDimitry Andric for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 268324d58133SDimitry Andric LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 268424d58133SDimitry Andric } 268524d58133SDimitry Andric 2686ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 2687d88c1a5aSDimitry Andric return Error::success(); 2688ff0cc061SDimitry Andric } 2689ff0cc061SDimitry Andric 2690ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 2691ff0cc061SDimitry Andric 26928f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then 26938f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 2694d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() { 2695f22ef01cSRoman Divacky // Get the function we are talking about. 2696f22ef01cSRoman Divacky if (FunctionsWithBodies.empty()) 26978f0fd8f6SDimitry Andric return error("Insufficient function protos"); 2698f22ef01cSRoman Divacky 2699f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back(); 2700f22ef01cSRoman Divacky FunctionsWithBodies.pop_back(); 2701f22ef01cSRoman Divacky 2702f22ef01cSRoman Divacky // Save the current stream state. 2703f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo(); 27047d523365SDimitry Andric assert( 27057d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 27067d523365SDimitry Andric "Mismatch between VST and scanned function offsets"); 2707f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit; 2708f22ef01cSRoman Divacky 2709f22ef01cSRoman Divacky // Skip over the function block for now. 2710f22ef01cSRoman Divacky if (Stream.SkipBlock()) 27118f0fd8f6SDimitry Andric return error("Invalid record"); 2712d88c1a5aSDimitry Andric return Error::success(); 2713f22ef01cSRoman Divacky } 2714f22ef01cSRoman Divacky 2715d88c1a5aSDimitry Andric Error BitcodeReader::globalCleanup() { 2716f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up. 2717d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 2718d88c1a5aSDimitry Andric return Err; 27193ca95b02SDimitry Andric if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 27208f0fd8f6SDimitry Andric return error("Malformed global initializer set"); 2721f22ef01cSRoman Divacky 2722f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point 27238f0fd8f6SDimitry Andric for (Function &F : *TheModule) { 27246bc11b14SDimitry Andric MDLoader->upgradeDebugIntrinsics(F); 2725f22ef01cSRoman Divacky Function *NewFn; 27268f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 27273dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn; 27283ca95b02SDimitry Andric else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) 27293ca95b02SDimitry Andric // Some types could be renamed during loading if several modules are 27303ca95b02SDimitry Andric // loaded in the same LLVMContext (LTO scenario). In this case we should 27313ca95b02SDimitry Andric // remangle intrinsics names as well. 27323ca95b02SDimitry Andric RemangledIntrinsics[&F] = Remangled.getValue(); 2733f22ef01cSRoman Divacky } 2734f22ef01cSRoman Divacky 2735e580952dSDimitry Andric // Look for global variables which need to be renamed. 27368f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 27378f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV); 273891bc56edSDimitry Andric 2739f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that 2740f22ef01cSRoman Divacky // want lazy deserialization. 2741f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); 27423ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap( 27433ca95b02SDimitry Andric IndirectSymbolInits); 2744d88c1a5aSDimitry Andric return Error::success(); 2745f22ef01cSRoman Divacky } 2746f22ef01cSRoman Divacky 27477d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 27487d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 27497d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 27507d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST. 2751d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() { 2752dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit); 27537d523365SDimitry Andric 27547d523365SDimitry Andric if (Stream.AtEndOfStream()) 27557d523365SDimitry Andric return error("Could not find function in stream"); 27567d523365SDimitry Andric 27577d523365SDimitry Andric if (!SeenFirstFunctionBody) 27587d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 27597d523365SDimitry Andric 27607d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have 27617d523365SDimitry Andric // finished the parse greedily. 27627d523365SDimitry Andric assert(SeenValueSymbolTable); 27637d523365SDimitry Andric 27647d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 27657d523365SDimitry Andric 2766d88c1a5aSDimitry Andric while (true) { 27677d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 27687d523365SDimitry Andric switch (Entry.Kind) { 27697d523365SDimitry Andric default: 27707d523365SDimitry Andric return error("Expect SubBlock"); 27717d523365SDimitry Andric case BitstreamEntry::SubBlock: 27727d523365SDimitry Andric switch (Entry.ID) { 27737d523365SDimitry Andric default: 27747d523365SDimitry Andric return error("Expect function block"); 27757d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 2776d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 2777d88c1a5aSDimitry Andric return Err; 27787d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 2779d88c1a5aSDimitry Andric return Error::success(); 27807d523365SDimitry Andric } 27817d523365SDimitry Andric } 27827d523365SDimitry Andric } 27837d523365SDimitry Andric } 27847d523365SDimitry Andric 2785d88c1a5aSDimitry Andric bool BitcodeReaderBase::readBlockInfo() { 2786d88c1a5aSDimitry Andric Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock(); 2787d88c1a5aSDimitry Andric if (!NewBlockInfo) 2788d88c1a5aSDimitry Andric return true; 2789d88c1a5aSDimitry Andric BlockInfo = std::move(*NewBlockInfo); 2790d88c1a5aSDimitry Andric return false; 27917d523365SDimitry Andric } 27927d523365SDimitry Andric 27937a7e6055SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 27946bc11b14SDimitry Andric // v1: [selection_kind, name] 27956bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, selection_kind] 27966bc11b14SDimitry Andric StringRef Name; 27976bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 27986bc11b14SDimitry Andric 27992cab237bSDimitry Andric if (Record.empty()) 28007a7e6055SDimitry Andric return error("Invalid record"); 28017a7e6055SDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 28026bc11b14SDimitry Andric std::string OldFormatName; 28036bc11b14SDimitry Andric if (!UseStrtab) { 28046bc11b14SDimitry Andric if (Record.size() < 2) 28056bc11b14SDimitry Andric return error("Invalid record"); 28067a7e6055SDimitry Andric unsigned ComdatNameSize = Record[1]; 28076bc11b14SDimitry Andric OldFormatName.reserve(ComdatNameSize); 28087a7e6055SDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 28096bc11b14SDimitry Andric OldFormatName += (char)Record[2 + i]; 28106bc11b14SDimitry Andric Name = OldFormatName; 28116bc11b14SDimitry Andric } 28127a7e6055SDimitry Andric Comdat *C = TheModule->getOrInsertComdat(Name); 28137a7e6055SDimitry Andric C->setSelectionKind(SK); 28147a7e6055SDimitry Andric ComdatList.push_back(C); 28157a7e6055SDimitry Andric return Error::success(); 28167a7e6055SDimitry Andric } 28177a7e6055SDimitry Andric 28187a7e6055SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 28196bc11b14SDimitry Andric // v1: [pointer type, isconst, initid, linkage, alignment, section, 28207a7e6055SDimitry Andric // visibility, threadlocal, unnamed_addr, externally_initialized, 28212cab237bSDimitry Andric // dllstorageclass, comdat, attributes, preemption specifier] (name in VST) 28226bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 28236bc11b14SDimitry Andric StringRef Name; 28246bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 28256bc11b14SDimitry Andric 28267a7e6055SDimitry Andric if (Record.size() < 6) 28277a7e6055SDimitry Andric return error("Invalid record"); 28287a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]); 28297a7e6055SDimitry Andric if (!Ty) 28307a7e6055SDimitry Andric return error("Invalid record"); 28317a7e6055SDimitry Andric bool isConstant = Record[1] & 1; 28327a7e6055SDimitry Andric bool explicitType = Record[1] & 2; 28337a7e6055SDimitry Andric unsigned AddressSpace; 28347a7e6055SDimitry Andric if (explicitType) { 28357a7e6055SDimitry Andric AddressSpace = Record[1] >> 2; 28367a7e6055SDimitry Andric } else { 28377a7e6055SDimitry Andric if (!Ty->isPointerTy()) 28387a7e6055SDimitry Andric return error("Invalid type for value"); 28397a7e6055SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 28407a7e6055SDimitry Andric Ty = cast<PointerType>(Ty)->getElementType(); 28417a7e6055SDimitry Andric } 28427a7e6055SDimitry Andric 28437a7e6055SDimitry Andric uint64_t RawLinkage = Record[3]; 28447a7e6055SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 28457a7e6055SDimitry Andric unsigned Alignment; 28467a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[4], Alignment)) 28477a7e6055SDimitry Andric return Err; 28487a7e6055SDimitry Andric std::string Section; 28497a7e6055SDimitry Andric if (Record[5]) { 28507a7e6055SDimitry Andric if (Record[5] - 1 >= SectionTable.size()) 28517a7e6055SDimitry Andric return error("Invalid ID"); 28527a7e6055SDimitry Andric Section = SectionTable[Record[5] - 1]; 28537a7e6055SDimitry Andric } 28547a7e6055SDimitry Andric GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 28557a7e6055SDimitry Andric // Local linkage must have default visibility. 28567a7e6055SDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 28577a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 28587a7e6055SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 28597a7e6055SDimitry Andric 28607a7e6055SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 28617a7e6055SDimitry Andric if (Record.size() > 7) 28627a7e6055SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 28637a7e6055SDimitry Andric 28647a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 28657a7e6055SDimitry Andric if (Record.size() > 8) 28667a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 28677a7e6055SDimitry Andric 28687a7e6055SDimitry Andric bool ExternallyInitialized = false; 28697a7e6055SDimitry Andric if (Record.size() > 9) 28707a7e6055SDimitry Andric ExternallyInitialized = Record[9]; 28717a7e6055SDimitry Andric 28727a7e6055SDimitry Andric GlobalVariable *NewGV = 28736bc11b14SDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 28747a7e6055SDimitry Andric nullptr, TLM, AddressSpace, ExternallyInitialized); 28757a7e6055SDimitry Andric NewGV->setAlignment(Alignment); 28767a7e6055SDimitry Andric if (!Section.empty()) 28777a7e6055SDimitry Andric NewGV->setSection(Section); 28787a7e6055SDimitry Andric NewGV->setVisibility(Visibility); 28797a7e6055SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 28807a7e6055SDimitry Andric 28817a7e6055SDimitry Andric if (Record.size() > 10) 28827a7e6055SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 28837a7e6055SDimitry Andric else 28847a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 28857a7e6055SDimitry Andric 28867a7e6055SDimitry Andric ValueList.push_back(NewGV); 28877a7e6055SDimitry Andric 28887a7e6055SDimitry Andric // Remember which value to use for the global initializer. 28897a7e6055SDimitry Andric if (unsigned InitID = Record[2]) 28907a7e6055SDimitry Andric GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 28917a7e6055SDimitry Andric 28927a7e6055SDimitry Andric if (Record.size() > 11) { 28937a7e6055SDimitry Andric if (unsigned ComdatID = Record[11]) { 28947a7e6055SDimitry Andric if (ComdatID > ComdatList.size()) 28957a7e6055SDimitry Andric return error("Invalid global variable comdat ID"); 28967a7e6055SDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 28977a7e6055SDimitry Andric } 28987a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 28997a7e6055SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 29007a7e6055SDimitry Andric } 29015517e702SDimitry Andric 29025517e702SDimitry Andric if (Record.size() > 12) { 29035517e702SDimitry Andric auto AS = getAttributes(Record[12]).getFnAttributes(); 29045517e702SDimitry Andric NewGV->setAttributes(AS); 29055517e702SDimitry Andric } 29062cab237bSDimitry Andric 29072cab237bSDimitry Andric if (Record.size() > 13) { 29082cab237bSDimitry Andric NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); 29092cab237bSDimitry Andric } 29102cab237bSDimitry Andric 29117a7e6055SDimitry Andric return Error::success(); 29127a7e6055SDimitry Andric } 29137a7e6055SDimitry Andric 29147a7e6055SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 29156bc11b14SDimitry Andric // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 29167a7e6055SDimitry Andric // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 29172cab237bSDimitry Andric // prefixdata, personalityfn, preemption specifier] (name in VST) 29186bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 29196bc11b14SDimitry Andric StringRef Name; 29206bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 29216bc11b14SDimitry Andric 29227a7e6055SDimitry Andric if (Record.size() < 8) 29237a7e6055SDimitry Andric return error("Invalid record"); 29247a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]); 29257a7e6055SDimitry Andric if (!Ty) 29267a7e6055SDimitry Andric return error("Invalid record"); 29277a7e6055SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty)) 29287a7e6055SDimitry Andric Ty = PTy->getElementType(); 29297a7e6055SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty); 29307a7e6055SDimitry Andric if (!FTy) 29317a7e6055SDimitry Andric return error("Invalid type for value"); 29327a7e6055SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 29337a7e6055SDimitry Andric if (CC & ~CallingConv::MaxID) 29347a7e6055SDimitry Andric return error("Invalid calling convention ID"); 29357a7e6055SDimitry Andric 29367a7e6055SDimitry Andric Function *Func = 29376bc11b14SDimitry Andric Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule); 29387a7e6055SDimitry Andric 29397a7e6055SDimitry Andric Func->setCallingConv(CC); 29407a7e6055SDimitry Andric bool isProto = Record[2]; 29417a7e6055SDimitry Andric uint64_t RawLinkage = Record[3]; 29427a7e6055SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 29437a7e6055SDimitry Andric Func->setAttributes(getAttributes(Record[4])); 29447a7e6055SDimitry Andric 29457a7e6055SDimitry Andric unsigned Alignment; 29467a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[5], Alignment)) 29477a7e6055SDimitry Andric return Err; 29487a7e6055SDimitry Andric Func->setAlignment(Alignment); 29497a7e6055SDimitry Andric if (Record[6]) { 29507a7e6055SDimitry Andric if (Record[6] - 1 >= SectionTable.size()) 29517a7e6055SDimitry Andric return error("Invalid ID"); 29527a7e6055SDimitry Andric Func->setSection(SectionTable[Record[6] - 1]); 29537a7e6055SDimitry Andric } 29547a7e6055SDimitry Andric // Local linkage must have default visibility. 29557a7e6055SDimitry Andric if (!Func->hasLocalLinkage()) 29567a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 29577a7e6055SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 29587a7e6055SDimitry Andric if (Record.size() > 8 && Record[8]) { 29597a7e6055SDimitry Andric if (Record[8] - 1 >= GCTable.size()) 29607a7e6055SDimitry Andric return error("Invalid ID"); 29617a7e6055SDimitry Andric Func->setGC(GCTable[Record[8] - 1]); 29627a7e6055SDimitry Andric } 29637a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 29647a7e6055SDimitry Andric if (Record.size() > 9) 29657a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 29667a7e6055SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 29677a7e6055SDimitry Andric if (Record.size() > 10 && Record[10] != 0) 29687a7e6055SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1)); 29697a7e6055SDimitry Andric 29707a7e6055SDimitry Andric if (Record.size() > 11) 29717a7e6055SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 29727a7e6055SDimitry Andric else 29737a7e6055SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 29747a7e6055SDimitry Andric 29757a7e6055SDimitry Andric if (Record.size() > 12) { 29767a7e6055SDimitry Andric if (unsigned ComdatID = Record[12]) { 29777a7e6055SDimitry Andric if (ComdatID > ComdatList.size()) 29787a7e6055SDimitry Andric return error("Invalid function comdat ID"); 29797a7e6055SDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 29807a7e6055SDimitry Andric } 29817a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 29827a7e6055SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1)); 29837a7e6055SDimitry Andric } 29847a7e6055SDimitry Andric 29857a7e6055SDimitry Andric if (Record.size() > 13 && Record[13] != 0) 29867a7e6055SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1)); 29877a7e6055SDimitry Andric 29887a7e6055SDimitry Andric if (Record.size() > 14 && Record[14] != 0) 29897a7e6055SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 29907a7e6055SDimitry Andric 29912cab237bSDimitry Andric if (Record.size() > 15) { 29922cab237bSDimitry Andric Func->setDSOLocal(getDecodedDSOLocal(Record[15])); 29932cab237bSDimitry Andric } 29942cab237bSDimitry Andric 29957a7e6055SDimitry Andric ValueList.push_back(Func); 29967a7e6055SDimitry Andric 29977a7e6055SDimitry Andric // If this is a function with a body, remember the prototype we are 29987a7e6055SDimitry Andric // creating now, so that we can match up the body with them later. 29997a7e6055SDimitry Andric if (!isProto) { 30007a7e6055SDimitry Andric Func->setIsMaterializable(true); 30017a7e6055SDimitry Andric FunctionsWithBodies.push_back(Func); 30027a7e6055SDimitry Andric DeferredFunctionInfo[Func] = 0; 30037a7e6055SDimitry Andric } 30047a7e6055SDimitry Andric return Error::success(); 30057a7e6055SDimitry Andric } 30067a7e6055SDimitry Andric 30077a7e6055SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord( 30087a7e6055SDimitry Andric unsigned BitCode, ArrayRef<uint64_t> Record) { 30096bc11b14SDimitry Andric // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 30106bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 30112cab237bSDimitry Andric // dllstorageclass, threadlocal, unnamed_addr, 30122cab237bSDimitry Andric // preemption specifier] (name in VST) 30136bc11b14SDimitry Andric // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 30142cab237bSDimitry Andric // visibility, dllstorageclass, threadlocal, unnamed_addr, 30152cab237bSDimitry Andric // preemption specifier] (name in VST) 30166bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1] 30176bc11b14SDimitry Andric StringRef Name; 30186bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record); 30196bc11b14SDimitry Andric 30207a7e6055SDimitry Andric bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 30217a7e6055SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 30227a7e6055SDimitry Andric return error("Invalid record"); 30237a7e6055SDimitry Andric unsigned OpNum = 0; 30247a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]); 30257a7e6055SDimitry Andric if (!Ty) 30267a7e6055SDimitry Andric return error("Invalid record"); 30277a7e6055SDimitry Andric 30287a7e6055SDimitry Andric unsigned AddrSpace; 30297a7e6055SDimitry Andric if (!NewRecord) { 30307a7e6055SDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 30317a7e6055SDimitry Andric if (!PTy) 30327a7e6055SDimitry Andric return error("Invalid type for value"); 30337a7e6055SDimitry Andric Ty = PTy->getElementType(); 30347a7e6055SDimitry Andric AddrSpace = PTy->getAddressSpace(); 30357a7e6055SDimitry Andric } else { 30367a7e6055SDimitry Andric AddrSpace = Record[OpNum++]; 30377a7e6055SDimitry Andric } 30387a7e6055SDimitry Andric 30397a7e6055SDimitry Andric auto Val = Record[OpNum++]; 30407a7e6055SDimitry Andric auto Linkage = Record[OpNum++]; 30417a7e6055SDimitry Andric GlobalIndirectSymbol *NewGA; 30427a7e6055SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS || 30437a7e6055SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) 30446bc11b14SDimitry Andric NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 30457a7e6055SDimitry Andric TheModule); 30467a7e6055SDimitry Andric else 30476bc11b14SDimitry Andric NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 30487a7e6055SDimitry Andric nullptr, TheModule); 30497a7e6055SDimitry Andric // Old bitcode files didn't have visibility field. 30507a7e6055SDimitry Andric // Local linkage must have default visibility. 30517a7e6055SDimitry Andric if (OpNum != Record.size()) { 30527a7e6055SDimitry Andric auto VisInd = OpNum++; 30537a7e6055SDimitry Andric if (!NewGA->hasLocalLinkage()) 30547a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0. 30557a7e6055SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 30567a7e6055SDimitry Andric } 30577a7e6055SDimitry Andric if (OpNum != Record.size()) 30587a7e6055SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 30597a7e6055SDimitry Andric else 30607a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 30617a7e6055SDimitry Andric if (OpNum != Record.size()) 30627a7e6055SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 30637a7e6055SDimitry Andric if (OpNum != Record.size()) 30647a7e6055SDimitry Andric NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 30652cab237bSDimitry Andric if (OpNum != Record.size()) 30662cab237bSDimitry Andric NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); 30677a7e6055SDimitry Andric ValueList.push_back(NewGA); 30687a7e6055SDimitry Andric IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 30697a7e6055SDimitry Andric return Error::success(); 30707a7e6055SDimitry Andric } 30717a7e6055SDimitry Andric 3072d88c1a5aSDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit, 30737d523365SDimitry Andric bool ShouldLazyLoadMetadata) { 30747d523365SDimitry Andric if (ResumeBit) 30757d523365SDimitry Andric Stream.JumpToBit(ResumeBit); 3076dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 30778f0fd8f6SDimitry Andric return error("Invalid record"); 3078dff0c46cSDimitry Andric 3079dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record; 3080dff0c46cSDimitry Andric 3081dff0c46cSDimitry Andric // Read all the records for this module. 3082d88c1a5aSDimitry Andric while (true) { 3083139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3084dff0c46cSDimitry Andric 3085139f7f9bSDimitry Andric switch (Entry.Kind) { 3086139f7f9bSDimitry Andric case BitstreamEntry::Error: 30878f0fd8f6SDimitry Andric return error("Malformed block"); 3088139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 30898f0fd8f6SDimitry Andric return globalCleanup(); 3090dff0c46cSDimitry Andric 3091139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3092139f7f9bSDimitry Andric switch (Entry.ID) { 3093f22ef01cSRoman Divacky default: // Skip unknown content. 3094f22ef01cSRoman Divacky if (Stream.SkipBlock()) 30958f0fd8f6SDimitry Andric return error("Invalid record"); 3096f22ef01cSRoman Divacky break; 3097f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID: 3098d88c1a5aSDimitry Andric if (readBlockInfo()) 30998f0fd8f6SDimitry Andric return error("Malformed block"); 3100f22ef01cSRoman Divacky break; 3101f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID: 3102d88c1a5aSDimitry Andric if (Error Err = parseAttributeBlock()) 3103d88c1a5aSDimitry Andric return Err; 3104f22ef01cSRoman Divacky break; 3105139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 3106d88c1a5aSDimitry Andric if (Error Err = parseAttributeGroupBlock()) 3107d88c1a5aSDimitry Andric return Err; 3108139f7f9bSDimitry Andric break; 310917a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 3110d88c1a5aSDimitry Andric if (Error Err = parseTypeTable()) 3111d88c1a5aSDimitry Andric return Err; 3112f22ef01cSRoman Divacky break; 3113f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 31147d523365SDimitry Andric if (!SeenValueSymbolTable) { 31157d523365SDimitry Andric // Either this is an old form VST without function index and an 31167d523365SDimitry Andric // associated VST forward declaration record (which would have caused 31177d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered 31187d523365SDimitry Andric // normally in the stream), or there were no function blocks to 31197d523365SDimitry Andric // trigger an earlier parsing of the VST. 31207d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3121d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable()) 3122d88c1a5aSDimitry Andric return Err; 3123dff0c46cSDimitry Andric SeenValueSymbolTable = true; 31247d523365SDimitry Andric } else { 31257d523365SDimitry Andric // We must have had a VST forward declaration record, which caused 31267d523365SDimitry Andric // the parser to jump to and parse the VST earlier. 31277d523365SDimitry Andric assert(VSTOffset > 0); 31287d523365SDimitry Andric if (Stream.SkipBlock()) 31297d523365SDimitry Andric return error("Invalid record"); 31307d523365SDimitry Andric } 3131f22ef01cSRoman Divacky break; 3132f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 3133d88c1a5aSDimitry Andric if (Error Err = parseConstants()) 3134d88c1a5aSDimitry Andric return Err; 3135d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3136d88c1a5aSDimitry Andric return Err; 3137f22ef01cSRoman Divacky break; 3138f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3139d88c1a5aSDimitry Andric if (ShouldLazyLoadMetadata) { 3140d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipMetadata()) 3141d88c1a5aSDimitry Andric return Err; 3142ff0cc061SDimitry Andric break; 3143ff0cc061SDimitry Andric } 3144ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3145d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata()) 3146d88c1a5aSDimitry Andric return Err; 31477d523365SDimitry Andric break; 31487d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 3149d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataKinds()) 3150d88c1a5aSDimitry Andric return Err; 3151f22ef01cSRoman Divacky break; 3152f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID: 3153f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the 3154f22ef01cSRoman Divacky // FunctionsWithBodies list. 3155dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) { 3156f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3157d88c1a5aSDimitry Andric if (Error Err = globalCleanup()) 3158d88c1a5aSDimitry Andric return Err; 3159dff0c46cSDimitry Andric SeenFirstFunctionBody = true; 3160f22ef01cSRoman Divacky } 3161f22ef01cSRoman Divacky 31627d523365SDimitry Andric if (VSTOffset > 0) { 31637d523365SDimitry Andric // If we have a VST forward declaration record, make sure we 31647d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to 31657d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 31667d523365SDimitry Andric if (!SeenValueSymbolTable) { 3167d88c1a5aSDimitry Andric if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 3168d88c1a5aSDimitry Andric return Err; 31697d523365SDimitry Andric SeenValueSymbolTable = true; 31707d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below. 31717d523365SDimitry Andric // This is necessary in case we have an anonymous function that 31727d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we 31737d523365SDimitry Andric // need to fall back to the lazy parse to find its offset. 31747d523365SDimitry Andric } else { 31757d523365SDimitry Andric // If we have a VST forward declaration record, but have already 31767d523365SDimitry Andric // parsed the VST (just above, when the first function body was 31777d523365SDimitry Andric // encountered here), then we are resuming the parse after 31787d523365SDimitry Andric // materializing functions. The ResumeBit points to the 31797d523365SDimitry Andric // start of the last function block recorded in the 31807d523365SDimitry Andric // DeferredFunctionInfo map. Skip it. 31817d523365SDimitry Andric if (Stream.SkipBlock()) 31827d523365SDimitry Andric return error("Invalid record"); 31837d523365SDimitry Andric continue; 31847d523365SDimitry Andric } 31857d523365SDimitry Andric } 31867d523365SDimitry Andric 31877d523365SDimitry Andric // Support older bitcode files that did not have the function 31887d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as 31897d523365SDimitry Andric // well as anonymous functions that do not have VST entries. 31907d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 3191d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody()) 3192d88c1a5aSDimitry Andric return Err; 31937d523365SDimitry Andric 31943dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 31953dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode 31963dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not 31973dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now. 31983dac3a9bSDimitry Andric if (SeenValueSymbolTable) { 3199dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 3200d88c1a5aSDimitry Andric // After the VST has been parsed, we need to make sure intrinsic name 3201d88c1a5aSDimitry Andric // are auto-upgraded. 3202d88c1a5aSDimitry Andric return globalCleanup(); 3203dff0c46cSDimitry Andric } 3204dff0c46cSDimitry Andric break; 3205dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID: 3206d88c1a5aSDimitry Andric if (Error Err = parseUseLists()) 3207d88c1a5aSDimitry Andric return Err; 3208f22ef01cSRoman Divacky break; 32097d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 3210d88c1a5aSDimitry Andric if (Error Err = parseOperandBundleTags()) 3211d88c1a5aSDimitry Andric return Err; 32127d523365SDimitry Andric break; 3213c4394386SDimitry Andric case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 3214c4394386SDimitry Andric if (Error Err = parseSyncScopeNames()) 3215c4394386SDimitry Andric return Err; 3216c4394386SDimitry Andric break; 3217f22ef01cSRoman Divacky } 3218f22ef01cSRoman Divacky continue; 3219139f7f9bSDimitry Andric 3220139f7f9bSDimitry Andric case BitstreamEntry::Record: 3221139f7f9bSDimitry Andric // The interesting case. 3222139f7f9bSDimitry Andric break; 3223f22ef01cSRoman Divacky } 3224f22ef01cSRoman Divacky 3225f22ef01cSRoman Divacky // Read a record. 32267d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 32277d523365SDimitry Andric switch (BitCode) { 3228f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content. 32297a7e6055SDimitry Andric case bitc::MODULE_CODE_VERSION: { 32307a7e6055SDimitry Andric Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 32317a7e6055SDimitry Andric if (!VersionOrErr) 32327a7e6055SDimitry Andric return VersionOrErr.takeError(); 32337a7e6055SDimitry Andric UseRelativeIDs = *VersionOrErr >= 1; 32343861d79fSDimitry Andric break; 32353861d79fSDimitry Andric } 3236f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3237f22ef01cSRoman Divacky std::string S; 32388f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32398f0fd8f6SDimitry Andric return error("Invalid record"); 3240f22ef01cSRoman Divacky TheModule->setTargetTriple(S); 3241f22ef01cSRoman Divacky break; 3242f22ef01cSRoman Divacky } 3243f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3244f22ef01cSRoman Divacky std::string S; 32458f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32468f0fd8f6SDimitry Andric return error("Invalid record"); 3247f22ef01cSRoman Divacky TheModule->setDataLayout(S); 3248f22ef01cSRoman Divacky break; 3249f22ef01cSRoman Divacky } 3250f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3251f22ef01cSRoman Divacky std::string S; 32528f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32538f0fd8f6SDimitry Andric return error("Invalid record"); 3254f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S); 3255f22ef01cSRoman Divacky break; 3256f22ef01cSRoman Divacky } 3257f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3258139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 3259f22ef01cSRoman Divacky std::string S; 32608f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32618f0fd8f6SDimitry Andric return error("Invalid record"); 3262139f7f9bSDimitry Andric // Ignore value. 3263f22ef01cSRoman Divacky break; 3264f22ef01cSRoman Divacky } 3265f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3266f22ef01cSRoman Divacky std::string S; 32678f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32688f0fd8f6SDimitry Andric return error("Invalid record"); 3269f22ef01cSRoman Divacky SectionTable.push_back(S); 3270f22ef01cSRoman Divacky break; 3271f22ef01cSRoman Divacky } 3272f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3273f22ef01cSRoman Divacky std::string S; 32748f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 32758f0fd8f6SDimitry Andric return error("Invalid record"); 3276f22ef01cSRoman Divacky GCTable.push_back(S); 3277f22ef01cSRoman Divacky break; 3278f22ef01cSRoman Divacky } 32792cab237bSDimitry Andric case bitc::MODULE_CODE_COMDAT: 32807a7e6055SDimitry Andric if (Error Err = parseComdatRecord(Record)) 32817a7e6055SDimitry Andric return Err; 328291bc56edSDimitry Andric break; 32832cab237bSDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 32847a7e6055SDimitry Andric if (Error Err = parseGlobalVarRecord(Record)) 3285d88c1a5aSDimitry Andric return Err; 3286f22ef01cSRoman Divacky break; 32872cab237bSDimitry Andric case bitc::MODULE_CODE_FUNCTION: 32887a7e6055SDimitry Andric if (Error Err = parseFunctionRecord(Record)) 3289d88c1a5aSDimitry Andric return Err; 3290f22ef01cSRoman Divacky break; 32913ca95b02SDimitry Andric case bitc::MODULE_CODE_IFUNC: 32927d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS: 32932cab237bSDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: 32947a7e6055SDimitry Andric if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 32957a7e6055SDimitry Andric return Err; 3296f22ef01cSRoman Divacky break; 32977d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 32987d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 32997d523365SDimitry Andric if (Record.size() < 1) 33007d523365SDimitry Andric return error("Invalid record"); 3301d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one word 3302d88c1a5aSDimitry Andric // before the start of the identification or module block, which was 3303d88c1a5aSDimitry Andric // historically always the start of the regular bitcode header. 3304d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1; 33057d523365SDimitry Andric break; 33063ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 33073ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: 33083ca95b02SDimitry Andric SmallString<128> ValueName; 33093ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName)) 33107d523365SDimitry Andric return error("Invalid record"); 33113ca95b02SDimitry Andric TheModule->setSourceFileName(ValueName); 33127d523365SDimitry Andric break; 3313f22ef01cSRoman Divacky } 3314f22ef01cSRoman Divacky Record.clear(); 3315f22ef01cSRoman Divacky } 3316f22ef01cSRoman Divacky } 3317f22ef01cSRoman Divacky 3318d88c1a5aSDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 3319d88c1a5aSDimitry Andric bool IsImporting) { 33208f0fd8f6SDimitry Andric TheModule = M; 3321d88c1a5aSDimitry Andric MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, 3322d88c1a5aSDimitry Andric [&](unsigned ID) { return getTypeByID(ID); }); 33237d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata); 3324f22ef01cSRoman Divacky } 3325f22ef01cSRoman Divacky 3326d88c1a5aSDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 3327ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType)) 3328d88c1a5aSDimitry Andric return error("Load/Store operand is not a pointer type"); 3329ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3330ff0cc061SDimitry Andric 3331ff0cc061SDimitry Andric if (ValType && ValType != ElemType) 3332d88c1a5aSDimitry Andric return error("Explicit load/store type does not match pointee " 33337d523365SDimitry Andric "type of pointer operand"); 3334ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType)) 3335d88c1a5aSDimitry Andric return error("Cannot load/store from pointer"); 3336d88c1a5aSDimitry Andric return Error::success(); 3337ff0cc061SDimitry Andric } 3338ff0cc061SDimitry Andric 33398f0fd8f6SDimitry Andric /// Lazily parse the specified function body block. 3340d88c1a5aSDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) { 3341f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 33428f0fd8f6SDimitry Andric return error("Invalid record"); 3343f22ef01cSRoman Divacky 33443ca95b02SDimitry Andric // Unexpected unresolved metadata when parsing function. 3345d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs()) 33463ca95b02SDimitry Andric return error("Invalid function metadata: incoming forward references"); 33473ca95b02SDimitry Andric 3348f22ef01cSRoman Divacky InstructionList.clear(); 3349f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size(); 3350d88c1a5aSDimitry Andric unsigned ModuleMDLoaderSize = MDLoader->size(); 3351f22ef01cSRoman Divacky 3352f22ef01cSRoman Divacky // Add all the function arguments to the value table. 33537d523365SDimitry Andric for (Argument &I : F->args()) 33547d523365SDimitry Andric ValueList.push_back(&I); 3355f22ef01cSRoman Divacky 3356f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size(); 335791bc56edSDimitry Andric BasicBlock *CurBB = nullptr; 3358f22ef01cSRoman Divacky unsigned CurBBNo = 0; 3359f22ef01cSRoman Divacky 3360f22ef01cSRoman Divacky DebugLoc LastLoc; 336139d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 336239d628a0SDimitry Andric if (CurBB && !CurBB->empty()) 336339d628a0SDimitry Andric return &CurBB->back(); 336439d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 336539d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 336639d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 336739d628a0SDimitry Andric return nullptr; 336839d628a0SDimitry Andric }; 3369f22ef01cSRoman Divacky 33707d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 33717d523365SDimitry Andric 3372f22ef01cSRoman Divacky // Read all the records. 3373f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3374d88c1a5aSDimitry Andric 3375d88c1a5aSDimitry Andric while (true) { 3376139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3377f22ef01cSRoman Divacky 3378139f7f9bSDimitry Andric switch (Entry.Kind) { 3379139f7f9bSDimitry Andric case BitstreamEntry::Error: 33808f0fd8f6SDimitry Andric return error("Malformed block"); 3381139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 3382139f7f9bSDimitry Andric goto OutOfRecordLoop; 3383139f7f9bSDimitry Andric 3384139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3385139f7f9bSDimitry Andric switch (Entry.ID) { 3386f22ef01cSRoman Divacky default: // Skip unknown content. 3387f22ef01cSRoman Divacky if (Stream.SkipBlock()) 33888f0fd8f6SDimitry Andric return error("Invalid record"); 3389f22ef01cSRoman Divacky break; 3390f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 3391d88c1a5aSDimitry Andric if (Error Err = parseConstants()) 3392d88c1a5aSDimitry Andric return Err; 3393f22ef01cSRoman Divacky NextValueNo = ValueList.size(); 3394f22ef01cSRoman Divacky break; 3395f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 3396d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable()) 3397d88c1a5aSDimitry Andric return Err; 3398f22ef01cSRoman Divacky break; 3399f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID: 3400d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 3401d88c1a5aSDimitry Andric return Err; 3402f22ef01cSRoman Divacky break; 3403f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3404d88c1a5aSDimitry Andric assert(DeferredMetadataInfo.empty() && 3405d88c1a5aSDimitry Andric "Must read all module-level metadata before function-level"); 3406d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseFunctionMetadata()) 3407d88c1a5aSDimitry Andric return Err; 3408f22ef01cSRoman Divacky break; 340939d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID: 3410d88c1a5aSDimitry Andric if (Error Err = parseUseLists()) 3411d88c1a5aSDimitry Andric return Err; 341239d628a0SDimitry Andric break; 3413f22ef01cSRoman Divacky } 3414f22ef01cSRoman Divacky continue; 3415f22ef01cSRoman Divacky 3416139f7f9bSDimitry Andric case BitstreamEntry::Record: 3417139f7f9bSDimitry Andric // The interesting case. 3418139f7f9bSDimitry Andric break; 3419f22ef01cSRoman Divacky } 3420f22ef01cSRoman Divacky 3421f22ef01cSRoman Divacky // Read a record. 3422f22ef01cSRoman Divacky Record.clear(); 342391bc56edSDimitry Andric Instruction *I = nullptr; 3424139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3425f22ef01cSRoman Divacky switch (BitCode) { 3426f22ef01cSRoman Divacky default: // Default behavior: reject 34278f0fd8f6SDimitry Andric return error("Invalid value"); 342839d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 3429f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0) 34308f0fd8f6SDimitry Andric return error("Invalid record"); 3431f22ef01cSRoman Divacky // Create all the basic blocks for the function. 3432f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]); 343339d628a0SDimitry Andric 343439d628a0SDimitry Andric // See if anything took the address of blocks in this function. 343539d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 343639d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 3437f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 3438f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 343939d628a0SDimitry Andric } else { 344039d628a0SDimitry Andric auto &BBRefs = BBFRI->second; 344139d628a0SDimitry Andric // Check for invalid basic block references. 344239d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 34438f0fd8f6SDimitry Andric return error("Invalid ID"); 344439d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 344539d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 344639d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 344739d628a0SDimitry Andric ++I) 344839d628a0SDimitry Andric if (I < RE && BBRefs[I]) { 344939d628a0SDimitry Andric BBRefs[I]->insertInto(F); 345039d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I]; 345139d628a0SDimitry Andric } else { 345239d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 345339d628a0SDimitry Andric } 345439d628a0SDimitry Andric 345539d628a0SDimitry Andric // Erase from the table. 345639d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 345739d628a0SDimitry Andric } 345839d628a0SDimitry Andric 3459f22ef01cSRoman Divacky CurBB = FunctionBBs[0]; 3460f22ef01cSRoman Divacky continue; 346139d628a0SDimitry Andric } 3462f22ef01cSRoman Divacky 3463f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 3464f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same 3465f22ef01cSRoman Divacky // location as the previous instruction with a location. 346639d628a0SDimitry Andric I = getLastInstruction(); 3467f22ef01cSRoman Divacky 346891bc56edSDimitry Andric if (!I) 34698f0fd8f6SDimitry Andric return error("Invalid record"); 3470f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 347191bc56edSDimitry Andric I = nullptr; 3472f22ef01cSRoman Divacky continue; 3473f22ef01cSRoman Divacky 347417a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 347539d628a0SDimitry Andric I = getLastInstruction(); 347691bc56edSDimitry Andric if (!I || Record.size() < 4) 34778f0fd8f6SDimitry Andric return error("Invalid record"); 3478f22ef01cSRoman Divacky 3479f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1]; 3480f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3]; 3481f22ef01cSRoman Divacky 348291bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 34833ca95b02SDimitry Andric if (ScopeID) { 3484d88c1a5aSDimitry Andric Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1); 34853ca95b02SDimitry Andric if (!Scope) 34863ca95b02SDimitry Andric return error("Invalid record"); 34873ca95b02SDimitry Andric } 34883ca95b02SDimitry Andric if (IAID) { 3489d88c1a5aSDimitry Andric IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1); 34903ca95b02SDimitry Andric if (!IA) 34913ca95b02SDimitry Andric return error("Invalid record"); 34923ca95b02SDimitry Andric } 3493f22ef01cSRoman Divacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 3494f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 349591bc56edSDimitry Andric I = nullptr; 3496f22ef01cSRoman Divacky continue; 3497f22ef01cSRoman Divacky } 3498f22ef01cSRoman Divacky 3499f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 3500f22ef01cSRoman Divacky unsigned OpNum = 0; 3501f22ef01cSRoman Divacky Value *LHS, *RHS; 3502f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 35033861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 3504f22ef01cSRoman Divacky OpNum+1 > Record.size()) 35058f0fd8f6SDimitry Andric return error("Invalid record"); 3506f22ef01cSRoman Divacky 35078f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 3508f785676fSDimitry Andric if (Opc == -1) 35098f0fd8f6SDimitry Andric return error("Invalid record"); 3510f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 3511f22ef01cSRoman Divacky InstructionList.push_back(I); 3512f22ef01cSRoman Divacky if (OpNum < Record.size()) { 3513f22ef01cSRoman Divacky if (Opc == Instruction::Add || 3514f22ef01cSRoman Divacky Opc == Instruction::Sub || 35152754fe60SDimitry Andric Opc == Instruction::Mul || 35162754fe60SDimitry Andric Opc == Instruction::Shl) { 3517f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3518f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 3519f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3520f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 35212754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 35222754fe60SDimitry Andric Opc == Instruction::UDiv || 35232754fe60SDimitry Andric Opc == Instruction::LShr || 35242754fe60SDimitry Andric Opc == Instruction::AShr) { 35252754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 3526f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true); 3527139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) { 3528875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 3529139f7f9bSDimitry Andric if (FMF.any()) 3530139f7f9bSDimitry Andric I->setFastMathFlags(FMF); 3531f22ef01cSRoman Divacky } 3532139f7f9bSDimitry Andric 3533f22ef01cSRoman Divacky } 3534f22ef01cSRoman Divacky break; 3535f22ef01cSRoman Divacky } 3536f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 3537f22ef01cSRoman Divacky unsigned OpNum = 0; 3538f22ef01cSRoman Divacky Value *Op; 3539f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3540f22ef01cSRoman Divacky OpNum+2 != Record.size()) 35418f0fd8f6SDimitry Andric return error("Invalid record"); 3542f22ef01cSRoman Divacky 35436122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]); 35448f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 354591bc56edSDimitry Andric if (Opc == -1 || !ResTy) 35468f0fd8f6SDimitry Andric return error("Invalid record"); 354791bc56edSDimitry Andric Instruction *Temp = nullptr; 3548f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 3549f785676fSDimitry Andric if (Temp) { 3550f785676fSDimitry Andric InstructionList.push_back(Temp); 3551f785676fSDimitry Andric CurBB->getInstList().push_back(Temp); 3552f785676fSDimitry Andric } 3553f785676fSDimitry Andric } else { 35547d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 35557d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 35567d523365SDimitry Andric return error("Invalid cast"); 35577d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 3558f785676fSDimitry Andric } 3559f22ef01cSRoman Divacky InstructionList.push_back(I); 3560f22ef01cSRoman Divacky break; 3561f22ef01cSRoman Divacky } 3562ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 3563ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 3564ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 3565f22ef01cSRoman Divacky unsigned OpNum = 0; 3566ff0cc061SDimitry Andric 3567ff0cc061SDimitry Andric Type *Ty; 3568ff0cc061SDimitry Andric bool InBounds; 3569ff0cc061SDimitry Andric 3570ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 3571ff0cc061SDimitry Andric InBounds = Record[OpNum++]; 3572ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 3573ff0cc061SDimitry Andric } else { 3574ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 3575ff0cc061SDimitry Andric Ty = nullptr; 3576ff0cc061SDimitry Andric } 3577ff0cc061SDimitry Andric 3578f22ef01cSRoman Divacky Value *BasePtr; 3579f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 35808f0fd8f6SDimitry Andric return error("Invalid record"); 3581f22ef01cSRoman Divacky 3582ff0cc061SDimitry Andric if (!Ty) 3583d88c1a5aSDimitry Andric Ty = cast<PointerType>(BasePtr->getType()->getScalarType()) 3584ff0cc061SDimitry Andric ->getElementType(); 3585ff0cc061SDimitry Andric else if (Ty != 3586d88c1a5aSDimitry Andric cast<PointerType>(BasePtr->getType()->getScalarType()) 3587ff0cc061SDimitry Andric ->getElementType()) 35888f0fd8f6SDimitry Andric return error( 3589ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand"); 3590ff0cc061SDimitry Andric 3591f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx; 3592f22ef01cSRoman Divacky while (OpNum != Record.size()) { 3593f22ef01cSRoman Divacky Value *Op; 3594f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 35958f0fd8f6SDimitry Andric return error("Invalid record"); 3596f22ef01cSRoman Divacky GEPIdx.push_back(Op); 3597f22ef01cSRoman Divacky } 3598f22ef01cSRoman Divacky 3599ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 3600ff0cc061SDimitry Andric 3601f22ef01cSRoman Divacky InstructionList.push_back(I); 3602ff0cc061SDimitry Andric if (InBounds) 3603f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 3604f22ef01cSRoman Divacky break; 3605f22ef01cSRoman Divacky } 3606f22ef01cSRoman Divacky 3607f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: { 3608f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices] 3609f22ef01cSRoman Divacky unsigned OpNum = 0; 3610f22ef01cSRoman Divacky Value *Agg; 3611f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 36128f0fd8f6SDimitry Andric return error("Invalid record"); 3613f22ef01cSRoman Divacky 3614ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 3615ff0cc061SDimitry Andric if (OpNum == RecSize) 36168f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 3617ff0cc061SDimitry Andric 3618f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx; 3619ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 3620ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 3621ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 3622ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 3623f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 3624ff0cc061SDimitry Andric 3625ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 36268f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type"); 3627f22ef01cSRoman Divacky if ((unsigned)Index != Index) 36288f0fd8f6SDimitry Andric return error("Invalid value"); 3629ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 36308f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 3631ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 36328f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 3633f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index); 3634ff0cc061SDimitry Andric 3635ff0cc061SDimitry Andric if (IsStruct) 3636ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 3637ff0cc061SDimitry Andric else 3638ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 3639f22ef01cSRoman Divacky } 3640f22ef01cSRoman Divacky 364117a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 3642f22ef01cSRoman Divacky InstructionList.push_back(I); 3643f22ef01cSRoman Divacky break; 3644f22ef01cSRoman Divacky } 3645f22ef01cSRoman Divacky 3646f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: { 3647f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices] 3648f22ef01cSRoman Divacky unsigned OpNum = 0; 3649f22ef01cSRoman Divacky Value *Agg; 3650f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 36518f0fd8f6SDimitry Andric return error("Invalid record"); 3652f22ef01cSRoman Divacky Value *Val; 3653f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 36548f0fd8f6SDimitry Andric return error("Invalid record"); 3655f22ef01cSRoman Divacky 3656ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 3657ff0cc061SDimitry Andric if (OpNum == RecSize) 36588f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 3659ff0cc061SDimitry Andric 3660f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx; 3661ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 3662ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 3663ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 3664ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 3665f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 3666ff0cc061SDimitry Andric 3667ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 36688f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type"); 3669f22ef01cSRoman Divacky if ((unsigned)Index != Index) 36708f0fd8f6SDimitry Andric return error("Invalid value"); 3671ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 36728f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index"); 3673ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 36748f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index"); 3675ff0cc061SDimitry Andric 3676f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index); 3677ff0cc061SDimitry Andric if (IsStruct) 3678ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 3679ff0cc061SDimitry Andric else 3680ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 3681f22ef01cSRoman Divacky } 3682f22ef01cSRoman Divacky 3683ff0cc061SDimitry Andric if (CurTy != Val->getType()) 36848f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 3685ff0cc061SDimitry Andric 368617a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 3687f22ef01cSRoman Divacky InstructionList.push_back(I); 3688f22ef01cSRoman Divacky break; 3689f22ef01cSRoman Divacky } 3690f22ef01cSRoman Divacky 3691f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 3692f22ef01cSRoman Divacky // obsolete form of select 3693f22ef01cSRoman Divacky // handles select i1 ... in old bitcode 3694f22ef01cSRoman Divacky unsigned OpNum = 0; 3695f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 3696f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 36973861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 36983861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 36998f0fd8f6SDimitry Andric return error("Invalid record"); 3700f22ef01cSRoman Divacky 3701f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 3702f22ef01cSRoman Divacky InstructionList.push_back(I); 3703f22ef01cSRoman Divacky break; 3704f22ef01cSRoman Divacky } 3705f22ef01cSRoman Divacky 3706f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 3707f22ef01cSRoman Divacky // new form of select 3708f22ef01cSRoman Divacky // handles select i1 or select [N x i1] 3709f22ef01cSRoman Divacky unsigned OpNum = 0; 3710f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 3711f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 37123861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3713f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond)) 37148f0fd8f6SDimitry Andric return error("Invalid record"); 3715f22ef01cSRoman Divacky 3716f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1] 37176122f3e6SDimitry Andric if (VectorType* vector_type = 37186122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 3719f22ef01cSRoman Divacky // expect <n x i1> 3720f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 37218f0fd8f6SDimitry Andric return error("Invalid type for value"); 3722f22ef01cSRoman Divacky } else { 3723f22ef01cSRoman Divacky // expect i1 3724f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context)) 37258f0fd8f6SDimitry Andric return error("Invalid type for value"); 3726f22ef01cSRoman Divacky } 3727f22ef01cSRoman Divacky 3728f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 3729f22ef01cSRoman Divacky InstructionList.push_back(I); 3730f22ef01cSRoman Divacky break; 3731f22ef01cSRoman Divacky } 3732f22ef01cSRoman Divacky 3733f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 3734f22ef01cSRoman Divacky unsigned OpNum = 0; 3735f22ef01cSRoman Divacky Value *Vec, *Idx; 3736f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 373791bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 37388f0fd8f6SDimitry Andric return error("Invalid record"); 3739ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 37408f0fd8f6SDimitry Andric return error("Invalid type for value"); 3741f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx); 3742f22ef01cSRoman Divacky InstructionList.push_back(I); 3743f22ef01cSRoman Divacky break; 3744f22ef01cSRoman Divacky } 3745f22ef01cSRoman Divacky 3746f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 3747f22ef01cSRoman Divacky unsigned OpNum = 0; 3748f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx; 3749ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 37508f0fd8f6SDimitry Andric return error("Invalid record"); 3751ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 37528f0fd8f6SDimitry Andric return error("Invalid type for value"); 3753ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 3754f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) || 375591bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 37568f0fd8f6SDimitry Andric return error("Invalid record"); 3757f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx); 3758f22ef01cSRoman Divacky InstructionList.push_back(I); 3759f22ef01cSRoman Divacky break; 3760f22ef01cSRoman Divacky } 3761f22ef01cSRoman Divacky 3762f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 3763f22ef01cSRoman Divacky unsigned OpNum = 0; 3764f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask; 3765f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 37663861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 37678f0fd8f6SDimitry Andric return error("Invalid record"); 3768f22ef01cSRoman Divacky 3769f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 37708f0fd8f6SDimitry Andric return error("Invalid record"); 3771ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 37728f0fd8f6SDimitry Andric return error("Invalid type for value"); 3773f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask); 3774f22ef01cSRoman Divacky InstructionList.push_back(I); 3775f22ef01cSRoman Divacky break; 3776f22ef01cSRoman Divacky } 3777f22ef01cSRoman Divacky 3778f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 3779f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool 3780f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 3781f22ef01cSRoman Divacky // both legal on vectors but had different behaviour. 3782f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 3783f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool 3784f22ef01cSRoman Divacky 3785f22ef01cSRoman Divacky unsigned OpNum = 0; 3786f22ef01cSRoman Divacky Value *LHS, *RHS; 3787f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3788875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 3789875ed548SDimitry Andric return error("Invalid record"); 3790875ed548SDimitry Andric 3791875ed548SDimitry Andric unsigned PredVal = Record[OpNum]; 3792875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 3793875ed548SDimitry Andric FastMathFlags FMF; 3794875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1) 3795875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 3796875ed548SDimitry Andric 3797875ed548SDimitry Andric if (OpNum+1 != Record.size()) 37988f0fd8f6SDimitry Andric return error("Invalid record"); 3799f22ef01cSRoman Divacky 3800f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy()) 3801875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 3802f22ef01cSRoman Divacky else 3803875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 3804875ed548SDimitry Andric 3805875ed548SDimitry Andric if (FMF.any()) 3806875ed548SDimitry Andric I->setFastMathFlags(FMF); 3807f22ef01cSRoman Divacky InstructionList.push_back(I); 3808f22ef01cSRoman Divacky break; 3809f22ef01cSRoman Divacky } 3810f22ef01cSRoman Divacky 3811f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 3812f22ef01cSRoman Divacky { 3813f22ef01cSRoman Divacky unsigned Size = Record.size(); 3814f22ef01cSRoman Divacky if (Size == 0) { 3815f22ef01cSRoman Divacky I = ReturnInst::Create(Context); 3816f22ef01cSRoman Divacky InstructionList.push_back(I); 3817f22ef01cSRoman Divacky break; 3818f22ef01cSRoman Divacky } 3819f22ef01cSRoman Divacky 3820f22ef01cSRoman Divacky unsigned OpNum = 0; 382191bc56edSDimitry Andric Value *Op = nullptr; 3822f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 38238f0fd8f6SDimitry Andric return error("Invalid record"); 382417a519f9SDimitry Andric if (OpNum != Record.size()) 38258f0fd8f6SDimitry Andric return error("Invalid record"); 3826f22ef01cSRoman Divacky 382717a519f9SDimitry Andric I = ReturnInst::Create(Context, Op); 3828f22ef01cSRoman Divacky InstructionList.push_back(I); 3829f22ef01cSRoman Divacky break; 3830f22ef01cSRoman Divacky } 3831f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3832f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3) 38338f0fd8f6SDimitry Andric return error("Invalid record"); 3834f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]); 383591bc56edSDimitry Andric if (!TrueDest) 38368f0fd8f6SDimitry Andric return error("Invalid record"); 3837f22ef01cSRoman Divacky 3838f22ef01cSRoman Divacky if (Record.size() == 1) { 3839f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest); 3840f22ef01cSRoman Divacky InstructionList.push_back(I); 3841f22ef01cSRoman Divacky } 3842f22ef01cSRoman Divacky else { 3843f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]); 38443861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, 38453861d79fSDimitry Andric Type::getInt1Ty(Context)); 384691bc56edSDimitry Andric if (!FalseDest || !Cond) 38478f0fd8f6SDimitry Andric return error("Invalid record"); 3848f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond); 3849f22ef01cSRoman Divacky InstructionList.push_back(I); 3850f22ef01cSRoman Divacky } 3851f22ef01cSRoman Divacky break; 3852f22ef01cSRoman Divacky } 38537d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 38547d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 38557d523365SDimitry Andric return error("Invalid record"); 38567d523365SDimitry Andric unsigned Idx = 0; 38577d523365SDimitry Andric Value *CleanupPad = 38587d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38597d523365SDimitry Andric if (!CleanupPad) 38607d523365SDimitry Andric return error("Invalid record"); 38617d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 38627d523365SDimitry Andric if (Record.size() == 2) { 38637d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 38647d523365SDimitry Andric if (!UnwindDest) 38657d523365SDimitry Andric return error("Invalid record"); 38667d523365SDimitry Andric } 38677d523365SDimitry Andric 38687d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 38697d523365SDimitry Andric InstructionList.push_back(I); 38707d523365SDimitry Andric break; 38717d523365SDimitry Andric } 38727d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 38737d523365SDimitry Andric if (Record.size() != 2) 38747d523365SDimitry Andric return error("Invalid record"); 38757d523365SDimitry Andric unsigned Idx = 0; 38767d523365SDimitry Andric Value *CatchPad = 38777d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38787d523365SDimitry Andric if (!CatchPad) 38797d523365SDimitry Andric return error("Invalid record"); 38807d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 38817d523365SDimitry Andric if (!BB) 38827d523365SDimitry Andric return error("Invalid record"); 38837d523365SDimitry Andric 38847d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 38857d523365SDimitry Andric InstructionList.push_back(I); 38867d523365SDimitry Andric break; 38877d523365SDimitry Andric } 38887d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 38897d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 38907d523365SDimitry Andric if (Record.size() < 2) 38917d523365SDimitry Andric return error("Invalid record"); 38927d523365SDimitry Andric 38937d523365SDimitry Andric unsigned Idx = 0; 38947d523365SDimitry Andric 38957d523365SDimitry Andric Value *ParentPad = 38967d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 38977d523365SDimitry Andric 38987d523365SDimitry Andric unsigned NumHandlers = Record[Idx++]; 38997d523365SDimitry Andric 39007d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 39017d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 39027d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 39037d523365SDimitry Andric if (!BB) 39047d523365SDimitry Andric return error("Invalid record"); 39057d523365SDimitry Andric Handlers.push_back(BB); 39067d523365SDimitry Andric } 39077d523365SDimitry Andric 39087d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 39097d523365SDimitry Andric if (Idx + 1 == Record.size()) { 39107d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 39117d523365SDimitry Andric if (!UnwindDest) 39127d523365SDimitry Andric return error("Invalid record"); 39137d523365SDimitry Andric } 39147d523365SDimitry Andric 39157d523365SDimitry Andric if (Record.size() != Idx) 39167d523365SDimitry Andric return error("Invalid record"); 39177d523365SDimitry Andric 39187d523365SDimitry Andric auto *CatchSwitch = 39197d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 39207d523365SDimitry Andric for (BasicBlock *Handler : Handlers) 39217d523365SDimitry Andric CatchSwitch->addHandler(Handler); 39227d523365SDimitry Andric I = CatchSwitch; 39237d523365SDimitry Andric InstructionList.push_back(I); 39247d523365SDimitry Andric break; 39257d523365SDimitry Andric } 39267d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 39277d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 39287d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 39297d523365SDimitry Andric if (Record.size() < 2) 39307d523365SDimitry Andric return error("Invalid record"); 39317d523365SDimitry Andric 39327d523365SDimitry Andric unsigned Idx = 0; 39337d523365SDimitry Andric 39347d523365SDimitry Andric Value *ParentPad = 39357d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 39367d523365SDimitry Andric 39377d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 39387d523365SDimitry Andric 39397d523365SDimitry Andric SmallVector<Value *, 2> Args; 39407d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 39417d523365SDimitry Andric Value *Val; 39427d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 39437d523365SDimitry Andric return error("Invalid record"); 39447d523365SDimitry Andric Args.push_back(Val); 39457d523365SDimitry Andric } 39467d523365SDimitry Andric 39477d523365SDimitry Andric if (Record.size() != Idx) 39487d523365SDimitry Andric return error("Invalid record"); 39497d523365SDimitry Andric 39507d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 39517d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 39527d523365SDimitry Andric else 39537d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 39547d523365SDimitry Andric InstructionList.push_back(I); 39557d523365SDimitry Andric break; 39567d523365SDimitry Andric } 3957f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 39587ae0e2c9SDimitry Andric // Check magic 39597ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 3960f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 3961f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it. 3962f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use 3963f785676fSDimitry Andric // this format again. 39647ae0e2c9SDimitry Andric 39657ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 39667ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 39677ae0e2c9SDimitry Andric 39683861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 39697ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 397091bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 39718f0fd8f6SDimitry Andric return error("Invalid record"); 39727ae0e2c9SDimitry Andric 39737ae0e2c9SDimitry Andric unsigned NumCases = Record[4]; 39747ae0e2c9SDimitry Andric 39757ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 39767ae0e2c9SDimitry Andric InstructionList.push_back(SI); 39777ae0e2c9SDimitry Andric 39787ae0e2c9SDimitry Andric unsigned CurIdx = 5; 39797ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 3980f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 39817ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++]; 39827ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 39837ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 39847ae0e2c9SDimitry Andric 39857ae0e2c9SDimitry Andric APInt Low; 39867ae0e2c9SDimitry Andric unsigned ActiveWords = 1; 39877ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 39887ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 39898f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 39907ae0e2c9SDimitry Andric ValueBitWidth); 39917ae0e2c9SDimitry Andric CurIdx += ActiveWords; 39927ae0e2c9SDimitry Andric 39937ae0e2c9SDimitry Andric if (!isSingleNumber) { 39947ae0e2c9SDimitry Andric ActiveWords = 1; 39957ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 39967ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 39978f0fd8f6SDimitry Andric APInt High = readWideAPInt( 39988f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 39997ae0e2c9SDimitry Andric CurIdx += ActiveWords; 4000f785676fSDimitry Andric 4001f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be 4002f785676fSDimitry Andric // compared as signed or unsigned values. The partially 4003f785676fSDimitry Andric // implemented changes that used this format in the past used 4004f785676fSDimitry Andric // unsigned comparisons. 4005f785676fSDimitry Andric for ( ; Low.ule(High); ++Low) 4006f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 40077ae0e2c9SDimitry Andric } else 4008f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 40097ae0e2c9SDimitry Andric } 40107ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4011f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4012f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi) 4013f785676fSDimitry Andric SI->addCase(*cvi, DestBB); 40147ae0e2c9SDimitry Andric } 40157ae0e2c9SDimitry Andric I = SI; 40167ae0e2c9SDimitry Andric break; 40177ae0e2c9SDimitry Andric } 40187ae0e2c9SDimitry Andric 40197ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges. 40207ae0e2c9SDimitry Andric 4021f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0) 40228f0fd8f6SDimitry Andric return error("Invalid record"); 40236122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 40243861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4025f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]); 402691bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 40278f0fd8f6SDimitry Andric return error("Invalid record"); 4028f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2; 4029f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4030f22ef01cSRoman Divacky InstructionList.push_back(SI); 4031f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) { 4032f22ef01cSRoman Divacky ConstantInt *CaseVal = 4033f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4034f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 403591bc56edSDimitry Andric if (!CaseVal || !DestBB) { 4036f22ef01cSRoman Divacky delete SI; 40378f0fd8f6SDimitry Andric return error("Invalid record"); 4038f22ef01cSRoman Divacky } 4039f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB); 4040f22ef01cSRoman Divacky } 4041f22ef01cSRoman Divacky I = SI; 4042f22ef01cSRoman Divacky break; 4043f22ef01cSRoman Divacky } 4044f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4045f22ef01cSRoman Divacky if (Record.size() < 2) 40468f0fd8f6SDimitry Andric return error("Invalid record"); 40476122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 40483861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy); 404991bc56edSDimitry Andric if (!OpTy || !Address) 40508f0fd8f6SDimitry Andric return error("Invalid record"); 4051f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2; 4052f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4053f22ef01cSRoman Divacky InstructionList.push_back(IBI); 4054f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 4055f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4056f22ef01cSRoman Divacky IBI->addDestination(DestBB); 4057f22ef01cSRoman Divacky } else { 4058f22ef01cSRoman Divacky delete IBI; 40598f0fd8f6SDimitry Andric return error("Invalid record"); 4060f22ef01cSRoman Divacky } 4061f22ef01cSRoman Divacky } 4062f22ef01cSRoman Divacky I = IBI; 4063f22ef01cSRoman Divacky break; 4064f22ef01cSRoman Divacky } 4065f22ef01cSRoman Divacky 4066f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: { 4067f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4068f785676fSDimitry Andric if (Record.size() < 4) 40698f0fd8f6SDimitry Andric return error("Invalid record"); 4070ff0cc061SDimitry Andric unsigned OpNum = 0; 40717a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 4072ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4073ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4074ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4075f22ef01cSRoman Divacky 4076ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 4077ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 && 4078ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 40798f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type"); 4080ff0cc061SDimitry Andric 4081f22ef01cSRoman Divacky Value *Callee; 4082f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 40838f0fd8f6SDimitry Andric return error("Invalid record"); 4084f22ef01cSRoman Divacky 40856122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4086ff0cc061SDimitry Andric if (!CalleeTy) 40878f0fd8f6SDimitry Andric return error("Callee is not a pointer"); 4088ff0cc061SDimitry Andric if (!FTy) { 4089ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4090ff0cc061SDimitry Andric if (!FTy) 40918f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4092ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy) 40938f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of " 4094ff0cc061SDimitry Andric "callee operand"); 4095ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 40968f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4097f22ef01cSRoman Divacky 4098f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops; 4099f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 41003861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, 41013861d79fSDimitry Andric FTy->getParamType(i))); 410291bc56edSDimitry Andric if (!Ops.back()) 41038f0fd8f6SDimitry Andric return error("Invalid record"); 4104f22ef01cSRoman Divacky } 4105f22ef01cSRoman Divacky 4106f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4107f22ef01cSRoman Divacky if (Record.size() != OpNum) 41088f0fd8f6SDimitry Andric return error("Invalid record"); 4109f22ef01cSRoman Divacky } else { 4110f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4111f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4112f22ef01cSRoman Divacky Value *Op; 4113f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 41148f0fd8f6SDimitry Andric return error("Invalid record"); 4115f22ef01cSRoman Divacky Ops.push_back(Op); 4116f22ef01cSRoman Divacky } 4117f22ef01cSRoman Divacky } 4118f22ef01cSRoman Divacky 41197d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 41207d523365SDimitry Andric OperandBundles.clear(); 4121f22ef01cSRoman Divacky InstructionList.push_back(I); 41227d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 41237d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4124f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL); 4125f22ef01cSRoman Divacky break; 4126f22ef01cSRoman Divacky } 41276122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 41286122f3e6SDimitry Andric unsigned Idx = 0; 412991bc56edSDimitry Andric Value *Val = nullptr; 41306122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 41318f0fd8f6SDimitry Andric return error("Invalid record"); 41326122f3e6SDimitry Andric I = ResumeInst::Create(Val); 41336122f3e6SDimitry Andric InstructionList.push_back(I); 41346122f3e6SDimitry Andric break; 41356122f3e6SDimitry Andric } 4136f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4137f22ef01cSRoman Divacky I = new UnreachableInst(Context); 4138f22ef01cSRoman Divacky InstructionList.push_back(I); 4139f22ef01cSRoman Divacky break; 4140f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4141f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1)) 41428f0fd8f6SDimitry Andric return error("Invalid record"); 41436122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4144f785676fSDimitry Andric if (!Ty) 41458f0fd8f6SDimitry Andric return error("Invalid record"); 4146f22ef01cSRoman Divacky 41473b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4148f22ef01cSRoman Divacky InstructionList.push_back(PN); 4149f22ef01cSRoman Divacky 4150f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 41513861d79fSDimitry Andric Value *V; 41523861d79fSDimitry Andric // With the new function encoding, it is possible that operands have 41533861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR 41543861d79fSDimitry Andric // representation to keep the encoding small. 41553861d79fSDimitry Andric if (UseRelativeIDs) 41563861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty); 41573861d79fSDimitry Andric else 41583861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty); 4159f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]); 4160f785676fSDimitry Andric if (!V || !BB) 41618f0fd8f6SDimitry Andric return error("Invalid record"); 4162f22ef01cSRoman Divacky PN->addIncoming(V, BB); 4163f22ef01cSRoman Divacky } 4164f22ef01cSRoman Divacky I = PN; 4165f22ef01cSRoman Divacky break; 4166f22ef01cSRoman Divacky } 4167f22ef01cSRoman Divacky 41688f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 41698f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 41706122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 41716122f3e6SDimitry Andric unsigned Idx = 0; 41728f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 41738f0fd8f6SDimitry Andric if (Record.size() < 3) 41748f0fd8f6SDimitry Andric return error("Invalid record"); 41758f0fd8f6SDimitry Andric } else { 41768f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 41776122f3e6SDimitry Andric if (Record.size() < 4) 41788f0fd8f6SDimitry Andric return error("Invalid record"); 41798f0fd8f6SDimitry Andric } 41806122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]); 4181f785676fSDimitry Andric if (!Ty) 41828f0fd8f6SDimitry Andric return error("Invalid record"); 41838f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 418491bc56edSDimitry Andric Value *PersFn = nullptr; 41856122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 41868f0fd8f6SDimitry Andric return error("Invalid record"); 41878f0fd8f6SDimitry Andric 41888f0fd8f6SDimitry Andric if (!F->hasPersonalityFn()) 41898f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 41908f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 41918f0fd8f6SDimitry Andric return error("Personality function mismatch"); 41928f0fd8f6SDimitry Andric } 41936122f3e6SDimitry Andric 41946122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++]; 41956122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++]; 41968f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 41976122f3e6SDimitry Andric LP->setCleanup(IsCleanup); 41986122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 41996122f3e6SDimitry Andric LandingPadInst::ClauseType CT = 42006122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 42016122f3e6SDimitry Andric Value *Val; 42026122f3e6SDimitry Andric 42036122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 42046122f3e6SDimitry Andric delete LP; 42058f0fd8f6SDimitry Andric return error("Invalid record"); 42066122f3e6SDimitry Andric } 42076122f3e6SDimitry Andric 42086122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch || 42096122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) && 42106122f3e6SDimitry Andric "Catch clause has a invalid type!"); 42116122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter || 42126122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) && 42136122f3e6SDimitry Andric "Filter clause has invalid type!"); 421491bc56edSDimitry Andric LP->addClause(cast<Constant>(Val)); 42156122f3e6SDimitry Andric } 42166122f3e6SDimitry Andric 42176122f3e6SDimitry Andric I = LP; 42186122f3e6SDimitry Andric InstructionList.push_back(I); 42196122f3e6SDimitry Andric break; 42206122f3e6SDimitry Andric } 42216122f3e6SDimitry Andric 422217a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 422317a519f9SDimitry Andric if (Record.size() != 4) 42248f0fd8f6SDimitry Andric return error("Invalid record"); 4225ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3]; 4226ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5; 4227ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 42283ca95b02SDimitry Andric const uint64_t SwiftErrorMask = uint64_t(1) << 7; 42293ca95b02SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 42303ca95b02SDimitry Andric SwiftErrorMask; 4231ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask; 42323ca95b02SDimitry Andric bool SwiftError = AlignRecord & SwiftErrorMask; 4233ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4234ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) { 4235ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4236ff0cc061SDimitry Andric if (!PTy) 42378f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type"); 4238ff0cc061SDimitry Andric Ty = PTy->getElementType(); 4239ff0cc061SDimitry Andric } 42406122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 424117a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy); 4242ff0cc061SDimitry Andric unsigned Align; 4243d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4244d88c1a5aSDimitry Andric return Err; 4245ff0cc061SDimitry Andric } 4246f785676fSDimitry Andric if (!Ty || !Size) 42478f0fd8f6SDimitry Andric return error("Invalid record"); 42487a7e6055SDimitry Andric 42497a7e6055SDimitry Andric // FIXME: Make this an optional field. 42507a7e6055SDimitry Andric const DataLayout &DL = TheModule->getDataLayout(); 42517a7e6055SDimitry Andric unsigned AS = DL.getAllocaAddrSpace(); 42527a7e6055SDimitry Andric 42537a7e6055SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align); 425491bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca); 42553ca95b02SDimitry Andric AI->setSwiftError(SwiftError); 425691bc56edSDimitry Andric I = AI; 4257f22ef01cSRoman Divacky InstructionList.push_back(I); 4258f22ef01cSRoman Divacky break; 4259f22ef01cSRoman Divacky } 4260f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4261f22ef01cSRoman Divacky unsigned OpNum = 0; 4262f22ef01cSRoman Divacky Value *Op; 4263f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4264ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 42658f0fd8f6SDimitry Andric return error("Invalid record"); 4266f22ef01cSRoman Divacky 4267ff0cc061SDimitry Andric Type *Ty = nullptr; 4268ff0cc061SDimitry Andric if (OpNum + 3 == Record.size()) 4269ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4270d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4271d88c1a5aSDimitry Andric return Err; 4272ff0cc061SDimitry Andric if (!Ty) 4273ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4274ff0cc061SDimitry Andric 4275ff0cc061SDimitry Andric unsigned Align; 4276d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4277d88c1a5aSDimitry Andric return Err; 4278ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4279ff0cc061SDimitry Andric 4280f22ef01cSRoman Divacky InstructionList.push_back(I); 4281f22ef01cSRoman Divacky break; 4282f22ef01cSRoman Divacky } 42836122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 4284c4394386SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 42856122f3e6SDimitry Andric unsigned OpNum = 0; 42866122f3e6SDimitry Andric Value *Op; 42876122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4288ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 42898f0fd8f6SDimitry Andric return error("Invalid record"); 42906122f3e6SDimitry Andric 4291ff0cc061SDimitry Andric Type *Ty = nullptr; 4292ff0cc061SDimitry Andric if (OpNum + 5 == Record.size()) 4293ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4294d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4295d88c1a5aSDimitry Andric return Err; 4296ff0cc061SDimitry Andric if (!Ty) 4297ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4298ff0cc061SDimitry Andric 42998f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 43003ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 43013ca95b02SDimitry Andric Ordering == AtomicOrdering::Release || 43023ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 43038f0fd8f6SDimitry Andric return error("Invalid record"); 43043ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 43058f0fd8f6SDimitry Andric return error("Invalid record"); 4306c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 43076122f3e6SDimitry Andric 4308ff0cc061SDimitry Andric unsigned Align; 4309d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4310d88c1a5aSDimitry Andric return Err; 4311c4394386SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID); 4312ff0cc061SDimitry Andric 43136122f3e6SDimitry Andric InstructionList.push_back(I); 43146122f3e6SDimitry Andric break; 43156122f3e6SDimitry Andric } 4316ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 4317ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4318f22ef01cSRoman Divacky unsigned OpNum = 0; 4319f22ef01cSRoman Divacky Value *Val, *Ptr; 4320f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4321ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE 4322ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4323ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4324ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4325ff0cc061SDimitry Andric Val)) || 4326f22ef01cSRoman Divacky OpNum + 2 != Record.size()) 43278f0fd8f6SDimitry Andric return error("Invalid record"); 4328f22ef01cSRoman Divacky 4329d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4330d88c1a5aSDimitry Andric return Err; 4331ff0cc061SDimitry Andric unsigned Align; 4332d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4333d88c1a5aSDimitry Andric return Err; 4334ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4335f22ef01cSRoman Divacky InstructionList.push_back(I); 4336f22ef01cSRoman Divacky break; 4337f22ef01cSRoman Divacky } 4338ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 4339ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 4340c4394386SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 43416122f3e6SDimitry Andric unsigned OpNum = 0; 43426122f3e6SDimitry Andric Value *Val, *Ptr; 43436122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 43443ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) || 4345ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4346ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4347ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4348ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4349ff0cc061SDimitry Andric Val)) || 43506122f3e6SDimitry Andric OpNum + 4 != Record.size()) 43518f0fd8f6SDimitry Andric return error("Invalid record"); 43526122f3e6SDimitry Andric 4353d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4354d88c1a5aSDimitry Andric return Err; 43558f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 43563ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 43573ca95b02SDimitry Andric Ordering == AtomicOrdering::Acquire || 43583ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease) 43598f0fd8f6SDimitry Andric return error("Invalid record"); 4360c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 43613ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 43628f0fd8f6SDimitry Andric return error("Invalid record"); 43636122f3e6SDimitry Andric 4364ff0cc061SDimitry Andric unsigned Align; 4365d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4366d88c1a5aSDimitry Andric return Err; 4367c4394386SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID); 43686122f3e6SDimitry Andric InstructionList.push_back(I); 43696122f3e6SDimitry Andric break; 43706122f3e6SDimitry Andric } 4371ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 43726122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 4373c4394386SDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid, 437491bc56edSDimitry Andric // failureordering?, isweak?] 43756122f3e6SDimitry Andric unsigned OpNum = 0; 43766122f3e6SDimitry Andric Value *Ptr, *Cmp, *New; 43776122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4378ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4379ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4380ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4381ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4382ff0cc061SDimitry Andric Cmp)) || 4383ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4384ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 43858f0fd8f6SDimitry Andric return error("Invalid record"); 43868f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 43873ca95b02SDimitry Andric if (SuccessOrdering == AtomicOrdering::NotAtomic || 43883ca95b02SDimitry Andric SuccessOrdering == AtomicOrdering::Unordered) 43898f0fd8f6SDimitry Andric return error("Invalid record"); 4390c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 439191bc56edSDimitry Andric 4392d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4393d88c1a5aSDimitry Andric return Err; 439491bc56edSDimitry Andric AtomicOrdering FailureOrdering; 439591bc56edSDimitry Andric if (Record.size() < 7) 439691bc56edSDimitry Andric FailureOrdering = 439791bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 439891bc56edSDimitry Andric else 43998f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 440091bc56edSDimitry Andric 440191bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 4402c4394386SDimitry Andric SSID); 44036122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 440491bc56edSDimitry Andric 440591bc56edSDimitry Andric if (Record.size() < 8) { 440691bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 440791bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be 440891bc56edSDimitry Andric // expecting the first component of a modern cmpxchg. 440991bc56edSDimitry Andric CurBB->getInstList().push_back(I); 441091bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0); 441191bc56edSDimitry Andric } else { 441291bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 441391bc56edSDimitry Andric } 441491bc56edSDimitry Andric 44156122f3e6SDimitry Andric InstructionList.push_back(I); 44166122f3e6SDimitry Andric break; 44176122f3e6SDimitry Andric } 44186122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 4419c4394386SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid] 44206122f3e6SDimitry Andric unsigned OpNum = 0; 44216122f3e6SDimitry Andric Value *Ptr, *Val; 44226122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 44233ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) || 44243861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, 44256122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) || 44266122f3e6SDimitry Andric OpNum+4 != Record.size()) 44278f0fd8f6SDimitry Andric return error("Invalid record"); 44288f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 44296122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 44306122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 44318f0fd8f6SDimitry Andric return error("Invalid record"); 44328f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 44333ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 44343ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered) 44358f0fd8f6SDimitry Andric return error("Invalid record"); 4436c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 4437c4394386SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); 44386122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 44396122f3e6SDimitry Andric InstructionList.push_back(I); 44406122f3e6SDimitry Andric break; 44416122f3e6SDimitry Andric } 4442c4394386SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 44436122f3e6SDimitry Andric if (2 != Record.size()) 44448f0fd8f6SDimitry Andric return error("Invalid record"); 44458f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 44463ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic || 44473ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered || 44483ca95b02SDimitry Andric Ordering == AtomicOrdering::Monotonic) 44498f0fd8f6SDimitry Andric return error("Invalid record"); 4450c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 4451c4394386SDimitry Andric I = new FenceInst(Context, Ordering, SSID); 44526122f3e6SDimitry Andric InstructionList.push_back(I); 44536122f3e6SDimitry Andric break; 44546122f3e6SDimitry Andric } 445517a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 44567d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 4457f22ef01cSRoman Divacky if (Record.size() < 3) 44588f0fd8f6SDimitry Andric return error("Invalid record"); 4459f22ef01cSRoman Divacky 4460ff0cc061SDimitry Andric unsigned OpNum = 0; 44617a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]); 4462ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4463f22ef01cSRoman Divacky 44647d523365SDimitry Andric FastMathFlags FMF; 44657d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 44667d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 44677d523365SDimitry Andric if (!FMF.any()) 44687d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 44697d523365SDimitry Andric } 44707d523365SDimitry Andric 4471ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 44727d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 4473ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 44748f0fd8f6SDimitry Andric return error("Explicit call type is not a function type"); 4475ff0cc061SDimitry Andric 4476f22ef01cSRoman Divacky Value *Callee; 4477f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 44788f0fd8f6SDimitry Andric return error("Invalid record"); 4479f22ef01cSRoman Divacky 44806122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 4481ff0cc061SDimitry Andric if (!OpTy) 44828f0fd8f6SDimitry Andric return error("Callee is not a pointer type"); 4483ff0cc061SDimitry Andric if (!FTy) { 4484ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 4485ff0cc061SDimitry Andric if (!FTy) 44868f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4487ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy) 44888f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of " 4489ff0cc061SDimitry Andric "callee operand"); 4490ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 44918f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4492f22ef01cSRoman Divacky 4493f22ef01cSRoman Divacky SmallVector<Value*, 16> Args; 4494f22ef01cSRoman Divacky // Read the fixed params. 4495f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 449617a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 4497f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum])); 4498f22ef01cSRoman Divacky else 44993861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 45003861d79fSDimitry Andric FTy->getParamType(i))); 450191bc56edSDimitry Andric if (!Args.back()) 45028f0fd8f6SDimitry Andric return error("Invalid record"); 4503f22ef01cSRoman Divacky } 4504f22ef01cSRoman Divacky 4505f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4506f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4507f22ef01cSRoman Divacky if (OpNum != Record.size()) 45088f0fd8f6SDimitry Andric return error("Invalid record"); 4509f22ef01cSRoman Divacky } else { 4510f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4511f22ef01cSRoman Divacky Value *Op; 4512f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 45138f0fd8f6SDimitry Andric return error("Invalid record"); 4514f22ef01cSRoman Divacky Args.push_back(Op); 4515f22ef01cSRoman Divacky } 4516f22ef01cSRoman Divacky } 4517f22ef01cSRoman Divacky 45187d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 45197d523365SDimitry Andric OperandBundles.clear(); 4520f22ef01cSRoman Divacky InstructionList.push_back(I); 4521f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv( 45227d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 452391bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 45247d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 452591bc56edSDimitry Andric TCK = CallInst::TCK_Tail; 45267d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 452791bc56edSDimitry Andric TCK = CallInst::TCK_MustTail; 45287d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 45297d523365SDimitry Andric TCK = CallInst::TCK_NoTail; 453091bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 4531f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL); 45327d523365SDimitry Andric if (FMF.any()) { 45337d523365SDimitry Andric if (!isa<FPMathOperator>(I)) 45347d523365SDimitry Andric return error("Fast-math-flags specified for call without " 45357d523365SDimitry Andric "floating-point scalar or vector return type"); 45367d523365SDimitry Andric I->setFastMathFlags(FMF); 45377d523365SDimitry Andric } 4538f22ef01cSRoman Divacky break; 4539f22ef01cSRoman Divacky } 4540f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 4541f22ef01cSRoman Divacky if (Record.size() < 3) 45428f0fd8f6SDimitry Andric return error("Invalid record"); 45436122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 45443861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy); 45456122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]); 4546f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy) 45478f0fd8f6SDimitry Andric return error("Invalid record"); 4548f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy); 4549f22ef01cSRoman Divacky InstructionList.push_back(I); 4550f22ef01cSRoman Divacky break; 4551f22ef01cSRoman Divacky } 45527d523365SDimitry Andric 45537d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 45547d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 45557d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into 45567d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 45577d523365SDimitry Andric 45587d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size()) 45597d523365SDimitry Andric return error("Invalid record"); 45607d523365SDimitry Andric 45617d523365SDimitry Andric std::vector<Value *> Inputs; 45627d523365SDimitry Andric 45637d523365SDimitry Andric unsigned OpNum = 1; 45647d523365SDimitry Andric while (OpNum != Record.size()) { 45657d523365SDimitry Andric Value *Op; 45667d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 45677d523365SDimitry Andric return error("Invalid record"); 45687d523365SDimitry Andric Inputs.push_back(Op); 45697d523365SDimitry Andric } 45707d523365SDimitry Andric 45717d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 45727d523365SDimitry Andric continue; 45737d523365SDimitry Andric } 4574f22ef01cSRoman Divacky } 4575f22ef01cSRoman Divacky 4576f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject 4577f22ef01cSRoman Divacky // this file. 457891bc56edSDimitry Andric if (!CurBB) { 4579d8866befSDimitry Andric I->deleteValue(); 45808f0fd8f6SDimitry Andric return error("Invalid instruction with no BB"); 4581f22ef01cSRoman Divacky } 45827d523365SDimitry Andric if (!OperandBundles.empty()) { 4583d8866befSDimitry Andric I->deleteValue(); 45847d523365SDimitry Andric return error("Operand bundles found with no consumer"); 45857d523365SDimitry Andric } 4586f22ef01cSRoman Divacky CurBB->getInstList().push_back(I); 4587f22ef01cSRoman Divacky 4588f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block. 4589f22ef01cSRoman Divacky if (isa<TerminatorInst>(I)) { 4590f22ef01cSRoman Divacky ++CurBBNo; 459191bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 4592f22ef01cSRoman Divacky } 4593f22ef01cSRoman Divacky 4594f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use. 4595f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy()) 45968f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++); 4597f22ef01cSRoman Divacky } 4598f22ef01cSRoman Divacky 4599139f7f9bSDimitry Andric OutOfRecordLoop: 4600139f7f9bSDimitry Andric 46017d523365SDimitry Andric if (!OperandBundles.empty()) 46027d523365SDimitry Andric return error("Operand bundles found with no consumer"); 46037d523365SDimitry Andric 4604f22ef01cSRoman Divacky // Check the function list for unresolved values. 4605f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 460691bc56edSDimitry Andric if (!A->getParent()) { 4607f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks. 4608f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 460991bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 4610f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType())); 4611f22ef01cSRoman Divacky delete A; 4612f22ef01cSRoman Divacky } 4613f22ef01cSRoman Divacky } 46148f0fd8f6SDimitry Andric return error("Never resolved value found in function"); 4615f22ef01cSRoman Divacky } 4616f22ef01cSRoman Divacky } 4617f22ef01cSRoman Divacky 46183ca95b02SDimitry Andric // Unexpected unresolved metadata about to be dropped. 4619d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs()) 46203ca95b02SDimitry Andric return error("Invalid function metadata: outgoing forward refs"); 4621e580952dSDimitry Andric 4622f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function. 4623f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize); 4624d88c1a5aSDimitry Andric MDLoader->shrinkTo(ModuleMDLoaderSize); 4625f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 4626d88c1a5aSDimitry Andric return Error::success(); 4627f22ef01cSRoman Divacky } 4628f22ef01cSRoman Divacky 4629f785676fSDimitry Andric /// Find the function body in the bitcode stream 4630d88c1a5aSDimitry Andric Error BitcodeReader::findFunctionInStream( 463191bc56edSDimitry Andric Function *F, 4632dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 4633dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 46347d523365SDimitry Andric // This is the fallback handling for the old format bitcode that 46357d523365SDimitry Andric // didn't contain the function index in the VST, or when we have 46367d523365SDimitry Andric // an anonymous function which would not have a VST entry. 46377d523365SDimitry Andric // Assert that we have one of those two cases. 46387d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 46397d523365SDimitry Andric // Parse the next body in the stream and set its position in the 46407d523365SDimitry Andric // DeferredFunctionInfo map. 4641d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBodies()) 4642d88c1a5aSDimitry Andric return Err; 4643dff0c46cSDimitry Andric } 4644d88c1a5aSDimitry Andric return Error::success(); 4645dff0c46cSDimitry Andric } 4646dff0c46cSDimitry Andric 4647c4394386SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 4648c4394386SDimitry Andric if (Val == SyncScope::SingleThread || Val == SyncScope::System) 4649c4394386SDimitry Andric return SyncScope::ID(Val); 4650c4394386SDimitry Andric if (Val >= SSIDs.size()) 4651c4394386SDimitry Andric return SyncScope::System; // Map unknown synchronization scopes to system. 4652c4394386SDimitry Andric return SSIDs[Val]; 4653c4394386SDimitry Andric } 4654c4394386SDimitry Andric 4655f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 4656f22ef01cSRoman Divacky // GVMaterializer implementation 4657f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 4658f22ef01cSRoman Divacky 4659d88c1a5aSDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) { 4660f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV); 4661f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request. 4662f785676fSDimitry Andric if (!F || !F->isMaterializable()) 4663d88c1a5aSDimitry Andric return Error::success(); 4664f22ef01cSRoman Divacky 4665f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 4666f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 4667dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 4668dff0c46cSDimitry Andric // but we haven't seen it yet. 46693dac3a9bSDimitry Andric if (DFII->second == 0) 4670d88c1a5aSDimitry Andric if (Error Err = findFunctionInStream(F, DFII)) 4671d88c1a5aSDimitry Andric return Err; 4672f22ef01cSRoman Divacky 46733ca95b02SDimitry Andric // Materialize metadata before parsing any function bodies. 4674d88c1a5aSDimitry Andric if (Error Err = materializeMetadata()) 4675d88c1a5aSDimitry Andric return Err; 46763ca95b02SDimitry Andric 4677f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body. 4678f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second); 4679f22ef01cSRoman Divacky 4680d88c1a5aSDimitry Andric if (Error Err = parseFunctionBody(F)) 4681d88c1a5aSDimitry Andric return Err; 468239d628a0SDimitry Andric F->setIsMaterializable(false); 4683f22ef01cSRoman Divacky 4684ff0cc061SDimitry Andric if (StripDebugInfo) 4685ff0cc061SDimitry Andric stripDebugInfo(*F); 4686ff0cc061SDimitry Andric 4687f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function. 46883dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 46897d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 46907d523365SDimitry Andric UI != UE;) { 46913dac3a9bSDimitry Andric User *U = *UI; 46923dac3a9bSDimitry Andric ++UI; 46933dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 46943dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 4695f22ef01cSRoman Divacky } 4696f22ef01cSRoman Divacky } 4697f22ef01cSRoman Divacky 46983ca95b02SDimitry Andric // Update calls to the remangled intrinsics 46993ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) 47003ca95b02SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 47013ca95b02SDimitry Andric UI != UE;) 47023ca95b02SDimitry Andric // Don't expect any other users than call sites 47033ca95b02SDimitry Andric CallSite(*UI++).setCalledFunction(I.second); 47043ca95b02SDimitry Andric 47057d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 4706d88c1a5aSDimitry Andric if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 47077d523365SDimitry Andric F->setSubprogram(SP); 47087d523365SDimitry Andric 4709d88c1a5aSDimitry Andric // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 4710d88c1a5aSDimitry Andric if (!MDLoader->isStrippingTBAA()) { 4711d88c1a5aSDimitry Andric for (auto &I : instructions(F)) { 4712d88c1a5aSDimitry Andric MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 4713d88c1a5aSDimitry Andric if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 4714d88c1a5aSDimitry Andric continue; 4715d88c1a5aSDimitry Andric MDLoader->setStripTBAA(true); 4716d88c1a5aSDimitry Andric stripTBAA(F->getParent()); 4717d88c1a5aSDimitry Andric } 4718d88c1a5aSDimitry Andric } 4719d88c1a5aSDimitry Andric 472039d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via 472139d628a0SDimitry Andric // blockaddresses. 472239d628a0SDimitry Andric return materializeForwardReferencedFunctions(); 4723f22ef01cSRoman Divacky } 4724f22ef01cSRoman Divacky 4725d88c1a5aSDimitry Andric Error BitcodeReader::materializeModule() { 4726d88c1a5aSDimitry Andric if (Error Err = materializeMetadata()) 4727d88c1a5aSDimitry Andric return Err; 4728ff0cc061SDimitry Andric 472939d628a0SDimitry Andric // Promise to materialize all forward references. 473039d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 473139d628a0SDimitry Andric 4732f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on 4733f22ef01cSRoman Divacky // disk. 47347d523365SDimitry Andric for (Function &F : *TheModule) { 4735d88c1a5aSDimitry Andric if (Error Err = materialize(&F)) 4736d88c1a5aSDimitry Andric return Err; 4737f785676fSDimitry Andric } 47387d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of 47397d523365SDimitry Andric // the bits in the module past the last function block we have recorded 47407d523365SDimitry Andric // through either lazy scanning or the VST. 47417d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 4742d88c1a5aSDimitry Andric if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 4743d88c1a5aSDimitry Andric ? LastFunctionBlockBit 4744d88c1a5aSDimitry Andric : NextUnreadBit)) 4745d88c1a5aSDimitry Andric return Err; 4746dff0c46cSDimitry Andric 474739d628a0SDimitry Andric // Check that all block address forward references got resolved (as we 474839d628a0SDimitry Andric // promised above). 474939d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty()) 47508f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 475139d628a0SDimitry Andric 4752f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 4753f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire 4754f22ef01cSRoman Divacky // module is materialized because there could always be another function body 4755f22ef01cSRoman Divacky // with calls to the old function. 47563dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 47573dac3a9bSDimitry Andric for (auto *U : I.first->users()) { 47583dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 47593dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 4760f22ef01cSRoman Divacky } 47613dac3a9bSDimitry Andric if (!I.first->use_empty()) 47623dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second); 47633dac3a9bSDimitry Andric I.first->eraseFromParent(); 4764f22ef01cSRoman Divacky } 47653dac3a9bSDimitry Andric UpgradedIntrinsics.clear(); 47663ca95b02SDimitry Andric // Do the same for remangled intrinsics 47673ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) { 47683ca95b02SDimitry Andric I.first->replaceAllUsesWith(I.second); 47693ca95b02SDimitry Andric I.first->eraseFromParent(); 47703ca95b02SDimitry Andric } 47713ca95b02SDimitry Andric RemangledIntrinsics.clear(); 4772f785676fSDimitry Andric 47737d523365SDimitry Andric UpgradeDebugInfo(*TheModule); 47743ca95b02SDimitry Andric 47753ca95b02SDimitry Andric UpgradeModuleFlags(*TheModule); 4776d88c1a5aSDimitry Andric return Error::success(); 4777dff0c46cSDimitry Andric } 47786122f3e6SDimitry Andric 477939d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 478039d628a0SDimitry Andric return IdentifiedStructTypes; 478139d628a0SDimitry Andric } 478239d628a0SDimitry Andric 47833ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 4784f37b6182SDimitry Andric BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 4785f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId) 4786f37b6182SDimitry Andric : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 4787f37b6182SDimitry Andric ModulePath(ModulePath), ModuleId(ModuleId) {} 4788f37b6182SDimitry Andric 478924d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo * 479024d58133SDimitry Andric ModuleSummaryIndexBitcodeReader::addThisModule() { 479124d58133SDimitry Andric return TheIndex.addModule(ModulePath, ModuleId); 4792f37b6182SDimitry Andric } 47933ca95b02SDimitry Andric 47940f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID> 47950f5676f4SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 47960f5676f4SDimitry Andric auto VGI = ValueIdToValueInfoMap[ValueId]; 47970f5676f4SDimitry Andric assert(VGI.first); 47980f5676f4SDimitry Andric return VGI; 47997d523365SDimitry Andric } 48007d523365SDimitry Andric 48016bc11b14SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID( 48026bc11b14SDimitry Andric uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 48036bc11b14SDimitry Andric StringRef SourceFileName) { 48046bc11b14SDimitry Andric std::string GlobalId = 48056bc11b14SDimitry Andric GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 48066bc11b14SDimitry Andric auto ValueGUID = GlobalValue::getGUID(GlobalId); 48076bc11b14SDimitry Andric auto OriginalNameID = ValueGUID; 48086bc11b14SDimitry Andric if (GlobalValue::isLocalLinkage(Linkage)) 48096bc11b14SDimitry Andric OriginalNameID = GlobalValue::getGUID(ValueName); 48106bc11b14SDimitry Andric if (PrintSummaryGUIDs) 48116bc11b14SDimitry Andric dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 48126bc11b14SDimitry Andric << ValueName << "\n"; 48130f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 48140f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID); 48156bc11b14SDimitry Andric } 48166bc11b14SDimitry Andric 48173ca95b02SDimitry Andric // Specialized value symbol table parser used when reading module index 48183ca95b02SDimitry Andric // blocks where we don't actually create global values. The parsed information 48193ca95b02SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries. 4820d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 48213ca95b02SDimitry Andric uint64_t Offset, 48223ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 48236bc11b14SDimitry Andric // With a strtab the VST is not required to parse the summary. 48246bc11b14SDimitry Andric if (UseStrtab) 48256bc11b14SDimitry Andric return Error::success(); 48266bc11b14SDimitry Andric 48273ca95b02SDimitry Andric assert(Offset > 0 && "Expected non-zero VST offset"); 48283ca95b02SDimitry Andric uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 48297d523365SDimitry Andric 48307d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 48317d523365SDimitry Andric return error("Invalid record"); 48327d523365SDimitry Andric 48337d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 48347d523365SDimitry Andric 48357d523365SDimitry Andric // Read all the records for this value table. 48367d523365SDimitry Andric SmallString<128> ValueName; 4837d88c1a5aSDimitry Andric 4838d88c1a5aSDimitry Andric while (true) { 48397d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 48407d523365SDimitry Andric 48417d523365SDimitry Andric switch (Entry.Kind) { 48427d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 48437d523365SDimitry Andric case BitstreamEntry::Error: 48447d523365SDimitry Andric return error("Malformed block"); 48457d523365SDimitry Andric case BitstreamEntry::EndBlock: 48463ca95b02SDimitry Andric // Done parsing VST, jump back to wherever we came from. 48473ca95b02SDimitry Andric Stream.JumpToBit(CurrentBit); 4848d88c1a5aSDimitry Andric return Error::success(); 48497d523365SDimitry Andric case BitstreamEntry::Record: 48507d523365SDimitry Andric // The interesting case. 48517d523365SDimitry Andric break; 48527d523365SDimitry Andric } 48537d523365SDimitry Andric 48547d523365SDimitry Andric // Read a record. 48557d523365SDimitry Andric Record.clear(); 48567d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 48577d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 48587d523365SDimitry Andric break; 48593ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 48603ca95b02SDimitry Andric if (convertToString(Record, 1, ValueName)) 48613ca95b02SDimitry Andric return error("Invalid record"); 48623ca95b02SDimitry Andric unsigned ValueID = Record[0]; 48633ca95b02SDimitry Andric assert(!SourceFileName.empty()); 48643ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 48653ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 48663ca95b02SDimitry Andric "No linkage found for VST entry?"); 48673ca95b02SDimitry Andric auto Linkage = VLI->second; 48686bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 48693ca95b02SDimitry Andric ValueName.clear(); 48703ca95b02SDimitry Andric break; 48713ca95b02SDimitry Andric } 48727d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 48733ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 48747d523365SDimitry Andric if (convertToString(Record, 2, ValueName)) 48757d523365SDimitry Andric return error("Invalid record"); 48767d523365SDimitry Andric unsigned ValueID = Record[0]; 48773ca95b02SDimitry Andric assert(!SourceFileName.empty()); 48783ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID); 48793ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() && 48803ca95b02SDimitry Andric "No linkage found for VST entry?"); 48813ca95b02SDimitry Andric auto Linkage = VLI->second; 48826bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 48837d523365SDimitry Andric ValueName.clear(); 48847d523365SDimitry Andric break; 48857d523365SDimitry Andric } 48863ca95b02SDimitry Andric case bitc::VST_CODE_COMBINED_ENTRY: { 48873ca95b02SDimitry Andric // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 48883ca95b02SDimitry Andric unsigned ValueID = Record[0]; 48893ca95b02SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 48903ca95b02SDimitry Andric // The "original name", which is the second value of the pair will be 48913ca95b02SDimitry Andric // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 48920f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 48930f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 48947d523365SDimitry Andric break; 48957d523365SDimitry Andric } 48967d523365SDimitry Andric } 48977d523365SDimitry Andric } 48987d523365SDimitry Andric } 48997d523365SDimitry Andric 49003ca95b02SDimitry Andric // Parse just the blocks needed for building the index out of the module. 49013ca95b02SDimitry Andric // At the end of this routine the module Index is populated with a map 49023ca95b02SDimitry Andric // from global value id to GlobalValueSummary objects. 4903f37b6182SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() { 49047d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 49057d523365SDimitry Andric return error("Invalid record"); 49067d523365SDimitry Andric 49073ca95b02SDimitry Andric SmallVector<uint64_t, 64> Record; 49083ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 49093ca95b02SDimitry Andric unsigned ValueId = 0; 49103ca95b02SDimitry Andric 49113ca95b02SDimitry Andric // Read the index for this module. 4912d88c1a5aSDimitry Andric while (true) { 49137d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 49147d523365SDimitry Andric 49157d523365SDimitry Andric switch (Entry.Kind) { 49167d523365SDimitry Andric case BitstreamEntry::Error: 49177d523365SDimitry Andric return error("Malformed block"); 49187d523365SDimitry Andric case BitstreamEntry::EndBlock: 4919d88c1a5aSDimitry Andric return Error::success(); 49207d523365SDimitry Andric 49217d523365SDimitry Andric case BitstreamEntry::SubBlock: 49227d523365SDimitry Andric switch (Entry.ID) { 49237d523365SDimitry Andric default: // Skip unknown content. 49247d523365SDimitry Andric if (Stream.SkipBlock()) 49257d523365SDimitry Andric return error("Invalid record"); 49267d523365SDimitry Andric break; 49277d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 49287d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 4929d88c1a5aSDimitry Andric if (readBlockInfo()) 49307d523365SDimitry Andric return error("Malformed block"); 49317d523365SDimitry Andric break; 49327d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 49333ca95b02SDimitry Andric // Should have been parsed earlier via VSTOffset, unless there 49343ca95b02SDimitry Andric // is no summary section. 49353ca95b02SDimitry Andric assert(((SeenValueSymbolTable && VSTOffset > 0) || 49363ca95b02SDimitry Andric !SeenGlobalValSummary) && 49373ca95b02SDimitry Andric "Expected early VST parse via VSTOffset record"); 49387d523365SDimitry Andric if (Stream.SkipBlock()) 49397d523365SDimitry Andric return error("Invalid record"); 49403ca95b02SDimitry Andric break; 49413ca95b02SDimitry Andric case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 494224d58133SDimitry Andric case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 49433ca95b02SDimitry Andric assert(!SeenValueSymbolTable && 49443ca95b02SDimitry Andric "Already read VST when parsing summary block?"); 4945d88c1a5aSDimitry Andric // We might not have a VST if there were no values in the 4946d88c1a5aSDimitry Andric // summary. An empty summary block generated when we are 4947d88c1a5aSDimitry Andric // performing ThinLTO compiles so we don't later invoke 4948d88c1a5aSDimitry Andric // the regular LTO process on them. 4949d88c1a5aSDimitry Andric if (VSTOffset > 0) { 4950d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 4951d88c1a5aSDimitry Andric return Err; 49523ca95b02SDimitry Andric SeenValueSymbolTable = true; 4953d88c1a5aSDimitry Andric } 49543ca95b02SDimitry Andric SeenGlobalValSummary = true; 495524d58133SDimitry Andric if (Error Err = parseEntireSummary(Entry.ID)) 4956d88c1a5aSDimitry Andric return Err; 49577d523365SDimitry Andric break; 49587d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 4959d88c1a5aSDimitry Andric if (Error Err = parseModuleStringTable()) 4960d88c1a5aSDimitry Andric return Err; 49617d523365SDimitry Andric break; 49627d523365SDimitry Andric } 49637d523365SDimitry Andric continue; 49647d523365SDimitry Andric 49653ca95b02SDimitry Andric case BitstreamEntry::Record: { 49663ca95b02SDimitry Andric Record.clear(); 49673ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 49683ca95b02SDimitry Andric switch (BitCode) { 49693ca95b02SDimitry Andric default: 49703ca95b02SDimitry Andric break; // Default behavior, ignore unknown content. 49716bc11b14SDimitry Andric case bitc::MODULE_CODE_VERSION: { 49726bc11b14SDimitry Andric if (Error Err = parseVersionRecord(Record).takeError()) 49736bc11b14SDimitry Andric return Err; 49746bc11b14SDimitry Andric break; 49756bc11b14SDimitry Andric } 49763ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 49773ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: { 49783ca95b02SDimitry Andric SmallString<128> ValueName; 49793ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName)) 49803ca95b02SDimitry Andric return error("Invalid record"); 49813ca95b02SDimitry Andric SourceFileName = ValueName.c_str(); 49823ca95b02SDimitry Andric break; 49833ca95b02SDimitry Andric } 49843ca95b02SDimitry Andric /// MODULE_CODE_HASH: [5*i32] 49853ca95b02SDimitry Andric case bitc::MODULE_CODE_HASH: { 49863ca95b02SDimitry Andric if (Record.size() != 5) 49873ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 498824d58133SDimitry Andric auto &Hash = addThisModule()->second.second; 49893ca95b02SDimitry Andric int Pos = 0; 49903ca95b02SDimitry Andric for (auto &Val : Record) { 49913ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 49923ca95b02SDimitry Andric Hash[Pos++] = Val; 49933ca95b02SDimitry Andric } 49943ca95b02SDimitry Andric break; 49953ca95b02SDimitry Andric } 49963ca95b02SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 49973ca95b02SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 49983ca95b02SDimitry Andric if (Record.size() < 1) 49993ca95b02SDimitry Andric return error("Invalid record"); 5000d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one 5001d88c1a5aSDimitry Andric // word before the start of the identification or module block, which 5002d88c1a5aSDimitry Andric // was historically always the start of the regular bitcode header. 5003d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1; 50043ca95b02SDimitry Andric break; 50056bc11b14SDimitry Andric // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 50066bc11b14SDimitry Andric // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 50076bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 50086bc11b14SDimitry Andric // v2: [strtab offset, strtab size, v1] 50097a7e6055SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR: 50107a7e6055SDimitry Andric case bitc::MODULE_CODE_FUNCTION: 50113ca95b02SDimitry Andric case bitc::MODULE_CODE_ALIAS: { 50126bc11b14SDimitry Andric StringRef Name; 50136bc11b14SDimitry Andric ArrayRef<uint64_t> GVRecord; 50146bc11b14SDimitry Andric std::tie(Name, GVRecord) = readNameFromStrtab(Record); 50156bc11b14SDimitry Andric if (GVRecord.size() <= 3) 50163ca95b02SDimitry Andric return error("Invalid record"); 50176bc11b14SDimitry Andric uint64_t RawLinkage = GVRecord[3]; 50183ca95b02SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 50196bc11b14SDimitry Andric if (!UseStrtab) { 50203ca95b02SDimitry Andric ValueIdToLinkageMap[ValueId++] = Linkage; 50213ca95b02SDimitry Andric break; 50223ca95b02SDimitry Andric } 50236bc11b14SDimitry Andric 50246bc11b14SDimitry Andric setValueGUID(ValueId++, Name, Linkage, SourceFileName); 50256bc11b14SDimitry Andric break; 50266bc11b14SDimitry Andric } 50273ca95b02SDimitry Andric } 50283ca95b02SDimitry Andric } 50297d523365SDimitry Andric continue; 50307d523365SDimitry Andric } 50317d523365SDimitry Andric } 50327d523365SDimitry Andric } 50337d523365SDimitry Andric 5034d88c1a5aSDimitry Andric std::vector<ValueInfo> 5035d88c1a5aSDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 5036d88c1a5aSDimitry Andric std::vector<ValueInfo> Ret; 5037d88c1a5aSDimitry Andric Ret.reserve(Record.size()); 5038d88c1a5aSDimitry Andric for (uint64_t RefValueId : Record) 50390f5676f4SDimitry Andric Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5040d88c1a5aSDimitry Andric return Ret; 5041d88c1a5aSDimitry Andric } 5042d88c1a5aSDimitry Andric 5043d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList( 5044d88c1a5aSDimitry Andric ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) { 5045d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Ret; 5046d88c1a5aSDimitry Andric Ret.reserve(Record.size()); 5047d88c1a5aSDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; ++I) { 5048d88c1a5aSDimitry Andric CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 50490f5676f4SDimitry Andric ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 5050d88c1a5aSDimitry Andric if (IsOldProfileFormat) { 5051d88c1a5aSDimitry Andric I += 1; // Skip old callsitecount field 5052d88c1a5aSDimitry Andric if (HasProfile) 5053d88c1a5aSDimitry Andric I += 1; // Skip old profilecount field 5054d88c1a5aSDimitry Andric } else if (HasProfile) 5055d88c1a5aSDimitry Andric Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 50560f5676f4SDimitry Andric Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}}); 5057d88c1a5aSDimitry Andric } 5058d88c1a5aSDimitry Andric return Ret; 5059d88c1a5aSDimitry Andric } 5060d88c1a5aSDimitry Andric 50613ca95b02SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary 50623ca95b02SDimitry Andric // objects in the index. 506324d58133SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 506424d58133SDimitry Andric if (Stream.EnterSubBlock(ID)) 50657d523365SDimitry Andric return error("Invalid record"); 50667d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 50677d523365SDimitry Andric 50683ca95b02SDimitry Andric // Parse version 50693ca95b02SDimitry Andric { 50703ca95b02SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 50713ca95b02SDimitry Andric if (Entry.Kind != BitstreamEntry::Record) 50723ca95b02SDimitry Andric return error("Invalid Summary Block: record for version expected"); 50733ca95b02SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 50743ca95b02SDimitry Andric return error("Invalid Summary Block: version expected"); 50753ca95b02SDimitry Andric } 50763ca95b02SDimitry Andric const uint64_t Version = Record[0]; 5077d88c1a5aSDimitry Andric const bool IsOldProfileFormat = Version == 1; 50782cab237bSDimitry Andric if (Version < 1 || Version > 4) 5079d88c1a5aSDimitry Andric return error("Invalid summary version " + Twine(Version) + 50802cab237bSDimitry Andric ", 1, 2, 3 or 4 expected"); 50813ca95b02SDimitry Andric Record.clear(); 50823ca95b02SDimitry Andric 50833ca95b02SDimitry Andric // Keep around the last seen summary to be used when we see an optional 50843ca95b02SDimitry Andric // "OriginalName" attachement. 50853ca95b02SDimitry Andric GlobalValueSummary *LastSeenSummary = nullptr; 50867a7e6055SDimitry Andric GlobalValue::GUID LastSeenGUID = 0; 50877a7e6055SDimitry Andric 50887a7e6055SDimitry Andric // We can expect to see any number of type ID information records before 50897a7e6055SDimitry Andric // each function summary records; these variables store the information 50907a7e6055SDimitry Andric // collected so far so that it can be used to create the summary object. 5091d88c1a5aSDimitry Andric std::vector<GlobalValue::GUID> PendingTypeTests; 50927a7e6055SDimitry Andric std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 50937a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls; 50947a7e6055SDimitry Andric std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 50957a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls; 5096d88c1a5aSDimitry Andric 5097d88c1a5aSDimitry Andric while (true) { 50987d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 50997d523365SDimitry Andric 51007d523365SDimitry Andric switch (Entry.Kind) { 51017d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 51027d523365SDimitry Andric case BitstreamEntry::Error: 51037d523365SDimitry Andric return error("Malformed block"); 51047d523365SDimitry Andric case BitstreamEntry::EndBlock: 5105d88c1a5aSDimitry Andric return Error::success(); 51067d523365SDimitry Andric case BitstreamEntry::Record: 51077d523365SDimitry Andric // The interesting case. 51087d523365SDimitry Andric break; 51097d523365SDimitry Andric } 51107d523365SDimitry Andric 51117d523365SDimitry Andric // Read a record. The record format depends on whether this 51127d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module 51137d523365SDimitry Andric // case the records contain the associated value's ID for correlation 51147d523365SDimitry Andric // with VST entries. In the combined index the correlation is done 51157d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved 51167d523365SDimitry Andric // in the combined index VST entries). The records also contain 51177d523365SDimitry Andric // information used for ThinLTO renaming and importing. 51187d523365SDimitry Andric Record.clear(); 51193ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 51203ca95b02SDimitry Andric switch (BitCode) { 51217d523365SDimitry Andric default: // Default behavior: ignore. 51227d523365SDimitry Andric break; 51236bc11b14SDimitry Andric case bitc::FS_VALUE_GUID: { // [valueid, refguid] 51246bc11b14SDimitry Andric uint64_t ValueID = Record[0]; 51256bc11b14SDimitry Andric GlobalValue::GUID RefGUID = Record[1]; 51260f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] = 51270f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 51286bc11b14SDimitry Andric break; 51296bc11b14SDimitry Andric } 51302cab237bSDimitry Andric // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 51312cab237bSDimitry Andric // numrefs x valueid, n x (valueid)] 51322cab237bSDimitry Andric // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 51333ca95b02SDimitry Andric // numrefs x valueid, 5134d88c1a5aSDimitry Andric // n x (valueid, hotness)] 51353ca95b02SDimitry Andric case bitc::FS_PERMODULE: 51363ca95b02SDimitry Andric case bitc::FS_PERMODULE_PROFILE: { 51377d523365SDimitry Andric unsigned ValueID = Record[0]; 51383ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51397d523365SDimitry Andric unsigned InstCount = Record[2]; 51402cab237bSDimitry Andric uint64_t RawFunFlags = 0; 51413ca95b02SDimitry Andric unsigned NumRefs = Record[3]; 51422cab237bSDimitry Andric int RefListStartIndex = 4; 51432cab237bSDimitry Andric if (Version >= 4) { 51442cab237bSDimitry Andric RawFunFlags = Record[3]; 51452cab237bSDimitry Andric NumRefs = Record[4]; 51462cab237bSDimitry Andric RefListStartIndex = 5; 51472cab237bSDimitry Andric } 51482cab237bSDimitry Andric 51493ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 51507d523365SDimitry Andric // The module path string ref set in the summary must be owned by the 51517d523365SDimitry Andric // index's module string table. Since we don't have a module path 51527d523365SDimitry Andric // string table section in the per-module index, we create a single 51537d523365SDimitry Andric // module path string table entry with an empty (0) ID to take 51547d523365SDimitry Andric // ownership. 51553ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 51563ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 51573ca95b02SDimitry Andric "Record size inconsistent with number of references"); 5158d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 5159d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 51603ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 5161d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 5162d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5163d88c1a5aSDimitry Andric IsOldProfileFormat, HasProfile); 5164d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>( 51652cab237bSDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs), 51662cab237bSDimitry Andric std::move(Calls), std::move(PendingTypeTests), 51672cab237bSDimitry Andric std::move(PendingTypeTestAssumeVCalls), 51687a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 51697a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 51707a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls)); 5171d88c1a5aSDimitry Andric PendingTypeTests.clear(); 51727a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear(); 51737a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear(); 51747a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear(); 51757a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear(); 51760f5676f4SDimitry Andric auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 517724d58133SDimitry Andric FS->setModulePath(addThisModule()->first()); 51780f5676f4SDimitry Andric FS->setOriginalName(VIAndOriginalGUID.second); 51790f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 51803ca95b02SDimitry Andric break; 51813ca95b02SDimitry Andric } 51823ca95b02SDimitry Andric // FS_ALIAS: [valueid, flags, valueid] 51833ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 51843ca95b02SDimitry Andric // they expect all aliasee summaries to be available. 51853ca95b02SDimitry Andric case bitc::FS_ALIAS: { 51863ca95b02SDimitry Andric unsigned ValueID = Record[0]; 51873ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 51883ca95b02SDimitry Andric unsigned AliaseeID = Record[2]; 51893ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 51902cab237bSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags); 51913ca95b02SDimitry Andric // The module path string ref set in the summary must be owned by the 51923ca95b02SDimitry Andric // index's module string table. Since we don't have a module path 51933ca95b02SDimitry Andric // string table section in the per-module index, we create a single 51943ca95b02SDimitry Andric // module path string table entry with an empty (0) ID to take 51953ca95b02SDimitry Andric // ownership. 519624d58133SDimitry Andric AS->setModulePath(addThisModule()->first()); 51973ca95b02SDimitry Andric 51980f5676f4SDimitry Andric GlobalValue::GUID AliaseeGUID = 51990f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeID).first.getGUID(); 5200f37b6182SDimitry Andric auto AliaseeInModule = 5201f37b6182SDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, ModulePath); 5202f37b6182SDimitry Andric if (!AliaseeInModule) 52033ca95b02SDimitry Andric return error("Alias expects aliasee summary to be parsed"); 5204f37b6182SDimitry Andric AS->setAliasee(AliaseeInModule); 52052cab237bSDimitry Andric AS->setAliaseeGUID(AliaseeGUID); 52063ca95b02SDimitry Andric 52070f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 52083ca95b02SDimitry Andric AS->setOriginalName(GUID.second); 5209d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 52103ca95b02SDimitry Andric break; 52113ca95b02SDimitry Andric } 52123ca95b02SDimitry Andric // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 52133ca95b02SDimitry Andric case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 52143ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52153ca95b02SDimitry Andric uint64_t RawFlags = Record[1]; 52163ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5217d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = 5218d88c1a5aSDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(2)); 5219d88c1a5aSDimitry Andric auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 522024d58133SDimitry Andric FS->setModulePath(addThisModule()->first()); 52210f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID); 52223ca95b02SDimitry Andric FS->setOriginalName(GUID.second); 5223d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 52243ca95b02SDimitry Andric break; 52253ca95b02SDimitry Andric } 52262cab237bSDimitry Andric // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 5227d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid)] 52282cab237bSDimitry Andric // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 5229d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid, hotness)] 52303ca95b02SDimitry Andric case bitc::FS_COMBINED: 52313ca95b02SDimitry Andric case bitc::FS_COMBINED_PROFILE: { 52323ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52333ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 52343ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 52353ca95b02SDimitry Andric unsigned InstCount = Record[3]; 52362cab237bSDimitry Andric uint64_t RawFunFlags = 0; 52373ca95b02SDimitry Andric unsigned NumRefs = Record[4]; 52382cab237bSDimitry Andric int RefListStartIndex = 5; 52392cab237bSDimitry Andric 52402cab237bSDimitry Andric if (Version >= 4) { 52412cab237bSDimitry Andric RawFunFlags = Record[4]; 52422cab237bSDimitry Andric NumRefs = Record[5]; 52432cab237bSDimitry Andric RefListStartIndex = 6; 52442cab237bSDimitry Andric } 52452cab237bSDimitry Andric 52463ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 52473ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 52483ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs && 52493ca95b02SDimitry Andric "Record size inconsistent with number of references"); 5250d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList( 5251d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 52523ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 5253d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 5254d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 5255d88c1a5aSDimitry Andric IsOldProfileFormat, HasProfile); 52560f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 5257d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>( 52582cab237bSDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs), 52592cab237bSDimitry Andric std::move(Edges), std::move(PendingTypeTests), 52602cab237bSDimitry Andric std::move(PendingTypeTestAssumeVCalls), 52617a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls), 52627a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls), 52637a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls)); 5264d88c1a5aSDimitry Andric PendingTypeTests.clear(); 52657a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear(); 52667a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear(); 52677a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear(); 52687a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear(); 5269d88c1a5aSDimitry Andric LastSeenSummary = FS.get(); 52700f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 5271d88c1a5aSDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 52720f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 52733ca95b02SDimitry Andric break; 52743ca95b02SDimitry Andric } 52753ca95b02SDimitry Andric // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 52763ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 52773ca95b02SDimitry Andric // they expect all aliasee summaries to be available. 52783ca95b02SDimitry Andric case bitc::FS_COMBINED_ALIAS: { 52793ca95b02SDimitry Andric unsigned ValueID = Record[0]; 52803ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 52813ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 52823ca95b02SDimitry Andric unsigned AliaseeValueId = Record[3]; 52833ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 52842cab237bSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags); 52853ca95b02SDimitry Andric LastSeenSummary = AS.get(); 52863ca95b02SDimitry Andric AS->setModulePath(ModuleIdMap[ModuleId]); 52873ca95b02SDimitry Andric 52880f5676f4SDimitry Andric auto AliaseeGUID = 52890f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeValueId).first.getGUID(); 52903ca95b02SDimitry Andric auto AliaseeInModule = 5291d88c1a5aSDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath()); 52923ca95b02SDimitry Andric AS->setAliasee(AliaseeInModule); 52932cab237bSDimitry Andric AS->setAliaseeGUID(AliaseeGUID); 52943ca95b02SDimitry Andric 52950f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 52960f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 52970f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(AS)); 52983ca95b02SDimitry Andric break; 52993ca95b02SDimitry Andric } 53003ca95b02SDimitry Andric // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 53013ca95b02SDimitry Andric case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 53023ca95b02SDimitry Andric unsigned ValueID = Record[0]; 53033ca95b02SDimitry Andric uint64_t ModuleId = Record[1]; 53043ca95b02SDimitry Andric uint64_t RawFlags = Record[2]; 53053ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 5306d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = 5307d88c1a5aSDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(3)); 5308d88c1a5aSDimitry Andric auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs)); 53093ca95b02SDimitry Andric LastSeenSummary = FS.get(); 53103ca95b02SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 53110f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first; 53120f5676f4SDimitry Andric LastSeenGUID = VI.getGUID(); 53130f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS)); 53143ca95b02SDimitry Andric break; 53153ca95b02SDimitry Andric } 53163ca95b02SDimitry Andric // FS_COMBINED_ORIGINAL_NAME: [original_name] 53173ca95b02SDimitry Andric case bitc::FS_COMBINED_ORIGINAL_NAME: { 53183ca95b02SDimitry Andric uint64_t OriginalName = Record[0]; 53193ca95b02SDimitry Andric if (!LastSeenSummary) 53203ca95b02SDimitry Andric return error("Name attachment that does not follow a combined record"); 53213ca95b02SDimitry Andric LastSeenSummary->setOriginalName(OriginalName); 53227a7e6055SDimitry Andric TheIndex.addOriginalName(LastSeenGUID, OriginalName); 53233ca95b02SDimitry Andric // Reset the LastSeenSummary 53243ca95b02SDimitry Andric LastSeenSummary = nullptr; 53257a7e6055SDimitry Andric LastSeenGUID = 0; 5326d88c1a5aSDimitry Andric break; 5327d88c1a5aSDimitry Andric } 53282cab237bSDimitry Andric case bitc::FS_TYPE_TESTS: 5329d88c1a5aSDimitry Andric assert(PendingTypeTests.empty()); 5330d88c1a5aSDimitry Andric PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(), 5331d88c1a5aSDimitry Andric Record.end()); 5332d88c1a5aSDimitry Andric break; 53332cab237bSDimitry Andric 53342cab237bSDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 53357a7e6055SDimitry Andric assert(PendingTypeTestAssumeVCalls.empty()); 53367a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 53377a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 53387a7e6055SDimitry Andric break; 53392cab237bSDimitry Andric 53402cab237bSDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 53417a7e6055SDimitry Andric assert(PendingTypeCheckedLoadVCalls.empty()); 53427a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 53437a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 53447a7e6055SDimitry Andric break; 53452cab237bSDimitry Andric 53462cab237bSDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 53477a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.push_back( 53487a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 53497a7e6055SDimitry Andric break; 53502cab237bSDimitry Andric 53512cab237bSDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 53527a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.push_back( 53537a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 53547a7e6055SDimitry Andric break; 53552cab237bSDimitry Andric 535624d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DEFS: { 535724d58133SDimitry Andric std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 535824d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 535924d58133SDimitry Andric CfiFunctionDefs.insert( 536024d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 536124d58133SDimitry Andric break; 536224d58133SDimitry Andric } 536324d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DECLS: { 536424d58133SDimitry Andric std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 536524d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2) 536624d58133SDimitry Andric CfiFunctionDecls.insert( 536724d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 536824d58133SDimitry Andric break; 536924d58133SDimitry Andric } 53707d523365SDimitry Andric } 53717d523365SDimitry Andric } 53727d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 53737d523365SDimitry Andric } 53747d523365SDimitry Andric 53757d523365SDimitry Andric // Parse the module string table block into the Index. 53767d523365SDimitry Andric // This populates the ModulePathStringTable map in the index. 5377d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 53787d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 53797d523365SDimitry Andric return error("Invalid record"); 53807d523365SDimitry Andric 53817d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 53827d523365SDimitry Andric 53837d523365SDimitry Andric SmallString<128> ModulePath; 538424d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 5385d88c1a5aSDimitry Andric 5386d88c1a5aSDimitry Andric while (true) { 53877d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 53887d523365SDimitry Andric 53897d523365SDimitry Andric switch (Entry.Kind) { 53907d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 53917d523365SDimitry Andric case BitstreamEntry::Error: 53927d523365SDimitry Andric return error("Malformed block"); 53937d523365SDimitry Andric case BitstreamEntry::EndBlock: 5394d88c1a5aSDimitry Andric return Error::success(); 53957d523365SDimitry Andric case BitstreamEntry::Record: 53967d523365SDimitry Andric // The interesting case. 53977d523365SDimitry Andric break; 53987d523365SDimitry Andric } 53997d523365SDimitry Andric 54007d523365SDimitry Andric Record.clear(); 54017d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 54027d523365SDimitry Andric default: // Default behavior: ignore. 54037d523365SDimitry Andric break; 54047d523365SDimitry Andric case bitc::MST_CODE_ENTRY: { 54057d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N] 54063ca95b02SDimitry Andric uint64_t ModuleId = Record[0]; 54073ca95b02SDimitry Andric 54087d523365SDimitry Andric if (convertToString(Record, 1, ModulePath)) 54097d523365SDimitry Andric return error("Invalid record"); 54103ca95b02SDimitry Andric 541124d58133SDimitry Andric LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 541224d58133SDimitry Andric ModuleIdMap[ModuleId] = LastSeenModule->first(); 54133ca95b02SDimitry Andric 54147d523365SDimitry Andric ModulePath.clear(); 54157d523365SDimitry Andric break; 54167d523365SDimitry Andric } 54173ca95b02SDimitry Andric /// MST_CODE_HASH: [5*i32] 54183ca95b02SDimitry Andric case bitc::MST_CODE_HASH: { 54193ca95b02SDimitry Andric if (Record.size() != 5) 54203ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str()); 542124d58133SDimitry Andric if (!LastSeenModule) 54223ca95b02SDimitry Andric return error("Invalid hash that does not follow a module path"); 54233ca95b02SDimitry Andric int Pos = 0; 54243ca95b02SDimitry Andric for (auto &Val : Record) { 54253ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set"); 542624d58133SDimitry Andric LastSeenModule->second.second[Pos++] = Val; 54273ca95b02SDimitry Andric } 542824d58133SDimitry Andric // Reset LastSeenModule to avoid overriding the hash unexpectedly. 542924d58133SDimitry Andric LastSeenModule = nullptr; 54303ca95b02SDimitry Andric break; 54313ca95b02SDimitry Andric } 54327d523365SDimitry Andric } 54337d523365SDimitry Andric } 54347d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 54357d523365SDimitry Andric } 54367d523365SDimitry Andric 5437f785676fSDimitry Andric namespace { 5438d88c1a5aSDimitry Andric 54393ca95b02SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It 54403ca95b02SDimitry Andric // will be removed once this transition is complete. Clients should prefer to 54413ca95b02SDimitry Andric // deal with the Error value directly, rather than converting to error_code. 544291bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 5443d88c1a5aSDimitry Andric const char *name() const noexcept override { 5444f785676fSDimitry Andric return "llvm.bitcode"; 5445f785676fSDimitry Andric } 54462cab237bSDimitry Andric 544791bc56edSDimitry Andric std::string message(int IE) const override { 544839d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 5449f785676fSDimitry Andric switch (E) { 545039d628a0SDimitry Andric case BitcodeError::CorruptedBitcode: 545139d628a0SDimitry Andric return "Corrupted bitcode"; 5452f785676fSDimitry Andric } 5453f785676fSDimitry Andric llvm_unreachable("Unknown error type!"); 5454f785676fSDimitry Andric } 5455f785676fSDimitry Andric }; 5456d88c1a5aSDimitry Andric 54573ca95b02SDimitry Andric } // end anonymous namespace 5458f785676fSDimitry Andric 545939d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 546039d628a0SDimitry Andric 546139d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 546239d628a0SDimitry Andric return *ErrorCategory; 5463dff0c46cSDimitry Andric } 5464f22ef01cSRoman Divacky 5465a580b014SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 5466a580b014SDimitry Andric unsigned Block, unsigned RecordID) { 5467a580b014SDimitry Andric if (Stream.EnterSubBlock(Block)) 54686bc11b14SDimitry Andric return error("Invalid record"); 54696bc11b14SDimitry Andric 54706bc11b14SDimitry Andric StringRef Strtab; 54712cab237bSDimitry Andric while (true) { 54726bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advance(); 54736bc11b14SDimitry Andric switch (Entry.Kind) { 54746bc11b14SDimitry Andric case BitstreamEntry::EndBlock: 54756bc11b14SDimitry Andric return Strtab; 54766bc11b14SDimitry Andric 54776bc11b14SDimitry Andric case BitstreamEntry::Error: 54786bc11b14SDimitry Andric return error("Malformed block"); 54796bc11b14SDimitry Andric 54806bc11b14SDimitry Andric case BitstreamEntry::SubBlock: 54816bc11b14SDimitry Andric if (Stream.SkipBlock()) 54826bc11b14SDimitry Andric return error("Malformed block"); 54836bc11b14SDimitry Andric break; 54846bc11b14SDimitry Andric 54856bc11b14SDimitry Andric case BitstreamEntry::Record: 54866bc11b14SDimitry Andric StringRef Blob; 54876bc11b14SDimitry Andric SmallVector<uint64_t, 1> Record; 5488a580b014SDimitry Andric if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID) 54896bc11b14SDimitry Andric Strtab = Blob; 54906bc11b14SDimitry Andric break; 54916bc11b14SDimitry Andric } 54926bc11b14SDimitry Andric } 54936bc11b14SDimitry Andric } 54946bc11b14SDimitry Andric 5495f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5496f22ef01cSRoman Divacky // External interface 5497f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5498f22ef01cSRoman Divacky 5499d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> 5500d88c1a5aSDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 5501db17bf38SDimitry Andric auto FOrErr = getBitcodeFileContents(Buffer); 5502db17bf38SDimitry Andric if (!FOrErr) 5503db17bf38SDimitry Andric return FOrErr.takeError(); 5504db17bf38SDimitry Andric return std::move(FOrErr->Mods); 5505db17bf38SDimitry Andric } 5506db17bf38SDimitry Andric 5507db17bf38SDimitry Andric Expected<BitcodeFileContents> 5508db17bf38SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 5509d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5510d88c1a5aSDimitry Andric if (!StreamOrErr) 5511d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5512d88c1a5aSDimitry Andric BitstreamCursor &Stream = *StreamOrErr; 55138f0fd8f6SDimitry Andric 5514db17bf38SDimitry Andric BitcodeFileContents F; 5515d88c1a5aSDimitry Andric while (true) { 5516d88c1a5aSDimitry Andric uint64_t BCBegin = Stream.getCurrentByteNo(); 55178f0fd8f6SDimitry Andric 5518d88c1a5aSDimitry Andric // We may be consuming bitcode from a client that leaves garbage at the end 5519d88c1a5aSDimitry Andric // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 5520d88c1a5aSDimitry Andric // the end that there cannot possibly be another module, stop looking. 5521d88c1a5aSDimitry Andric if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 5522db17bf38SDimitry Andric return F; 55238f0fd8f6SDimitry Andric 5524d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 5525d88c1a5aSDimitry Andric switch (Entry.Kind) { 5526d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 5527d88c1a5aSDimitry Andric case BitstreamEntry::Error: 5528d88c1a5aSDimitry Andric return error("Malformed block"); 5529d88c1a5aSDimitry Andric 5530d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: { 5531d88c1a5aSDimitry Andric uint64_t IdentificationBit = -1ull; 5532d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 5533d88c1a5aSDimitry Andric IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5534d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5535d88c1a5aSDimitry Andric return error("Malformed block"); 5536d88c1a5aSDimitry Andric 5537d88c1a5aSDimitry Andric Entry = Stream.advance(); 5538d88c1a5aSDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock || 5539d88c1a5aSDimitry Andric Entry.ID != bitc::MODULE_BLOCK_ID) 5540d88c1a5aSDimitry Andric return error("Malformed block"); 55418f0fd8f6SDimitry Andric } 5542d88c1a5aSDimitry Andric 5543d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) { 5544d88c1a5aSDimitry Andric uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 5545d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5546d88c1a5aSDimitry Andric return error("Malformed block"); 5547d88c1a5aSDimitry Andric 5548db17bf38SDimitry Andric F.Mods.push_back({Stream.getBitcodeBytes().slice( 5549d88c1a5aSDimitry Andric BCBegin, Stream.getCurrentByteNo() - BCBegin), 5550d88c1a5aSDimitry Andric Buffer.getBufferIdentifier(), IdentificationBit, 5551d88c1a5aSDimitry Andric ModuleBit}); 5552d88c1a5aSDimitry Andric continue; 5553d88c1a5aSDimitry Andric } 5554d88c1a5aSDimitry Andric 55556bc11b14SDimitry Andric if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 5556a580b014SDimitry Andric Expected<StringRef> Strtab = 5557a580b014SDimitry Andric readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 55586bc11b14SDimitry Andric if (!Strtab) 55596bc11b14SDimitry Andric return Strtab.takeError(); 55606bc11b14SDimitry Andric // This string table is used by every preceding bitcode module that does 55616bc11b14SDimitry Andric // not have its own string table. A bitcode file may have multiple 55626bc11b14SDimitry Andric // string tables if it was created by binary concatenation, for example 55636bc11b14SDimitry Andric // with "llvm-cat -b". 5564db17bf38SDimitry Andric for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 55656bc11b14SDimitry Andric if (!I->Strtab.empty()) 55666bc11b14SDimitry Andric break; 55676bc11b14SDimitry Andric I->Strtab = *Strtab; 55686bc11b14SDimitry Andric } 5569a580b014SDimitry Andric // Similarly, the string table is used by every preceding symbol table; 5570a580b014SDimitry Andric // normally there will be just one unless the bitcode file was created 5571a580b014SDimitry Andric // by binary concatenation. 5572a580b014SDimitry Andric if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 5573a580b014SDimitry Andric F.StrtabForSymtab = *Strtab; 5574a580b014SDimitry Andric continue; 5575a580b014SDimitry Andric } 5576a580b014SDimitry Andric 5577a580b014SDimitry Andric if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 5578a580b014SDimitry Andric Expected<StringRef> SymtabOrErr = 5579a580b014SDimitry Andric readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 5580a580b014SDimitry Andric if (!SymtabOrErr) 5581a580b014SDimitry Andric return SymtabOrErr.takeError(); 5582a580b014SDimitry Andric 5583a580b014SDimitry Andric // We can expect the bitcode file to have multiple symbol tables if it 5584a580b014SDimitry Andric // was created by binary concatenation. In that case we silently 5585a580b014SDimitry Andric // ignore any subsequent symbol tables, which is fine because this is a 5586a580b014SDimitry Andric // low level function. The client is expected to notice that the number 5587a580b014SDimitry Andric // of modules in the symbol table does not match the number of modules 5588a580b014SDimitry Andric // in the input file and regenerate the symbol table. 5589a580b014SDimitry Andric if (F.Symtab.empty()) 5590a580b014SDimitry Andric F.Symtab = *SymtabOrErr; 55916bc11b14SDimitry Andric continue; 55926bc11b14SDimitry Andric } 55936bc11b14SDimitry Andric 5594d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5595d88c1a5aSDimitry Andric return error("Malformed block"); 5596d88c1a5aSDimitry Andric continue; 5597d88c1a5aSDimitry Andric } 5598d88c1a5aSDimitry Andric case BitstreamEntry::Record: 5599d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 5600d88c1a5aSDimitry Andric continue; 5601d88c1a5aSDimitry Andric } 5602d88c1a5aSDimitry Andric } 56038f0fd8f6SDimitry Andric } 56048f0fd8f6SDimitry Andric 560539d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode. 5606f22ef01cSRoman Divacky /// 560739d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 5608d88c1a5aSDimitry Andric /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 560939d628a0SDimitry Andric /// in forward-referenced functions from block address references. 561039d628a0SDimitry Andric /// 56118f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 56128f0fd8f6SDimitry Andric /// everything. 5613d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5614d88c1a5aSDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 5615d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5616d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 561739d628a0SDimitry Andric 5618d88c1a5aSDimitry Andric std::string ProducerIdentification; 5619d88c1a5aSDimitry Andric if (IdentificationBit != -1ull) { 5620d88c1a5aSDimitry Andric Stream.JumpToBit(IdentificationBit); 5621d88c1a5aSDimitry Andric Expected<std::string> ProducerIdentificationOrErr = 5622d88c1a5aSDimitry Andric readIdentificationBlock(Stream); 5623d88c1a5aSDimitry Andric if (!ProducerIdentificationOrErr) 5624d88c1a5aSDimitry Andric return ProducerIdentificationOrErr.takeError(); 562539d628a0SDimitry Andric 5626d88c1a5aSDimitry Andric ProducerIdentification = *ProducerIdentificationOrErr; 5627dff0c46cSDimitry Andric } 5628dff0c46cSDimitry Andric 5629d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56306bc11b14SDimitry Andric auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 56316bc11b14SDimitry Andric Context); 5632d88c1a5aSDimitry Andric 5633d88c1a5aSDimitry Andric std::unique_ptr<Module> M = 5634d88c1a5aSDimitry Andric llvm::make_unique<Module>(ModuleIdentifier, Context); 5635d88c1a5aSDimitry Andric M->setMaterializer(R); 5636d88c1a5aSDimitry Andric 5637d88c1a5aSDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 5638d88c1a5aSDimitry Andric if (Error Err = 5639d88c1a5aSDimitry Andric R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting)) 5640d88c1a5aSDimitry Andric return std::move(Err); 5641d88c1a5aSDimitry Andric 5642d88c1a5aSDimitry Andric if (MaterializeAll) { 5643d88c1a5aSDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 5644d88c1a5aSDimitry Andric if (Error Err = M->materializeAll()) 5645d88c1a5aSDimitry Andric return std::move(Err); 5646d88c1a5aSDimitry Andric } else { 5647d88c1a5aSDimitry Andric // Resolve forward references from blockaddresses. 5648d88c1a5aSDimitry Andric if (Error Err = R->materializeForwardReferencedFunctions()) 5649d88c1a5aSDimitry Andric return std::move(Err); 5650d88c1a5aSDimitry Andric } 5651d88c1a5aSDimitry Andric return std::move(M); 5652f22ef01cSRoman Divacky } 5653f22ef01cSRoman Divacky 5654d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5655d88c1a5aSDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 5656d88c1a5aSDimitry Andric bool IsImporting) { 5657d88c1a5aSDimitry Andric return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting); 56587d523365SDimitry Andric } 56597d523365SDimitry Andric 5660f37b6182SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex. 566124d58133SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the 566224d58133SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for 566324d58133SDimitry Andric // regular LTO modules). 5664f37b6182SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 566524d58133SDimitry Andric StringRef ModulePath, uint64_t ModuleId) { 5666f37b6182SDimitry Andric BitstreamCursor Stream(Buffer); 5667f37b6182SDimitry Andric Stream.JumpToBit(ModuleBit); 5668f37b6182SDimitry Andric 5669f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 567024d58133SDimitry Andric ModulePath, ModuleId); 5671f37b6182SDimitry Andric return R.parseModule(); 5672f37b6182SDimitry Andric } 5673f37b6182SDimitry Andric 56747d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 5675d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 5676d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 5677d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56787d523365SDimitry Andric 56793ca95b02SDimitry Andric auto Index = llvm::make_unique<ModuleSummaryIndex>(); 5680f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 5681f37b6182SDimitry Andric ModuleIdentifier, 0); 56827d523365SDimitry Andric 5683f37b6182SDimitry Andric if (Error Err = R.parseModule()) 5684d88c1a5aSDimitry Andric return std::move(Err); 56857d523365SDimitry Andric 56867d523365SDimitry Andric return std::move(Index); 56877d523365SDimitry Andric } 56887d523365SDimitry Andric 56893ca95b02SDimitry Andric // Check if the given bitcode buffer contains a global value summary block. 569024d58133SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 5691d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer); 5692d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit); 56937d523365SDimitry Andric 5694d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5695d88c1a5aSDimitry Andric return error("Invalid record"); 5696d88c1a5aSDimitry Andric 5697d88c1a5aSDimitry Andric while (true) { 5698d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance(); 5699d88c1a5aSDimitry Andric 5700d88c1a5aSDimitry Andric switch (Entry.Kind) { 5701d88c1a5aSDimitry Andric case BitstreamEntry::Error: 5702d88c1a5aSDimitry Andric return error("Malformed block"); 5703d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock: 570424d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false}; 57057d523365SDimitry Andric 5706d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: 5707d88c1a5aSDimitry Andric if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) 570824d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true}; 570924d58133SDimitry Andric 571024d58133SDimitry Andric if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) 571124d58133SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true}; 57127d523365SDimitry Andric 5713d88c1a5aSDimitry Andric // Ignore other sub-blocks. 5714d88c1a5aSDimitry Andric if (Stream.SkipBlock()) 5715d88c1a5aSDimitry Andric return error("Malformed block"); 5716d88c1a5aSDimitry Andric continue; 5717d88c1a5aSDimitry Andric 5718d88c1a5aSDimitry Andric case BitstreamEntry::Record: 5719d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID); 5720d88c1a5aSDimitry Andric continue; 5721d88c1a5aSDimitry Andric } 5722d88c1a5aSDimitry Andric } 5723d88c1a5aSDimitry Andric } 5724d88c1a5aSDimitry Andric 5725d88c1a5aSDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 5726d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 5727d88c1a5aSDimitry Andric if (!MsOrErr) 5728d88c1a5aSDimitry Andric return MsOrErr.takeError(); 5729d88c1a5aSDimitry Andric 5730d88c1a5aSDimitry Andric if (MsOrErr->size() != 1) 5731d88c1a5aSDimitry Andric return error("Expected a single module"); 5732d88c1a5aSDimitry Andric 5733d88c1a5aSDimitry Andric return (*MsOrErr)[0]; 5734d88c1a5aSDimitry Andric } 5735d88c1a5aSDimitry Andric 5736d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5737d88c1a5aSDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 5738d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5739d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5740d88c1a5aSDimitry Andric if (!BM) 5741d88c1a5aSDimitry Andric return BM.takeError(); 5742d88c1a5aSDimitry Andric 5743d88c1a5aSDimitry Andric return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 5744d88c1a5aSDimitry Andric } 5745d88c1a5aSDimitry Andric 5746d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 5747d88c1a5aSDimitry Andric std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 5748d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) { 5749d88c1a5aSDimitry Andric auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 5750d88c1a5aSDimitry Andric IsImporting); 5751d88c1a5aSDimitry Andric if (MOrErr) 5752d88c1a5aSDimitry Andric (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 5753d88c1a5aSDimitry Andric return MOrErr; 5754d88c1a5aSDimitry Andric } 5755d88c1a5aSDimitry Andric 5756d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> 5757d88c1a5aSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context) { 5758d88c1a5aSDimitry Andric return getModuleImpl(Context, true, false, false); 5759d88c1a5aSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 5760d88c1a5aSDimitry Andric // written. We must defer until the Module has been fully materialized. 5761d88c1a5aSDimitry Andric } 5762d88c1a5aSDimitry Andric 5763d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 5764d88c1a5aSDimitry Andric LLVMContext &Context) { 5765d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5766d88c1a5aSDimitry Andric if (!BM) 5767d88c1a5aSDimitry Andric return BM.takeError(); 5768d88c1a5aSDimitry Andric 5769d88c1a5aSDimitry Andric return BM->parseModule(Context); 5770d88c1a5aSDimitry Andric } 5771d88c1a5aSDimitry Andric 5772d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 5773d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5774d88c1a5aSDimitry Andric if (!StreamOrErr) 5775d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5776d88c1a5aSDimitry Andric 5777d88c1a5aSDimitry Andric return readTriple(*StreamOrErr); 5778d88c1a5aSDimitry Andric } 5779d88c1a5aSDimitry Andric 5780d88c1a5aSDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 5781d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5782d88c1a5aSDimitry Andric if (!StreamOrErr) 5783d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5784d88c1a5aSDimitry Andric 5785d88c1a5aSDimitry Andric return hasObjCCategory(*StreamOrErr); 5786d88c1a5aSDimitry Andric } 5787d88c1a5aSDimitry Andric 5788d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 5789d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 5790d88c1a5aSDimitry Andric if (!StreamOrErr) 5791d88c1a5aSDimitry Andric return StreamOrErr.takeError(); 5792d88c1a5aSDimitry Andric 5793d88c1a5aSDimitry Andric return readIdentificationCode(*StreamOrErr); 5794d88c1a5aSDimitry Andric } 5795d88c1a5aSDimitry Andric 5796f37b6182SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 5797f37b6182SDimitry Andric ModuleSummaryIndex &CombinedIndex, 579824d58133SDimitry Andric uint64_t ModuleId) { 5799f37b6182SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5800f37b6182SDimitry Andric if (!BM) 5801f37b6182SDimitry Andric return BM.takeError(); 5802f37b6182SDimitry Andric 580324d58133SDimitry Andric return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 5804f37b6182SDimitry Andric } 5805f37b6182SDimitry Andric 5806d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 5807d88c1a5aSDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 5808d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5809d88c1a5aSDimitry Andric if (!BM) 5810d88c1a5aSDimitry Andric return BM.takeError(); 5811d88c1a5aSDimitry Andric 5812d88c1a5aSDimitry Andric return BM->getSummary(); 5813d88c1a5aSDimitry Andric } 5814d88c1a5aSDimitry Andric 581524d58133SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 5816d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer); 5817d88c1a5aSDimitry Andric if (!BM) 5818d88c1a5aSDimitry Andric return BM.takeError(); 5819d88c1a5aSDimitry Andric 582024d58133SDimitry Andric return BM->getLTOInfo(); 58217d523365SDimitry Andric } 5822f37b6182SDimitry Andric 5823f37b6182SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> 58245517e702SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path, 58255517e702SDimitry Andric bool IgnoreEmptyThinLTOIndexFile) { 5826f37b6182SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 5827f37b6182SDimitry Andric MemoryBuffer::getFileOrSTDIN(Path); 5828f37b6182SDimitry Andric if (!FileOrErr) 5829f37b6182SDimitry Andric return errorCodeToError(FileOrErr.getError()); 5830f37b6182SDimitry Andric if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 5831f37b6182SDimitry Andric return nullptr; 5832f37b6182SDimitry Andric return getModuleSummaryIndex(**FileOrErr); 5833f37b6182SDimitry Andric } 5834