1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Bitcode/BitcodeReader.h" 10 #include "MetadataLoader.h" 11 #include "ValueList.h" 12 #include "llvm/ADT/APFloat.h" 13 #include "llvm/ADT/APInt.h" 14 #include "llvm/ADT/ArrayRef.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/Twine.h" 21 #include "llvm/Bitcode/BitcodeCommon.h" 22 #include "llvm/Bitcode/LLVMBitCodes.h" 23 #include "llvm/Bitstream/BitstreamReader.h" 24 #include "llvm/Config/llvm-config.h" 25 #include "llvm/IR/Argument.h" 26 #include "llvm/IR/AttributeMask.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/AutoUpgrade.h" 29 #include "llvm/IR/BasicBlock.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/Comdat.h" 32 #include "llvm/IR/Constant.h" 33 #include "llvm/IR/Constants.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/DebugInfo.h" 36 #include "llvm/IR/DebugInfoMetadata.h" 37 #include "llvm/IR/DebugLoc.h" 38 #include "llvm/IR/DerivedTypes.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GVMaterializer.h" 41 #include "llvm/IR/GetElementPtrTypeIterator.h" 42 #include "llvm/IR/GlobalAlias.h" 43 #include "llvm/IR/GlobalIFunc.h" 44 #include "llvm/IR/GlobalObject.h" 45 #include "llvm/IR/GlobalValue.h" 46 #include "llvm/IR/GlobalVariable.h" 47 #include "llvm/IR/InlineAsm.h" 48 #include "llvm/IR/InstIterator.h" 49 #include "llvm/IR/InstrTypes.h" 50 #include "llvm/IR/Instruction.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/Intrinsics.h" 53 #include "llvm/IR/IntrinsicsAArch64.h" 54 #include "llvm/IR/IntrinsicsARM.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/ModuleSummaryIndex.h" 59 #include "llvm/IR/Operator.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/Value.h" 62 #include "llvm/IR/Verifier.h" 63 #include "llvm/Support/AtomicOrdering.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Compiler.h" 67 #include "llvm/Support/Debug.h" 68 #include "llvm/Support/Error.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/ErrorOr.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/MemoryBuffer.h" 73 #include "llvm/Support/ModRef.h" 74 #include "llvm/Support/raw_ostream.h" 75 #include "llvm/TargetParser/Triple.h" 76 #include <algorithm> 77 #include <cassert> 78 #include <cstddef> 79 #include <cstdint> 80 #include <deque> 81 #include <map> 82 #include <memory> 83 #include <optional> 84 #include <set> 85 #include <string> 86 #include <system_error> 87 #include <tuple> 88 #include <utility> 89 #include <vector> 90 91 using namespace llvm; 92 93 static cl::opt<bool> PrintSummaryGUIDs( 94 "print-summary-global-ids", cl::init(false), cl::Hidden, 95 cl::desc( 96 "Print the global id for each value when reading the module summary")); 97 98 static cl::opt<bool> ExpandConstantExprs( 99 "expand-constant-exprs", cl::Hidden, 100 cl::desc( 101 "Expand constant expressions to instructions for testing purposes")); 102 103 // Declare external flag for whether we're using the new debug-info format. 104 extern llvm::cl::opt<bool> UseNewDbgInfoFormat; 105 106 namespace { 107 108 enum { 109 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 110 }; 111 112 } // end anonymous namespace 113 114 static Error error(const Twine &Message) { 115 return make_error<StringError>( 116 Message, make_error_code(BitcodeError::CorruptedBitcode)); 117 } 118 119 static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) { 120 if (!Stream.canSkipToPos(4)) 121 return createStringError(std::errc::illegal_byte_sequence, 122 "file too small to contain bitcode header"); 123 for (unsigned C : {'B', 'C'}) 124 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) { 125 if (Res.get() != C) 126 return createStringError(std::errc::illegal_byte_sequence, 127 "file doesn't start with bitcode header"); 128 } else 129 return Res.takeError(); 130 for (unsigned C : {0x0, 0xC, 0xE, 0xD}) 131 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) { 132 if (Res.get() != C) 133 return createStringError(std::errc::illegal_byte_sequence, 134 "file doesn't start with bitcode header"); 135 } else 136 return Res.takeError(); 137 return Error::success(); 138 } 139 140 static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) { 141 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart(); 142 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize(); 143 144 if (Buffer.getBufferSize() & 3) 145 return error("Invalid bitcode signature"); 146 147 // If we have a wrapper header, parse it and ignore the non-bc file contents. 148 // The magic number is 0x0B17C0DE stored in little endian. 149 if (isBitcodeWrapper(BufPtr, BufEnd)) 150 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 151 return error("Invalid bitcode wrapper header"); 152 153 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd)); 154 if (Error Err = hasInvalidBitcodeHeader(Stream)) 155 return std::move(Err); 156 157 return std::move(Stream); 158 } 159 160 /// Convert a string from a record into an std::string, return true on failure. 161 template <typename StrTy> 162 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 163 StrTy &Result) { 164 if (Idx > Record.size()) 165 return true; 166 167 Result.append(Record.begin() + Idx, Record.end()); 168 return false; 169 } 170 171 // Strip all the TBAA attachment for the module. 172 static void stripTBAA(Module *M) { 173 for (auto &F : *M) { 174 if (F.isMaterializable()) 175 continue; 176 for (auto &I : instructions(F)) 177 I.setMetadata(LLVMContext::MD_tbaa, nullptr); 178 } 179 } 180 181 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the 182 /// "epoch" encoded in the bitcode, and return the producer name if any. 183 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) { 184 if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 185 return std::move(Err); 186 187 // Read all the records. 188 SmallVector<uint64_t, 64> Record; 189 190 std::string ProducerIdentification; 191 192 while (true) { 193 BitstreamEntry Entry; 194 if (Error E = Stream.advance().moveInto(Entry)) 195 return std::move(E); 196 197 switch (Entry.Kind) { 198 default: 199 case BitstreamEntry::Error: 200 return error("Malformed block"); 201 case BitstreamEntry::EndBlock: 202 return ProducerIdentification; 203 case BitstreamEntry::Record: 204 // The interesting case. 205 break; 206 } 207 208 // Read a record. 209 Record.clear(); 210 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 211 if (!MaybeBitCode) 212 return MaybeBitCode.takeError(); 213 switch (MaybeBitCode.get()) { 214 default: // Default behavior: reject 215 return error("Invalid value"); 216 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N] 217 convertToString(Record, 0, ProducerIdentification); 218 break; 219 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 220 unsigned epoch = (unsigned)Record[0]; 221 if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 222 return error( 223 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 224 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 225 } 226 } 227 } 228 } 229 } 230 231 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) { 232 // We expect a number of well-defined blocks, though we don't necessarily 233 // need to understand them all. 234 while (true) { 235 if (Stream.AtEndOfStream()) 236 return ""; 237 238 BitstreamEntry Entry; 239 if (Error E = Stream.advance().moveInto(Entry)) 240 return std::move(E); 241 242 switch (Entry.Kind) { 243 case BitstreamEntry::EndBlock: 244 case BitstreamEntry::Error: 245 return error("Malformed block"); 246 247 case BitstreamEntry::SubBlock: 248 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) 249 return readIdentificationBlock(Stream); 250 251 // Ignore other sub-blocks. 252 if (Error Err = Stream.SkipBlock()) 253 return std::move(Err); 254 continue; 255 case BitstreamEntry::Record: 256 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 257 return std::move(E); 258 continue; 259 } 260 } 261 } 262 263 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) { 264 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 265 return std::move(Err); 266 267 SmallVector<uint64_t, 64> Record; 268 // Read all the records for this module. 269 270 while (true) { 271 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 272 if (!MaybeEntry) 273 return MaybeEntry.takeError(); 274 BitstreamEntry Entry = MaybeEntry.get(); 275 276 switch (Entry.Kind) { 277 case BitstreamEntry::SubBlock: // Handled for us already. 278 case BitstreamEntry::Error: 279 return error("Malformed block"); 280 case BitstreamEntry::EndBlock: 281 return false; 282 case BitstreamEntry::Record: 283 // The interesting case. 284 break; 285 } 286 287 // Read a record. 288 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 289 if (!MaybeRecord) 290 return MaybeRecord.takeError(); 291 switch (MaybeRecord.get()) { 292 default: 293 break; // Default behavior, ignore unknown content. 294 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 295 std::string S; 296 if (convertToString(Record, 0, S)) 297 return error("Invalid section name record"); 298 // Check for the i386 and other (x86_64, ARM) conventions 299 if (S.find("__DATA,__objc_catlist") != std::string::npos || 300 S.find("__OBJC,__category") != std::string::npos) 301 return true; 302 break; 303 } 304 } 305 Record.clear(); 306 } 307 llvm_unreachable("Exit infinite loop"); 308 } 309 310 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) { 311 // We expect a number of well-defined blocks, though we don't necessarily 312 // need to understand them all. 313 while (true) { 314 BitstreamEntry Entry; 315 if (Error E = Stream.advance().moveInto(Entry)) 316 return std::move(E); 317 318 switch (Entry.Kind) { 319 case BitstreamEntry::Error: 320 return error("Malformed block"); 321 case BitstreamEntry::EndBlock: 322 return false; 323 324 case BitstreamEntry::SubBlock: 325 if (Entry.ID == bitc::MODULE_BLOCK_ID) 326 return hasObjCCategoryInModule(Stream); 327 328 // Ignore other sub-blocks. 329 if (Error Err = Stream.SkipBlock()) 330 return std::move(Err); 331 continue; 332 333 case BitstreamEntry::Record: 334 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 335 return std::move(E); 336 continue; 337 } 338 } 339 } 340 341 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) { 342 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 343 return std::move(Err); 344 345 SmallVector<uint64_t, 64> Record; 346 347 std::string Triple; 348 349 // Read all the records for this module. 350 while (true) { 351 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 352 if (!MaybeEntry) 353 return MaybeEntry.takeError(); 354 BitstreamEntry Entry = MaybeEntry.get(); 355 356 switch (Entry.Kind) { 357 case BitstreamEntry::SubBlock: // Handled for us already. 358 case BitstreamEntry::Error: 359 return error("Malformed block"); 360 case BitstreamEntry::EndBlock: 361 return Triple; 362 case BitstreamEntry::Record: 363 // The interesting case. 364 break; 365 } 366 367 // Read a record. 368 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 369 if (!MaybeRecord) 370 return MaybeRecord.takeError(); 371 switch (MaybeRecord.get()) { 372 default: break; // Default behavior, ignore unknown content. 373 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 374 std::string S; 375 if (convertToString(Record, 0, S)) 376 return error("Invalid triple record"); 377 Triple = S; 378 break; 379 } 380 } 381 Record.clear(); 382 } 383 llvm_unreachable("Exit infinite loop"); 384 } 385 386 static Expected<std::string> readTriple(BitstreamCursor &Stream) { 387 // We expect a number of well-defined blocks, though we don't necessarily 388 // need to understand them all. 389 while (true) { 390 Expected<BitstreamEntry> MaybeEntry = Stream.advance(); 391 if (!MaybeEntry) 392 return MaybeEntry.takeError(); 393 BitstreamEntry Entry = MaybeEntry.get(); 394 395 switch (Entry.Kind) { 396 case BitstreamEntry::Error: 397 return error("Malformed block"); 398 case BitstreamEntry::EndBlock: 399 return ""; 400 401 case BitstreamEntry::SubBlock: 402 if (Entry.ID == bitc::MODULE_BLOCK_ID) 403 return readModuleTriple(Stream); 404 405 // Ignore other sub-blocks. 406 if (Error Err = Stream.SkipBlock()) 407 return std::move(Err); 408 continue; 409 410 case BitstreamEntry::Record: 411 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID)) 412 continue; 413 else 414 return Skipped.takeError(); 415 } 416 } 417 } 418 419 namespace { 420 421 class BitcodeReaderBase { 422 protected: 423 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab) 424 : Stream(std::move(Stream)), Strtab(Strtab) { 425 this->Stream.setBlockInfo(&BlockInfo); 426 } 427 428 BitstreamBlockInfo BlockInfo; 429 BitstreamCursor Stream; 430 StringRef Strtab; 431 432 /// In version 2 of the bitcode we store names of global values and comdats in 433 /// a string table rather than in the VST. 434 bool UseStrtab = false; 435 436 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record); 437 438 /// If this module uses a string table, pop the reference to the string table 439 /// and return the referenced string and the rest of the record. Otherwise 440 /// just return the record itself. 441 std::pair<StringRef, ArrayRef<uint64_t>> 442 readNameFromStrtab(ArrayRef<uint64_t> Record); 443 444 Error readBlockInfo(); 445 446 // Contains an arbitrary and optional string identifying the bitcode producer 447 std::string ProducerIdentification; 448 449 Error error(const Twine &Message); 450 }; 451 452 } // end anonymous namespace 453 454 Error BitcodeReaderBase::error(const Twine &Message) { 455 std::string FullMsg = Message.str(); 456 if (!ProducerIdentification.empty()) 457 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " + 458 LLVM_VERSION_STRING "')"; 459 return ::error(FullMsg); 460 } 461 462 Expected<unsigned> 463 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) { 464 if (Record.empty()) 465 return error("Invalid version record"); 466 unsigned ModuleVersion = Record[0]; 467 if (ModuleVersion > 2) 468 return error("Invalid value"); 469 UseStrtab = ModuleVersion >= 2; 470 return ModuleVersion; 471 } 472 473 std::pair<StringRef, ArrayRef<uint64_t>> 474 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) { 475 if (!UseStrtab) 476 return {"", Record}; 477 // Invalid reference. Let the caller complain about the record being empty. 478 if (Record[0] + Record[1] > Strtab.size()) 479 return {"", {}}; 480 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)}; 481 } 482 483 namespace { 484 485 /// This represents a constant expression or constant aggregate using a custom 486 /// structure internal to the bitcode reader. Later, this structure will be 487 /// expanded by materializeValue() either into a constant expression/aggregate, 488 /// or into an instruction sequence at the point of use. This allows us to 489 /// upgrade bitcode using constant expressions even if this kind of constant 490 /// expression is no longer supported. 491 class BitcodeConstant final : public Value, 492 TrailingObjects<BitcodeConstant, unsigned> { 493 friend TrailingObjects; 494 495 // Value subclass ID: Pick largest possible value to avoid any clashes. 496 static constexpr uint8_t SubclassID = 255; 497 498 public: 499 // Opcodes used for non-expressions. This includes constant aggregates 500 // (struct, array, vector) that might need expansion, as well as non-leaf 501 // constants that don't need expansion (no_cfi, dso_local, blockaddress), 502 // but still go through BitcodeConstant to avoid different uselist orders 503 // between the two cases. 504 static constexpr uint8_t ConstantStructOpcode = 255; 505 static constexpr uint8_t ConstantArrayOpcode = 254; 506 static constexpr uint8_t ConstantVectorOpcode = 253; 507 static constexpr uint8_t NoCFIOpcode = 252; 508 static constexpr uint8_t DSOLocalEquivalentOpcode = 251; 509 static constexpr uint8_t BlockAddressOpcode = 250; 510 static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode; 511 512 // Separate struct to make passing different number of parameters to 513 // BitcodeConstant::create() more convenient. 514 struct ExtraInfo { 515 uint8_t Opcode; 516 uint8_t Flags; 517 unsigned Extra; 518 Type *SrcElemTy; 519 520 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0, 521 Type *SrcElemTy = nullptr) 522 : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {} 523 }; 524 525 uint8_t Opcode; 526 uint8_t Flags; 527 unsigned NumOperands; 528 unsigned Extra; // GEP inrange index or blockaddress BB id. 529 Type *SrcElemTy; // GEP source element type. 530 531 private: 532 BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs) 533 : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags), 534 NumOperands(OpIDs.size()), Extra(Info.Extra), 535 SrcElemTy(Info.SrcElemTy) { 536 std::uninitialized_copy(OpIDs.begin(), OpIDs.end(), 537 getTrailingObjects<unsigned>()); 538 } 539 540 BitcodeConstant &operator=(const BitcodeConstant &) = delete; 541 542 public: 543 static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty, 544 const ExtraInfo &Info, 545 ArrayRef<unsigned> OpIDs) { 546 void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()), 547 alignof(BitcodeConstant)); 548 return new (Mem) BitcodeConstant(Ty, Info, OpIDs); 549 } 550 551 static bool classof(const Value *V) { return V->getValueID() == SubclassID; } 552 553 ArrayRef<unsigned> getOperandIDs() const { 554 return ArrayRef(getTrailingObjects<unsigned>(), NumOperands); 555 } 556 557 std::optional<unsigned> getInRangeIndex() const { 558 assert(Opcode == Instruction::GetElementPtr); 559 if (Extra == (unsigned)-1) 560 return std::nullopt; 561 return Extra; 562 } 563 564 const char *getOpcodeName() const { 565 return Instruction::getOpcodeName(Opcode); 566 } 567 }; 568 569 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer { 570 LLVMContext &Context; 571 Module *TheModule = nullptr; 572 // Next offset to start scanning for lazy parsing of function bodies. 573 uint64_t NextUnreadBit = 0; 574 // Last function offset found in the VST. 575 uint64_t LastFunctionBlockBit = 0; 576 bool SeenValueSymbolTable = false; 577 uint64_t VSTOffset = 0; 578 579 std::vector<std::string> SectionTable; 580 std::vector<std::string> GCTable; 581 582 std::vector<Type *> TypeList; 583 /// Track type IDs of contained types. Order is the same as the contained 584 /// types of a Type*. This is used during upgrades of typed pointer IR in 585 /// opaque pointer mode. 586 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs; 587 /// In some cases, we need to create a type ID for a type that was not 588 /// explicitly encoded in the bitcode, or we don't know about at the current 589 /// point. For example, a global may explicitly encode the value type ID, but 590 /// not have a type ID for the pointer to value type, for which we create a 591 /// virtual type ID instead. This map stores the new type ID that was created 592 /// for the given pair of Type and contained type ID. 593 DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs; 594 DenseMap<Function *, unsigned> FunctionTypeIDs; 595 /// Allocator for BitcodeConstants. This should come before ValueList, 596 /// because the ValueList might hold ValueHandles to these constants, so 597 /// ValueList must be destroyed before Alloc. 598 BumpPtrAllocator Alloc; 599 BitcodeReaderValueList ValueList; 600 std::optional<MetadataLoader> MDLoader; 601 std::vector<Comdat *> ComdatList; 602 DenseSet<GlobalObject *> ImplicitComdatObjects; 603 SmallVector<Instruction *, 64> InstructionList; 604 605 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits; 606 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits; 607 608 struct FunctionOperandInfo { 609 Function *F; 610 unsigned PersonalityFn; 611 unsigned Prefix; 612 unsigned Prologue; 613 }; 614 std::vector<FunctionOperandInfo> FunctionOperands; 615 616 /// The set of attributes by index. Index zero in the file is for null, and 617 /// is thus not represented here. As such all indices are off by one. 618 std::vector<AttributeList> MAttributes; 619 620 /// The set of attribute groups. 621 std::map<unsigned, AttributeList> MAttributeGroups; 622 623 /// While parsing a function body, this is a list of the basic blocks for the 624 /// function. 625 std::vector<BasicBlock*> FunctionBBs; 626 627 // When reading the module header, this list is populated with functions that 628 // have bodies later in the file. 629 std::vector<Function*> FunctionsWithBodies; 630 631 // When intrinsic functions are encountered which require upgrading they are 632 // stored here with their replacement function. 633 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>; 634 UpdatedIntrinsicMap UpgradedIntrinsics; 635 636 // Several operations happen after the module header has been read, but 637 // before function bodies are processed. This keeps track of whether 638 // we've done this yet. 639 bool SeenFirstFunctionBody = false; 640 641 /// When function bodies are initially scanned, this map contains info about 642 /// where to find deferred function body in the stream. 643 DenseMap<Function*, uint64_t> DeferredFunctionInfo; 644 645 /// When Metadata block is initially scanned when parsing the module, we may 646 /// choose to defer parsing of the metadata. This vector contains info about 647 /// which Metadata blocks are deferred. 648 std::vector<uint64_t> DeferredMetadataInfo; 649 650 /// These are basic blocks forward-referenced by block addresses. They are 651 /// inserted lazily into functions when they're loaded. The basic block ID is 652 /// its index into the vector. 653 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 654 std::deque<Function *> BasicBlockFwdRefQueue; 655 656 /// These are Functions that contain BlockAddresses which refer a different 657 /// Function. When parsing the different Function, queue Functions that refer 658 /// to the different Function. Those Functions must be materialized in order 659 /// to resolve their BlockAddress constants before the different Function 660 /// gets moved into another Module. 661 std::vector<Function *> BackwardRefFunctions; 662 663 /// Indicates that we are using a new encoding for instruction operands where 664 /// most operands in the current FUNCTION_BLOCK are encoded relative to the 665 /// instruction number, for a more compact encoding. Some instruction 666 /// operands are not relative to the instruction ID: basic block numbers, and 667 /// types. Once the old style function blocks have been phased out, we would 668 /// not need this flag. 669 bool UseRelativeIDs = false; 670 671 /// True if all functions will be materialized, negating the need to process 672 /// (e.g.) blockaddress forward references. 673 bool WillMaterializeAllForwardRefs = false; 674 675 bool StripDebugInfo = false; 676 TBAAVerifier TBAAVerifyHelper; 677 678 std::vector<std::string> BundleTags; 679 SmallVector<SyncScope::ID, 8> SSIDs; 680 681 std::optional<ValueTypeCallbackTy> ValueTypeCallback; 682 683 public: 684 BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 685 StringRef ProducerIdentification, LLVMContext &Context); 686 687 Error materializeForwardReferencedFunctions(); 688 689 Error materialize(GlobalValue *GV) override; 690 Error materializeModule() override; 691 std::vector<StructType *> getIdentifiedStructTypes() const override; 692 693 /// Main interface to parsing a bitcode buffer. 694 /// \returns true if an error occurred. 695 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 696 bool IsImporting, ParserCallbacks Callbacks = {}); 697 698 static uint64_t decodeSignRotatedValue(uint64_t V); 699 700 /// Materialize any deferred Metadata block. 701 Error materializeMetadata() override; 702 703 void setStripDebugInfo() override; 704 705 private: 706 std::vector<StructType *> IdentifiedStructTypes; 707 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 708 StructType *createIdentifiedStructType(LLVMContext &Context); 709 710 static constexpr unsigned InvalidTypeID = ~0u; 711 712 Type *getTypeByID(unsigned ID); 713 Type *getPtrElementTypeByID(unsigned ID); 714 unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0); 715 unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {}); 716 717 void callValueTypeCallback(Value *F, unsigned TypeID); 718 Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB); 719 Expected<Constant *> getValueForInitializer(unsigned ID); 720 721 Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID, 722 BasicBlock *ConstExprInsertBB) { 723 if (Ty && Ty->isMetadataTy()) 724 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 725 return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB); 726 } 727 728 Metadata *getFnMetadataByID(unsigned ID) { 729 return MDLoader->getMetadataFwdRefOrLoad(ID); 730 } 731 732 BasicBlock *getBasicBlock(unsigned ID) const { 733 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 734 return FunctionBBs[ID]; 735 } 736 737 AttributeList getAttributes(unsigned i) const { 738 if (i-1 < MAttributes.size()) 739 return MAttributes[i-1]; 740 return AttributeList(); 741 } 742 743 /// Read a value/type pair out of the specified record from slot 'Slot'. 744 /// Increment Slot past the number of slots used in the record. Return true on 745 /// failure. 746 bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 747 unsigned InstNum, Value *&ResVal, unsigned &TypeID, 748 BasicBlock *ConstExprInsertBB) { 749 if (Slot == Record.size()) return true; 750 unsigned ValNo = (unsigned)Record[Slot++]; 751 // Adjust the ValNo, if it was encoded relative to the InstNum. 752 if (UseRelativeIDs) 753 ValNo = InstNum - ValNo; 754 if (ValNo < InstNum) { 755 // If this is not a forward reference, just return the value we already 756 // have. 757 TypeID = ValueList.getTypeID(ValNo); 758 ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB); 759 assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) && 760 "Incorrect type ID stored for value"); 761 return ResVal == nullptr; 762 } 763 if (Slot == Record.size()) 764 return true; 765 766 TypeID = (unsigned)Record[Slot++]; 767 ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID, 768 ConstExprInsertBB); 769 return ResVal == nullptr; 770 } 771 772 /// Read a value out of the specified record from slot 'Slot'. Increment Slot 773 /// past the number of slots used by the value in the record. Return true if 774 /// there is an error. 775 bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 776 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, 777 BasicBlock *ConstExprInsertBB) { 778 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB)) 779 return true; 780 // All values currently take a single record slot. 781 ++Slot; 782 return false; 783 } 784 785 /// Like popValue, but does not increment the Slot number. 786 bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 787 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal, 788 BasicBlock *ConstExprInsertBB) { 789 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB); 790 return ResVal == nullptr; 791 } 792 793 /// Version of getValue that returns ResVal directly, or 0 if there is an 794 /// error. 795 Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 796 unsigned InstNum, Type *Ty, unsigned TyID, 797 BasicBlock *ConstExprInsertBB) { 798 if (Slot == Record.size()) return nullptr; 799 unsigned ValNo = (unsigned)Record[Slot]; 800 // Adjust the ValNo, if it was encoded relative to the InstNum. 801 if (UseRelativeIDs) 802 ValNo = InstNum - ValNo; 803 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); 804 } 805 806 /// Like getValue, but decodes signed VBRs. 807 Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot, 808 unsigned InstNum, Type *Ty, unsigned TyID, 809 BasicBlock *ConstExprInsertBB) { 810 if (Slot == Record.size()) return nullptr; 811 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 812 // Adjust the ValNo, if it was encoded relative to the InstNum. 813 if (UseRelativeIDs) 814 ValNo = InstNum - ValNo; 815 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB); 816 } 817 818 /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the 819 /// corresponding argument's pointee type. Also upgrades intrinsics that now 820 /// require an elementtype attribute. 821 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys); 822 823 /// Converts alignment exponent (i.e. power of two (or zero)) to the 824 /// corresponding alignment to use. If alignment is too large, returns 825 /// a corresponding error code. 826 Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment); 827 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 828 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false, 829 ParserCallbacks Callbacks = {}); 830 831 Error parseComdatRecord(ArrayRef<uint64_t> Record); 832 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record); 833 Error parseFunctionRecord(ArrayRef<uint64_t> Record); 834 Error parseGlobalIndirectSymbolRecord(unsigned BitCode, 835 ArrayRef<uint64_t> Record); 836 837 Error parseAttributeBlock(); 838 Error parseAttributeGroupBlock(); 839 Error parseTypeTable(); 840 Error parseTypeTableBody(); 841 Error parseOperandBundleTags(); 842 Error parseSyncScopeNames(); 843 844 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 845 unsigned NameIndex, Triple &TT); 846 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F, 847 ArrayRef<uint64_t> Record); 848 Error parseValueSymbolTable(uint64_t Offset = 0); 849 Error parseGlobalValueSymbolTable(); 850 Error parseConstants(); 851 Error rememberAndSkipFunctionBodies(); 852 Error rememberAndSkipFunctionBody(); 853 /// Save the positions of the Metadata blocks and skip parsing the blocks. 854 Error rememberAndSkipMetadata(); 855 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType); 856 Error parseFunctionBody(Function *F); 857 Error globalCleanup(); 858 Error resolveGlobalAndIndirectSymbolInits(); 859 Error parseUseLists(); 860 Error findFunctionInStream( 861 Function *F, 862 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 863 864 SyncScope::ID getDecodedSyncScopeID(unsigned Val); 865 }; 866 867 /// Class to manage reading and parsing function summary index bitcode 868 /// files/sections. 869 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase { 870 /// The module index built during parsing. 871 ModuleSummaryIndex &TheIndex; 872 873 /// Indicates whether we have encountered a global value summary section 874 /// yet during parsing. 875 bool SeenGlobalValSummary = false; 876 877 /// Indicates whether we have already parsed the VST, used for error checking. 878 bool SeenValueSymbolTable = false; 879 880 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 881 /// Used to enable on-demand parsing of the VST. 882 uint64_t VSTOffset = 0; 883 884 // Map to save ValueId to ValueInfo association that was recorded in the 885 // ValueSymbolTable. It is used after the VST is parsed to convert 886 // call graph edges read from the function summary from referencing 887 // callees by their ValueId to using the ValueInfo instead, which is how 888 // they are recorded in the summary index being built. 889 // We save a GUID which refers to the same global as the ValueInfo, but 890 // ignoring the linkage, i.e. for values other than local linkage they are 891 // identical (this is the second tuple member). 892 // The third tuple member is the real GUID of the ValueInfo. 893 DenseMap<unsigned, 894 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>> 895 ValueIdToValueInfoMap; 896 897 /// Map populated during module path string table parsing, from the 898 /// module ID to a string reference owned by the index's module 899 /// path string table, used to correlate with combined index 900 /// summary records. 901 DenseMap<uint64_t, StringRef> ModuleIdMap; 902 903 /// Original source file name recorded in a bitcode record. 904 std::string SourceFileName; 905 906 /// The string identifier given to this module by the client, normally the 907 /// path to the bitcode file. 908 StringRef ModulePath; 909 910 /// Callback to ask whether a symbol is the prevailing copy when invoked 911 /// during combined index building. 912 std::function<bool(GlobalValue::GUID)> IsPrevailing; 913 914 /// Saves the stack ids from the STACK_IDS record to consult when adding stack 915 /// ids from the lists in the callsite and alloc entries to the index. 916 std::vector<uint64_t> StackIds; 917 918 public: 919 ModuleSummaryIndexBitcodeReader( 920 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex, 921 StringRef ModulePath, 922 std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr); 923 924 Error parseModule(); 925 926 private: 927 void setValueGUID(uint64_t ValueID, StringRef ValueName, 928 GlobalValue::LinkageTypes Linkage, 929 StringRef SourceFileName); 930 Error parseValueSymbolTable( 931 uint64_t Offset, 932 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 933 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record); 934 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record, 935 bool IsOldProfileFormat, 936 bool HasProfile, 937 bool HasRelBF); 938 Error parseEntireSummary(unsigned ID); 939 Error parseModuleStringTable(); 940 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record); 941 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot, 942 TypeIdCompatibleVtableInfo &TypeId); 943 std::vector<FunctionSummary::ParamAccess> 944 parseParamAccesses(ArrayRef<uint64_t> Record); 945 946 template <bool AllowNullValueInfo = false> 947 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 948 getValueInfoFromValueId(unsigned ValueId); 949 950 void addThisModule(); 951 ModuleSummaryIndex::ModuleInfo *getThisModule(); 952 }; 953 954 } // end anonymous namespace 955 956 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, 957 Error Err) { 958 if (Err) { 959 std::error_code EC; 960 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) { 961 EC = EIB.convertToErrorCode(); 962 Ctx.emitError(EIB.message()); 963 }); 964 return EC; 965 } 966 return std::error_code(); 967 } 968 969 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab, 970 StringRef ProducerIdentification, 971 LLVMContext &Context) 972 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context), 973 ValueList(this->Stream.SizeInBytes(), 974 [this](unsigned ValID, BasicBlock *InsertBB) { 975 return materializeValue(ValID, InsertBB); 976 }) { 977 this->ProducerIdentification = std::string(ProducerIdentification); 978 } 979 980 Error BitcodeReader::materializeForwardReferencedFunctions() { 981 if (WillMaterializeAllForwardRefs) 982 return Error::success(); 983 984 // Prevent recursion. 985 WillMaterializeAllForwardRefs = true; 986 987 while (!BasicBlockFwdRefQueue.empty()) { 988 Function *F = BasicBlockFwdRefQueue.front(); 989 BasicBlockFwdRefQueue.pop_front(); 990 assert(F && "Expected valid function"); 991 if (!BasicBlockFwdRefs.count(F)) 992 // Already materialized. 993 continue; 994 995 // Check for a function that isn't materializable to prevent an infinite 996 // loop. When parsing a blockaddress stored in a global variable, there 997 // isn't a trivial way to check if a function will have a body without a 998 // linear search through FunctionsWithBodies, so just check it here. 999 if (!F->isMaterializable()) 1000 return error("Never resolved function from blockaddress"); 1001 1002 // Try to materialize F. 1003 if (Error Err = materialize(F)) 1004 return Err; 1005 } 1006 assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 1007 1008 for (Function *F : BackwardRefFunctions) 1009 if (Error Err = materialize(F)) 1010 return Err; 1011 BackwardRefFunctions.clear(); 1012 1013 // Reset state. 1014 WillMaterializeAllForwardRefs = false; 1015 return Error::success(); 1016 } 1017 1018 //===----------------------------------------------------------------------===// 1019 // Helper functions to implement forward reference resolution, etc. 1020 //===----------------------------------------------------------------------===// 1021 1022 static bool hasImplicitComdat(size_t Val) { 1023 switch (Val) { 1024 default: 1025 return false; 1026 case 1: // Old WeakAnyLinkage 1027 case 4: // Old LinkOnceAnyLinkage 1028 case 10: // Old WeakODRLinkage 1029 case 11: // Old LinkOnceODRLinkage 1030 return true; 1031 } 1032 } 1033 1034 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 1035 switch (Val) { 1036 default: // Map unknown/new linkages to external 1037 case 0: 1038 return GlobalValue::ExternalLinkage; 1039 case 2: 1040 return GlobalValue::AppendingLinkage; 1041 case 3: 1042 return GlobalValue::InternalLinkage; 1043 case 5: 1044 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 1045 case 6: 1046 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 1047 case 7: 1048 return GlobalValue::ExternalWeakLinkage; 1049 case 8: 1050 return GlobalValue::CommonLinkage; 1051 case 9: 1052 return GlobalValue::PrivateLinkage; 1053 case 12: 1054 return GlobalValue::AvailableExternallyLinkage; 1055 case 13: 1056 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 1057 case 14: 1058 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 1059 case 15: 1060 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 1061 case 1: // Old value with implicit comdat. 1062 case 16: 1063 return GlobalValue::WeakAnyLinkage; 1064 case 10: // Old value with implicit comdat. 1065 case 17: 1066 return GlobalValue::WeakODRLinkage; 1067 case 4: // Old value with implicit comdat. 1068 case 18: 1069 return GlobalValue::LinkOnceAnyLinkage; 1070 case 11: // Old value with implicit comdat. 1071 case 19: 1072 return GlobalValue::LinkOnceODRLinkage; 1073 } 1074 } 1075 1076 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) { 1077 FunctionSummary::FFlags Flags; 1078 Flags.ReadNone = RawFlags & 0x1; 1079 Flags.ReadOnly = (RawFlags >> 1) & 0x1; 1080 Flags.NoRecurse = (RawFlags >> 2) & 0x1; 1081 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1; 1082 Flags.NoInline = (RawFlags >> 4) & 0x1; 1083 Flags.AlwaysInline = (RawFlags >> 5) & 0x1; 1084 Flags.NoUnwind = (RawFlags >> 6) & 0x1; 1085 Flags.MayThrow = (RawFlags >> 7) & 0x1; 1086 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1; 1087 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1; 1088 return Flags; 1089 } 1090 1091 // Decode the flags for GlobalValue in the summary. The bits for each attribute: 1092 // 1093 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7, 1094 // visibility: [8, 10). 1095 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, 1096 uint64_t Version) { 1097 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage 1098 // like getDecodedLinkage() above. Any future change to the linkage enum and 1099 // to getDecodedLinkage() will need to be taken into account here as above. 1100 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits 1101 auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits 1102 RawFlags = RawFlags >> 4; 1103 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3; 1104 // The Live flag wasn't introduced until version 3. For dead stripping 1105 // to work correctly on earlier versions, we must conservatively treat all 1106 // values as live. 1107 bool Live = (RawFlags & 0x2) || Version < 3; 1108 bool Local = (RawFlags & 0x4); 1109 bool AutoHide = (RawFlags & 0x8); 1110 1111 return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport, 1112 Live, Local, AutoHide); 1113 } 1114 1115 // Decode the flags for GlobalVariable in the summary 1116 static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) { 1117 return GlobalVarSummary::GVarFlags( 1118 (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false, 1119 (RawFlags & 0x4) ? true : false, 1120 (GlobalObject::VCallVisibility)(RawFlags >> 3)); 1121 } 1122 1123 static std::pair<CalleeInfo::HotnessType, bool> 1124 getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) { 1125 CalleeInfo::HotnessType Hotness = 1126 static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits 1127 bool HasTailCall = (RawFlags & 0x8); // 1 bit 1128 return {Hotness, HasTailCall}; 1129 } 1130 1131 static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, 1132 bool &HasTailCall) { 1133 static constexpr uint64_t RelBlockFreqMask = 1134 (1 << CalleeInfo::RelBlockFreqBits) - 1; 1135 RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits 1136 HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit 1137 } 1138 1139 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 1140 switch (Val) { 1141 default: // Map unknown visibilities to default. 1142 case 0: return GlobalValue::DefaultVisibility; 1143 case 1: return GlobalValue::HiddenVisibility; 1144 case 2: return GlobalValue::ProtectedVisibility; 1145 } 1146 } 1147 1148 static GlobalValue::DLLStorageClassTypes 1149 getDecodedDLLStorageClass(unsigned Val) { 1150 switch (Val) { 1151 default: // Map unknown values to default. 1152 case 0: return GlobalValue::DefaultStorageClass; 1153 case 1: return GlobalValue::DLLImportStorageClass; 1154 case 2: return GlobalValue::DLLExportStorageClass; 1155 } 1156 } 1157 1158 static bool getDecodedDSOLocal(unsigned Val) { 1159 switch(Val) { 1160 default: // Map unknown values to preemptable. 1161 case 0: return false; 1162 case 1: return true; 1163 } 1164 } 1165 1166 static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) { 1167 switch (Val) { 1168 case 1: 1169 return CodeModel::Tiny; 1170 case 2: 1171 return CodeModel::Small; 1172 case 3: 1173 return CodeModel::Kernel; 1174 case 4: 1175 return CodeModel::Medium; 1176 case 5: 1177 return CodeModel::Large; 1178 } 1179 1180 return {}; 1181 } 1182 1183 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 1184 switch (Val) { 1185 case 0: return GlobalVariable::NotThreadLocal; 1186 default: // Map unknown non-zero value to general dynamic. 1187 case 1: return GlobalVariable::GeneralDynamicTLSModel; 1188 case 2: return GlobalVariable::LocalDynamicTLSModel; 1189 case 3: return GlobalVariable::InitialExecTLSModel; 1190 case 4: return GlobalVariable::LocalExecTLSModel; 1191 } 1192 } 1193 1194 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { 1195 switch (Val) { 1196 default: // Map unknown to UnnamedAddr::None. 1197 case 0: return GlobalVariable::UnnamedAddr::None; 1198 case 1: return GlobalVariable::UnnamedAddr::Global; 1199 case 2: return GlobalVariable::UnnamedAddr::Local; 1200 } 1201 } 1202 1203 static int getDecodedCastOpcode(unsigned Val) { 1204 switch (Val) { 1205 default: return -1; 1206 case bitc::CAST_TRUNC : return Instruction::Trunc; 1207 case bitc::CAST_ZEXT : return Instruction::ZExt; 1208 case bitc::CAST_SEXT : return Instruction::SExt; 1209 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 1210 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 1211 case bitc::CAST_UITOFP : return Instruction::UIToFP; 1212 case bitc::CAST_SITOFP : return Instruction::SIToFP; 1213 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 1214 case bitc::CAST_FPEXT : return Instruction::FPExt; 1215 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 1216 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 1217 case bitc::CAST_BITCAST : return Instruction::BitCast; 1218 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 1219 } 1220 } 1221 1222 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) { 1223 bool IsFP = Ty->isFPOrFPVectorTy(); 1224 // UnOps are only valid for int/fp or vector of int/fp types 1225 if (!IsFP && !Ty->isIntOrIntVectorTy()) 1226 return -1; 1227 1228 switch (Val) { 1229 default: 1230 return -1; 1231 case bitc::UNOP_FNEG: 1232 return IsFP ? Instruction::FNeg : -1; 1233 } 1234 } 1235 1236 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 1237 bool IsFP = Ty->isFPOrFPVectorTy(); 1238 // BinOps are only valid for int/fp or vector of int/fp types 1239 if (!IsFP && !Ty->isIntOrIntVectorTy()) 1240 return -1; 1241 1242 switch (Val) { 1243 default: 1244 return -1; 1245 case bitc::BINOP_ADD: 1246 return IsFP ? Instruction::FAdd : Instruction::Add; 1247 case bitc::BINOP_SUB: 1248 return IsFP ? Instruction::FSub : Instruction::Sub; 1249 case bitc::BINOP_MUL: 1250 return IsFP ? Instruction::FMul : Instruction::Mul; 1251 case bitc::BINOP_UDIV: 1252 return IsFP ? -1 : Instruction::UDiv; 1253 case bitc::BINOP_SDIV: 1254 return IsFP ? Instruction::FDiv : Instruction::SDiv; 1255 case bitc::BINOP_UREM: 1256 return IsFP ? -1 : Instruction::URem; 1257 case bitc::BINOP_SREM: 1258 return IsFP ? Instruction::FRem : Instruction::SRem; 1259 case bitc::BINOP_SHL: 1260 return IsFP ? -1 : Instruction::Shl; 1261 case bitc::BINOP_LSHR: 1262 return IsFP ? -1 : Instruction::LShr; 1263 case bitc::BINOP_ASHR: 1264 return IsFP ? -1 : Instruction::AShr; 1265 case bitc::BINOP_AND: 1266 return IsFP ? -1 : Instruction::And; 1267 case bitc::BINOP_OR: 1268 return IsFP ? -1 : Instruction::Or; 1269 case bitc::BINOP_XOR: 1270 return IsFP ? -1 : Instruction::Xor; 1271 } 1272 } 1273 1274 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 1275 switch (Val) { 1276 default: return AtomicRMWInst::BAD_BINOP; 1277 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 1278 case bitc::RMW_ADD: return AtomicRMWInst::Add; 1279 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 1280 case bitc::RMW_AND: return AtomicRMWInst::And; 1281 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 1282 case bitc::RMW_OR: return AtomicRMWInst::Or; 1283 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 1284 case bitc::RMW_MAX: return AtomicRMWInst::Max; 1285 case bitc::RMW_MIN: return AtomicRMWInst::Min; 1286 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 1287 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 1288 case bitc::RMW_FADD: return AtomicRMWInst::FAdd; 1289 case bitc::RMW_FSUB: return AtomicRMWInst::FSub; 1290 case bitc::RMW_FMAX: return AtomicRMWInst::FMax; 1291 case bitc::RMW_FMIN: return AtomicRMWInst::FMin; 1292 case bitc::RMW_UINC_WRAP: 1293 return AtomicRMWInst::UIncWrap; 1294 case bitc::RMW_UDEC_WRAP: 1295 return AtomicRMWInst::UDecWrap; 1296 } 1297 } 1298 1299 static AtomicOrdering getDecodedOrdering(unsigned Val) { 1300 switch (Val) { 1301 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; 1302 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; 1303 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; 1304 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; 1305 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; 1306 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; 1307 default: // Map unknown orderings to sequentially-consistent. 1308 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; 1309 } 1310 } 1311 1312 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 1313 switch (Val) { 1314 default: // Map unknown selection kinds to any. 1315 case bitc::COMDAT_SELECTION_KIND_ANY: 1316 return Comdat::Any; 1317 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 1318 return Comdat::ExactMatch; 1319 case bitc::COMDAT_SELECTION_KIND_LARGEST: 1320 return Comdat::Largest; 1321 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 1322 return Comdat::NoDeduplicate; 1323 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 1324 return Comdat::SameSize; 1325 } 1326 } 1327 1328 static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 1329 FastMathFlags FMF; 1330 if (0 != (Val & bitc::UnsafeAlgebra)) 1331 FMF.setFast(); 1332 if (0 != (Val & bitc::AllowReassoc)) 1333 FMF.setAllowReassoc(); 1334 if (0 != (Val & bitc::NoNaNs)) 1335 FMF.setNoNaNs(); 1336 if (0 != (Val & bitc::NoInfs)) 1337 FMF.setNoInfs(); 1338 if (0 != (Val & bitc::NoSignedZeros)) 1339 FMF.setNoSignedZeros(); 1340 if (0 != (Val & bitc::AllowReciprocal)) 1341 FMF.setAllowReciprocal(); 1342 if (0 != (Val & bitc::AllowContract)) 1343 FMF.setAllowContract(true); 1344 if (0 != (Val & bitc::ApproxFunc)) 1345 FMF.setApproxFunc(); 1346 return FMF; 1347 } 1348 1349 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { 1350 // A GlobalValue with local linkage cannot have a DLL storage class. 1351 if (GV->hasLocalLinkage()) 1352 return; 1353 switch (Val) { 1354 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 1355 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 1356 } 1357 } 1358 1359 Type *BitcodeReader::getTypeByID(unsigned ID) { 1360 // The type table size is always specified correctly. 1361 if (ID >= TypeList.size()) 1362 return nullptr; 1363 1364 if (Type *Ty = TypeList[ID]) 1365 return Ty; 1366 1367 // If we have a forward reference, the only possible case is when it is to a 1368 // named struct. Just create a placeholder for now. 1369 return TypeList[ID] = createIdentifiedStructType(Context); 1370 } 1371 1372 unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) { 1373 auto It = ContainedTypeIDs.find(ID); 1374 if (It == ContainedTypeIDs.end()) 1375 return InvalidTypeID; 1376 1377 if (Idx >= It->second.size()) 1378 return InvalidTypeID; 1379 1380 return It->second[Idx]; 1381 } 1382 1383 Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) { 1384 if (ID >= TypeList.size()) 1385 return nullptr; 1386 1387 Type *Ty = TypeList[ID]; 1388 if (!Ty->isPointerTy()) 1389 return nullptr; 1390 1391 return getTypeByID(getContainedTypeID(ID, 0)); 1392 } 1393 1394 unsigned BitcodeReader::getVirtualTypeID(Type *Ty, 1395 ArrayRef<unsigned> ChildTypeIDs) { 1396 unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0]; 1397 auto CacheKey = std::make_pair(Ty, ChildTypeID); 1398 auto It = VirtualTypeIDs.find(CacheKey); 1399 if (It != VirtualTypeIDs.end()) { 1400 // The cmpxchg return value is the only place we need more than one 1401 // contained type ID, however the second one will always be the same (i1), 1402 // so we don't need to include it in the cache key. This asserts that the 1403 // contained types are indeed as expected and there are no collisions. 1404 assert((ChildTypeIDs.empty() || 1405 ContainedTypeIDs[It->second] == ChildTypeIDs) && 1406 "Incorrect cached contained type IDs"); 1407 return It->second; 1408 } 1409 1410 unsigned TypeID = TypeList.size(); 1411 TypeList.push_back(Ty); 1412 if (!ChildTypeIDs.empty()) 1413 append_range(ContainedTypeIDs[TypeID], ChildTypeIDs); 1414 VirtualTypeIDs.insert({CacheKey, TypeID}); 1415 return TypeID; 1416 } 1417 1418 static bool isConstExprSupported(const BitcodeConstant *BC) { 1419 uint8_t Opcode = BC->Opcode; 1420 1421 // These are not real constant expressions, always consider them supported. 1422 if (Opcode >= BitcodeConstant::FirstSpecialOpcode) 1423 return true; 1424 1425 // If -expand-constant-exprs is set, we want to consider all expressions 1426 // as unsupported. 1427 if (ExpandConstantExprs) 1428 return false; 1429 1430 if (Instruction::isBinaryOp(Opcode)) 1431 return ConstantExpr::isSupportedBinOp(Opcode); 1432 1433 if (Instruction::isCast(Opcode)) 1434 return ConstantExpr::isSupportedCastOp(Opcode); 1435 1436 if (Opcode == Instruction::GetElementPtr) 1437 return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy); 1438 1439 switch (Opcode) { 1440 case Instruction::FNeg: 1441 case Instruction::Select: 1442 return false; 1443 default: 1444 return true; 1445 } 1446 } 1447 1448 Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID, 1449 BasicBlock *InsertBB) { 1450 // Quickly handle the case where there is no BitcodeConstant to resolve. 1451 if (StartValID < ValueList.size() && ValueList[StartValID] && 1452 !isa<BitcodeConstant>(ValueList[StartValID])) 1453 return ValueList[StartValID]; 1454 1455 SmallDenseMap<unsigned, Value *> MaterializedValues; 1456 SmallVector<unsigned> Worklist; 1457 Worklist.push_back(StartValID); 1458 while (!Worklist.empty()) { 1459 unsigned ValID = Worklist.back(); 1460 if (MaterializedValues.count(ValID)) { 1461 // Duplicate expression that was already handled. 1462 Worklist.pop_back(); 1463 continue; 1464 } 1465 1466 if (ValID >= ValueList.size() || !ValueList[ValID]) 1467 return error("Invalid value ID"); 1468 1469 Value *V = ValueList[ValID]; 1470 auto *BC = dyn_cast<BitcodeConstant>(V); 1471 if (!BC) { 1472 MaterializedValues.insert({ValID, V}); 1473 Worklist.pop_back(); 1474 continue; 1475 } 1476 1477 // Iterate in reverse, so values will get popped from the worklist in 1478 // expected order. 1479 SmallVector<Value *> Ops; 1480 for (unsigned OpID : reverse(BC->getOperandIDs())) { 1481 auto It = MaterializedValues.find(OpID); 1482 if (It != MaterializedValues.end()) 1483 Ops.push_back(It->second); 1484 else 1485 Worklist.push_back(OpID); 1486 } 1487 1488 // Some expressions have not been resolved yet, handle them first and then 1489 // revisit this one. 1490 if (Ops.size() != BC->getOperandIDs().size()) 1491 continue; 1492 std::reverse(Ops.begin(), Ops.end()); 1493 1494 SmallVector<Constant *> ConstOps; 1495 for (Value *Op : Ops) 1496 if (auto *C = dyn_cast<Constant>(Op)) 1497 ConstOps.push_back(C); 1498 1499 // Materialize as constant expression if possible. 1500 if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) { 1501 Constant *C; 1502 if (Instruction::isCast(BC->Opcode)) { 1503 C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType()); 1504 if (!C) 1505 C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType()); 1506 } else if (Instruction::isBinaryOp(BC->Opcode)) { 1507 C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags); 1508 } else { 1509 switch (BC->Opcode) { 1510 case BitcodeConstant::NoCFIOpcode: { 1511 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); 1512 if (!GV) 1513 return error("no_cfi operand must be GlobalValue"); 1514 C = NoCFIValue::get(GV); 1515 break; 1516 } 1517 case BitcodeConstant::DSOLocalEquivalentOpcode: { 1518 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]); 1519 if (!GV) 1520 return error("dso_local operand must be GlobalValue"); 1521 C = DSOLocalEquivalent::get(GV); 1522 break; 1523 } 1524 case BitcodeConstant::BlockAddressOpcode: { 1525 Function *Fn = dyn_cast<Function>(ConstOps[0]); 1526 if (!Fn) 1527 return error("blockaddress operand must be a function"); 1528 1529 // If the function is already parsed we can insert the block address 1530 // right away. 1531 BasicBlock *BB; 1532 unsigned BBID = BC->Extra; 1533 if (!BBID) 1534 // Invalid reference to entry block. 1535 return error("Invalid ID"); 1536 if (!Fn->empty()) { 1537 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1538 for (size_t I = 0, E = BBID; I != E; ++I) { 1539 if (BBI == BBE) 1540 return error("Invalid ID"); 1541 ++BBI; 1542 } 1543 BB = &*BBI; 1544 } else { 1545 // Otherwise insert a placeholder and remember it so it can be 1546 // inserted when the function is parsed. 1547 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 1548 if (FwdBBs.empty()) 1549 BasicBlockFwdRefQueue.push_back(Fn); 1550 if (FwdBBs.size() < BBID + 1) 1551 FwdBBs.resize(BBID + 1); 1552 if (!FwdBBs[BBID]) 1553 FwdBBs[BBID] = BasicBlock::Create(Context); 1554 BB = FwdBBs[BBID]; 1555 } 1556 C = BlockAddress::get(Fn, BB); 1557 break; 1558 } 1559 case BitcodeConstant::ConstantStructOpcode: 1560 C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps); 1561 break; 1562 case BitcodeConstant::ConstantArrayOpcode: 1563 C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps); 1564 break; 1565 case BitcodeConstant::ConstantVectorOpcode: 1566 C = ConstantVector::get(ConstOps); 1567 break; 1568 case Instruction::ICmp: 1569 case Instruction::FCmp: 1570 C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]); 1571 break; 1572 case Instruction::GetElementPtr: 1573 C = ConstantExpr::getGetElementPtr(BC->SrcElemTy, ConstOps[0], 1574 ArrayRef(ConstOps).drop_front(), 1575 BC->Flags, BC->getInRangeIndex()); 1576 break; 1577 case Instruction::ExtractElement: 1578 C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]); 1579 break; 1580 case Instruction::InsertElement: 1581 C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1], 1582 ConstOps[2]); 1583 break; 1584 case Instruction::ShuffleVector: { 1585 SmallVector<int, 16> Mask; 1586 ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask); 1587 C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask); 1588 break; 1589 } 1590 default: 1591 llvm_unreachable("Unhandled bitcode constant"); 1592 } 1593 } 1594 1595 // Cache resolved constant. 1596 ValueList.replaceValueWithoutRAUW(ValID, C); 1597 MaterializedValues.insert({ValID, C}); 1598 Worklist.pop_back(); 1599 continue; 1600 } 1601 1602 if (!InsertBB) 1603 return error(Twine("Value referenced by initializer is an unsupported " 1604 "constant expression of type ") + 1605 BC->getOpcodeName()); 1606 1607 // Materialize as instructions if necessary. 1608 Instruction *I; 1609 if (Instruction::isCast(BC->Opcode)) { 1610 I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0], 1611 BC->getType(), "constexpr", InsertBB); 1612 } else if (Instruction::isUnaryOp(BC->Opcode)) { 1613 I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0], 1614 "constexpr", InsertBB); 1615 } else if (Instruction::isBinaryOp(BC->Opcode)) { 1616 I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0], 1617 Ops[1], "constexpr", InsertBB); 1618 if (isa<OverflowingBinaryOperator>(I)) { 1619 if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap) 1620 I->setHasNoSignedWrap(); 1621 if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap) 1622 I->setHasNoUnsignedWrap(); 1623 } 1624 if (isa<PossiblyExactOperator>(I) && 1625 (BC->Flags & PossiblyExactOperator::IsExact)) 1626 I->setIsExact(); 1627 } else { 1628 switch (BC->Opcode) { 1629 case BitcodeConstant::ConstantVectorOpcode: { 1630 Type *IdxTy = Type::getInt32Ty(BC->getContext()); 1631 Value *V = PoisonValue::get(BC->getType()); 1632 for (auto Pair : enumerate(Ops)) { 1633 Value *Idx = ConstantInt::get(IdxTy, Pair.index()); 1634 V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins", 1635 InsertBB); 1636 } 1637 I = cast<Instruction>(V); 1638 break; 1639 } 1640 case BitcodeConstant::ConstantStructOpcode: 1641 case BitcodeConstant::ConstantArrayOpcode: { 1642 Value *V = PoisonValue::get(BC->getType()); 1643 for (auto Pair : enumerate(Ops)) 1644 V = InsertValueInst::Create(V, Pair.value(), Pair.index(), 1645 "constexpr.ins", InsertBB); 1646 I = cast<Instruction>(V); 1647 break; 1648 } 1649 case Instruction::ICmp: 1650 case Instruction::FCmp: 1651 I = CmpInst::Create((Instruction::OtherOps)BC->Opcode, 1652 (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1], 1653 "constexpr", InsertBB); 1654 break; 1655 case Instruction::GetElementPtr: 1656 I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0], 1657 ArrayRef(Ops).drop_front(), "constexpr", 1658 InsertBB); 1659 if (BC->Flags) 1660 cast<GetElementPtrInst>(I)->setIsInBounds(); 1661 break; 1662 case Instruction::Select: 1663 I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB); 1664 break; 1665 case Instruction::ExtractElement: 1666 I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB); 1667 break; 1668 case Instruction::InsertElement: 1669 I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", 1670 InsertBB); 1671 break; 1672 case Instruction::ShuffleVector: 1673 I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr", 1674 InsertBB); 1675 break; 1676 default: 1677 llvm_unreachable("Unhandled bitcode constant"); 1678 } 1679 } 1680 1681 MaterializedValues.insert({ValID, I}); 1682 Worklist.pop_back(); 1683 } 1684 1685 return MaterializedValues[StartValID]; 1686 } 1687 1688 Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) { 1689 Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr); 1690 if (!MaybeV) 1691 return MaybeV.takeError(); 1692 1693 // Result must be Constant if InsertBB is nullptr. 1694 return cast<Constant>(MaybeV.get()); 1695 } 1696 1697 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 1698 StringRef Name) { 1699 auto *Ret = StructType::create(Context, Name); 1700 IdentifiedStructTypes.push_back(Ret); 1701 return Ret; 1702 } 1703 1704 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 1705 auto *Ret = StructType::create(Context); 1706 IdentifiedStructTypes.push_back(Ret); 1707 return Ret; 1708 } 1709 1710 //===----------------------------------------------------------------------===// 1711 // Functions for parsing blocks from the bitcode file 1712 //===----------------------------------------------------------------------===// 1713 1714 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) { 1715 switch (Val) { 1716 case Attribute::EndAttrKinds: 1717 case Attribute::EmptyKey: 1718 case Attribute::TombstoneKey: 1719 llvm_unreachable("Synthetic enumerators which should never get here"); 1720 1721 case Attribute::None: return 0; 1722 case Attribute::ZExt: return 1 << 0; 1723 case Attribute::SExt: return 1 << 1; 1724 case Attribute::NoReturn: return 1 << 2; 1725 case Attribute::InReg: return 1 << 3; 1726 case Attribute::StructRet: return 1 << 4; 1727 case Attribute::NoUnwind: return 1 << 5; 1728 case Attribute::NoAlias: return 1 << 6; 1729 case Attribute::ByVal: return 1 << 7; 1730 case Attribute::Nest: return 1 << 8; 1731 case Attribute::ReadNone: return 1 << 9; 1732 case Attribute::ReadOnly: return 1 << 10; 1733 case Attribute::NoInline: return 1 << 11; 1734 case Attribute::AlwaysInline: return 1 << 12; 1735 case Attribute::OptimizeForSize: return 1 << 13; 1736 case Attribute::StackProtect: return 1 << 14; 1737 case Attribute::StackProtectReq: return 1 << 15; 1738 case Attribute::Alignment: return 31 << 16; 1739 case Attribute::NoCapture: return 1 << 21; 1740 case Attribute::NoRedZone: return 1 << 22; 1741 case Attribute::NoImplicitFloat: return 1 << 23; 1742 case Attribute::Naked: return 1 << 24; 1743 case Attribute::InlineHint: return 1 << 25; 1744 case Attribute::StackAlignment: return 7 << 26; 1745 case Attribute::ReturnsTwice: return 1 << 29; 1746 case Attribute::UWTable: return 1 << 30; 1747 case Attribute::NonLazyBind: return 1U << 31; 1748 case Attribute::SanitizeAddress: return 1ULL << 32; 1749 case Attribute::MinSize: return 1ULL << 33; 1750 case Attribute::NoDuplicate: return 1ULL << 34; 1751 case Attribute::StackProtectStrong: return 1ULL << 35; 1752 case Attribute::SanitizeThread: return 1ULL << 36; 1753 case Attribute::SanitizeMemory: return 1ULL << 37; 1754 case Attribute::NoBuiltin: return 1ULL << 38; 1755 case Attribute::Returned: return 1ULL << 39; 1756 case Attribute::Cold: return 1ULL << 40; 1757 case Attribute::Builtin: return 1ULL << 41; 1758 case Attribute::OptimizeNone: return 1ULL << 42; 1759 case Attribute::InAlloca: return 1ULL << 43; 1760 case Attribute::NonNull: return 1ULL << 44; 1761 case Attribute::JumpTable: return 1ULL << 45; 1762 case Attribute::Convergent: return 1ULL << 46; 1763 case Attribute::SafeStack: return 1ULL << 47; 1764 case Attribute::NoRecurse: return 1ULL << 48; 1765 // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately. 1766 // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately. 1767 case Attribute::SwiftSelf: return 1ULL << 51; 1768 case Attribute::SwiftError: return 1ULL << 52; 1769 case Attribute::WriteOnly: return 1ULL << 53; 1770 case Attribute::Speculatable: return 1ULL << 54; 1771 case Attribute::StrictFP: return 1ULL << 55; 1772 case Attribute::SanitizeHWAddress: return 1ULL << 56; 1773 case Attribute::NoCfCheck: return 1ULL << 57; 1774 case Attribute::OptForFuzzing: return 1ULL << 58; 1775 case Attribute::ShadowCallStack: return 1ULL << 59; 1776 case Attribute::SpeculativeLoadHardening: 1777 return 1ULL << 60; 1778 case Attribute::ImmArg: 1779 return 1ULL << 61; 1780 case Attribute::WillReturn: 1781 return 1ULL << 62; 1782 case Attribute::NoFree: 1783 return 1ULL << 63; 1784 default: 1785 // Other attributes are not supported in the raw format, 1786 // as we ran out of space. 1787 return 0; 1788 } 1789 llvm_unreachable("Unsupported attribute type"); 1790 } 1791 1792 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { 1793 if (!Val) return; 1794 1795 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; 1796 I = Attribute::AttrKind(I + 1)) { 1797 if (uint64_t A = (Val & getRawAttributeMask(I))) { 1798 if (I == Attribute::Alignment) 1799 B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); 1800 else if (I == Attribute::StackAlignment) 1801 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); 1802 else if (Attribute::isTypeAttrKind(I)) 1803 B.addTypeAttr(I, nullptr); // Type will be auto-upgraded. 1804 else 1805 B.addAttribute(I); 1806 } 1807 } 1808 } 1809 1810 /// This fills an AttrBuilder object with the LLVM attributes that have 1811 /// been decoded from the given integer. This function must stay in sync with 1812 /// 'encodeLLVMAttributesForBitcode'. 1813 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1814 uint64_t EncodedAttrs, 1815 uint64_t AttrIdx) { 1816 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1817 // the bits above 31 down by 11 bits. 1818 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1819 assert((!Alignment || isPowerOf2_32(Alignment)) && 1820 "Alignment must be a power of two."); 1821 1822 if (Alignment) 1823 B.addAlignmentAttr(Alignment); 1824 1825 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1826 (EncodedAttrs & 0xffff); 1827 1828 if (AttrIdx == AttributeList::FunctionIndex) { 1829 // Upgrade old memory attributes. 1830 MemoryEffects ME = MemoryEffects::unknown(); 1831 if (Attrs & (1ULL << 9)) { 1832 // ReadNone 1833 Attrs &= ~(1ULL << 9); 1834 ME &= MemoryEffects::none(); 1835 } 1836 if (Attrs & (1ULL << 10)) { 1837 // ReadOnly 1838 Attrs &= ~(1ULL << 10); 1839 ME &= MemoryEffects::readOnly(); 1840 } 1841 if (Attrs & (1ULL << 49)) { 1842 // InaccessibleMemOnly 1843 Attrs &= ~(1ULL << 49); 1844 ME &= MemoryEffects::inaccessibleMemOnly(); 1845 } 1846 if (Attrs & (1ULL << 50)) { 1847 // InaccessibleMemOrArgMemOnly 1848 Attrs &= ~(1ULL << 50); 1849 ME &= MemoryEffects::inaccessibleOrArgMemOnly(); 1850 } 1851 if (Attrs & (1ULL << 53)) { 1852 // WriteOnly 1853 Attrs &= ~(1ULL << 53); 1854 ME &= MemoryEffects::writeOnly(); 1855 } 1856 if (ME != MemoryEffects::unknown()) 1857 B.addMemoryAttr(ME); 1858 } 1859 1860 addRawAttributeValue(B, Attrs); 1861 } 1862 1863 Error BitcodeReader::parseAttributeBlock() { 1864 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 1865 return Err; 1866 1867 if (!MAttributes.empty()) 1868 return error("Invalid multiple blocks"); 1869 1870 SmallVector<uint64_t, 64> Record; 1871 1872 SmallVector<AttributeList, 8> Attrs; 1873 1874 // Read all the records. 1875 while (true) { 1876 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 1877 if (!MaybeEntry) 1878 return MaybeEntry.takeError(); 1879 BitstreamEntry Entry = MaybeEntry.get(); 1880 1881 switch (Entry.Kind) { 1882 case BitstreamEntry::SubBlock: // Handled for us already. 1883 case BitstreamEntry::Error: 1884 return error("Malformed block"); 1885 case BitstreamEntry::EndBlock: 1886 return Error::success(); 1887 case BitstreamEntry::Record: 1888 // The interesting case. 1889 break; 1890 } 1891 1892 // Read a record. 1893 Record.clear(); 1894 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 1895 if (!MaybeRecord) 1896 return MaybeRecord.takeError(); 1897 switch (MaybeRecord.get()) { 1898 default: // Default behavior: ignore. 1899 break; 1900 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] 1901 // Deprecated, but still needed to read old bitcode files. 1902 if (Record.size() & 1) 1903 return error("Invalid parameter attribute record"); 1904 1905 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1906 AttrBuilder B(Context); 1907 decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]); 1908 Attrs.push_back(AttributeList::get(Context, Record[i], B)); 1909 } 1910 1911 MAttributes.push_back(AttributeList::get(Context, Attrs)); 1912 Attrs.clear(); 1913 break; 1914 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...] 1915 for (unsigned i = 0, e = Record.size(); i != e; ++i) 1916 Attrs.push_back(MAttributeGroups[Record[i]]); 1917 1918 MAttributes.push_back(AttributeList::get(Context, Attrs)); 1919 Attrs.clear(); 1920 break; 1921 } 1922 } 1923 } 1924 1925 // Returns Attribute::None on unrecognized codes. 1926 static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1927 switch (Code) { 1928 default: 1929 return Attribute::None; 1930 case bitc::ATTR_KIND_ALIGNMENT: 1931 return Attribute::Alignment; 1932 case bitc::ATTR_KIND_ALWAYS_INLINE: 1933 return Attribute::AlwaysInline; 1934 case bitc::ATTR_KIND_BUILTIN: 1935 return Attribute::Builtin; 1936 case bitc::ATTR_KIND_BY_VAL: 1937 return Attribute::ByVal; 1938 case bitc::ATTR_KIND_IN_ALLOCA: 1939 return Attribute::InAlloca; 1940 case bitc::ATTR_KIND_COLD: 1941 return Attribute::Cold; 1942 case bitc::ATTR_KIND_CONVERGENT: 1943 return Attribute::Convergent; 1944 case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION: 1945 return Attribute::DisableSanitizerInstrumentation; 1946 case bitc::ATTR_KIND_ELEMENTTYPE: 1947 return Attribute::ElementType; 1948 case bitc::ATTR_KIND_FNRETTHUNK_EXTERN: 1949 return Attribute::FnRetThunkExtern; 1950 case bitc::ATTR_KIND_INLINE_HINT: 1951 return Attribute::InlineHint; 1952 case bitc::ATTR_KIND_IN_REG: 1953 return Attribute::InReg; 1954 case bitc::ATTR_KIND_JUMP_TABLE: 1955 return Attribute::JumpTable; 1956 case bitc::ATTR_KIND_MEMORY: 1957 return Attribute::Memory; 1958 case bitc::ATTR_KIND_NOFPCLASS: 1959 return Attribute::NoFPClass; 1960 case bitc::ATTR_KIND_MIN_SIZE: 1961 return Attribute::MinSize; 1962 case bitc::ATTR_KIND_NAKED: 1963 return Attribute::Naked; 1964 case bitc::ATTR_KIND_NEST: 1965 return Attribute::Nest; 1966 case bitc::ATTR_KIND_NO_ALIAS: 1967 return Attribute::NoAlias; 1968 case bitc::ATTR_KIND_NO_BUILTIN: 1969 return Attribute::NoBuiltin; 1970 case bitc::ATTR_KIND_NO_CALLBACK: 1971 return Attribute::NoCallback; 1972 case bitc::ATTR_KIND_NO_CAPTURE: 1973 return Attribute::NoCapture; 1974 case bitc::ATTR_KIND_NO_DUPLICATE: 1975 return Attribute::NoDuplicate; 1976 case bitc::ATTR_KIND_NOFREE: 1977 return Attribute::NoFree; 1978 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1979 return Attribute::NoImplicitFloat; 1980 case bitc::ATTR_KIND_NO_INLINE: 1981 return Attribute::NoInline; 1982 case bitc::ATTR_KIND_NO_RECURSE: 1983 return Attribute::NoRecurse; 1984 case bitc::ATTR_KIND_NO_MERGE: 1985 return Attribute::NoMerge; 1986 case bitc::ATTR_KIND_NON_LAZY_BIND: 1987 return Attribute::NonLazyBind; 1988 case bitc::ATTR_KIND_NON_NULL: 1989 return Attribute::NonNull; 1990 case bitc::ATTR_KIND_DEREFERENCEABLE: 1991 return Attribute::Dereferenceable; 1992 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1993 return Attribute::DereferenceableOrNull; 1994 case bitc::ATTR_KIND_ALLOC_ALIGN: 1995 return Attribute::AllocAlign; 1996 case bitc::ATTR_KIND_ALLOC_KIND: 1997 return Attribute::AllocKind; 1998 case bitc::ATTR_KIND_ALLOC_SIZE: 1999 return Attribute::AllocSize; 2000 case bitc::ATTR_KIND_ALLOCATED_POINTER: 2001 return Attribute::AllocatedPointer; 2002 case bitc::ATTR_KIND_NO_RED_ZONE: 2003 return Attribute::NoRedZone; 2004 case bitc::ATTR_KIND_NO_RETURN: 2005 return Attribute::NoReturn; 2006 case bitc::ATTR_KIND_NOSYNC: 2007 return Attribute::NoSync; 2008 case bitc::ATTR_KIND_NOCF_CHECK: 2009 return Attribute::NoCfCheck; 2010 case bitc::ATTR_KIND_NO_PROFILE: 2011 return Attribute::NoProfile; 2012 case bitc::ATTR_KIND_SKIP_PROFILE: 2013 return Attribute::SkipProfile; 2014 case bitc::ATTR_KIND_NO_UNWIND: 2015 return Attribute::NoUnwind; 2016 case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS: 2017 return Attribute::NoSanitizeBounds; 2018 case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE: 2019 return Attribute::NoSanitizeCoverage; 2020 case bitc::ATTR_KIND_NULL_POINTER_IS_VALID: 2021 return Attribute::NullPointerIsValid; 2022 case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING: 2023 return Attribute::OptimizeForDebugging; 2024 case bitc::ATTR_KIND_OPT_FOR_FUZZING: 2025 return Attribute::OptForFuzzing; 2026 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 2027 return Attribute::OptimizeForSize; 2028 case bitc::ATTR_KIND_OPTIMIZE_NONE: 2029 return Attribute::OptimizeNone; 2030 case bitc::ATTR_KIND_READ_NONE: 2031 return Attribute::ReadNone; 2032 case bitc::ATTR_KIND_READ_ONLY: 2033 return Attribute::ReadOnly; 2034 case bitc::ATTR_KIND_RETURNED: 2035 return Attribute::Returned; 2036 case bitc::ATTR_KIND_RETURNS_TWICE: 2037 return Attribute::ReturnsTwice; 2038 case bitc::ATTR_KIND_S_EXT: 2039 return Attribute::SExt; 2040 case bitc::ATTR_KIND_SPECULATABLE: 2041 return Attribute::Speculatable; 2042 case bitc::ATTR_KIND_STACK_ALIGNMENT: 2043 return Attribute::StackAlignment; 2044 case bitc::ATTR_KIND_STACK_PROTECT: 2045 return Attribute::StackProtect; 2046 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 2047 return Attribute::StackProtectReq; 2048 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 2049 return Attribute::StackProtectStrong; 2050 case bitc::ATTR_KIND_SAFESTACK: 2051 return Attribute::SafeStack; 2052 case bitc::ATTR_KIND_SHADOWCALLSTACK: 2053 return Attribute::ShadowCallStack; 2054 case bitc::ATTR_KIND_STRICT_FP: 2055 return Attribute::StrictFP; 2056 case bitc::ATTR_KIND_STRUCT_RET: 2057 return Attribute::StructRet; 2058 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 2059 return Attribute::SanitizeAddress; 2060 case bitc::ATTR_KIND_SANITIZE_HWADDRESS: 2061 return Attribute::SanitizeHWAddress; 2062 case bitc::ATTR_KIND_SANITIZE_THREAD: 2063 return Attribute::SanitizeThread; 2064 case bitc::ATTR_KIND_SANITIZE_MEMORY: 2065 return Attribute::SanitizeMemory; 2066 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING: 2067 return Attribute::SpeculativeLoadHardening; 2068 case bitc::ATTR_KIND_SWIFT_ERROR: 2069 return Attribute::SwiftError; 2070 case bitc::ATTR_KIND_SWIFT_SELF: 2071 return Attribute::SwiftSelf; 2072 case bitc::ATTR_KIND_SWIFT_ASYNC: 2073 return Attribute::SwiftAsync; 2074 case bitc::ATTR_KIND_UW_TABLE: 2075 return Attribute::UWTable; 2076 case bitc::ATTR_KIND_VSCALE_RANGE: 2077 return Attribute::VScaleRange; 2078 case bitc::ATTR_KIND_WILLRETURN: 2079 return Attribute::WillReturn; 2080 case bitc::ATTR_KIND_WRITEONLY: 2081 return Attribute::WriteOnly; 2082 case bitc::ATTR_KIND_Z_EXT: 2083 return Attribute::ZExt; 2084 case bitc::ATTR_KIND_IMMARG: 2085 return Attribute::ImmArg; 2086 case bitc::ATTR_KIND_SANITIZE_MEMTAG: 2087 return Attribute::SanitizeMemTag; 2088 case bitc::ATTR_KIND_PREALLOCATED: 2089 return Attribute::Preallocated; 2090 case bitc::ATTR_KIND_NOUNDEF: 2091 return Attribute::NoUndef; 2092 case bitc::ATTR_KIND_BYREF: 2093 return Attribute::ByRef; 2094 case bitc::ATTR_KIND_MUSTPROGRESS: 2095 return Attribute::MustProgress; 2096 case bitc::ATTR_KIND_HOT: 2097 return Attribute::Hot; 2098 case bitc::ATTR_KIND_PRESPLIT_COROUTINE: 2099 return Attribute::PresplitCoroutine; 2100 case bitc::ATTR_KIND_WRITABLE: 2101 return Attribute::Writable; 2102 case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE: 2103 return Attribute::CoroDestroyOnlyWhenComplete; 2104 case bitc::ATTR_KIND_DEAD_ON_UNWIND: 2105 return Attribute::DeadOnUnwind; 2106 } 2107 } 2108 2109 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent, 2110 MaybeAlign &Alignment) { 2111 // Note: Alignment in bitcode files is incremented by 1, so that zero 2112 // can be used for default alignment. 2113 if (Exponent > Value::MaxAlignmentExponent + 1) 2114 return error("Invalid alignment value"); 2115 Alignment = decodeMaybeAlign(Exponent); 2116 return Error::success(); 2117 } 2118 2119 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) { 2120 *Kind = getAttrFromCode(Code); 2121 if (*Kind == Attribute::None) 2122 return error("Unknown attribute kind (" + Twine(Code) + ")"); 2123 return Error::success(); 2124 } 2125 2126 static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) { 2127 switch (EncodedKind) { 2128 case bitc::ATTR_KIND_READ_NONE: 2129 ME &= MemoryEffects::none(); 2130 return true; 2131 case bitc::ATTR_KIND_READ_ONLY: 2132 ME &= MemoryEffects::readOnly(); 2133 return true; 2134 case bitc::ATTR_KIND_WRITEONLY: 2135 ME &= MemoryEffects::writeOnly(); 2136 return true; 2137 case bitc::ATTR_KIND_ARGMEMONLY: 2138 ME &= MemoryEffects::argMemOnly(); 2139 return true; 2140 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 2141 ME &= MemoryEffects::inaccessibleMemOnly(); 2142 return true; 2143 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 2144 ME &= MemoryEffects::inaccessibleOrArgMemOnly(); 2145 return true; 2146 default: 2147 return false; 2148 } 2149 } 2150 2151 Error BitcodeReader::parseAttributeGroupBlock() { 2152 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 2153 return Err; 2154 2155 if (!MAttributeGroups.empty()) 2156 return error("Invalid multiple blocks"); 2157 2158 SmallVector<uint64_t, 64> Record; 2159 2160 // Read all the records. 2161 while (true) { 2162 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2163 if (!MaybeEntry) 2164 return MaybeEntry.takeError(); 2165 BitstreamEntry Entry = MaybeEntry.get(); 2166 2167 switch (Entry.Kind) { 2168 case BitstreamEntry::SubBlock: // Handled for us already. 2169 case BitstreamEntry::Error: 2170 return error("Malformed block"); 2171 case BitstreamEntry::EndBlock: 2172 return Error::success(); 2173 case BitstreamEntry::Record: 2174 // The interesting case. 2175 break; 2176 } 2177 2178 // Read a record. 2179 Record.clear(); 2180 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2181 if (!MaybeRecord) 2182 return MaybeRecord.takeError(); 2183 switch (MaybeRecord.get()) { 2184 default: // Default behavior: ignore. 2185 break; 2186 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 2187 if (Record.size() < 3) 2188 return error("Invalid grp record"); 2189 2190 uint64_t GrpID = Record[0]; 2191 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 2192 2193 AttrBuilder B(Context); 2194 MemoryEffects ME = MemoryEffects::unknown(); 2195 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 2196 if (Record[i] == 0) { // Enum attribute 2197 Attribute::AttrKind Kind; 2198 uint64_t EncodedKind = Record[++i]; 2199 if (Idx == AttributeList::FunctionIndex && 2200 upgradeOldMemoryAttribute(ME, EncodedKind)) 2201 continue; 2202 2203 if (Error Err = parseAttrKind(EncodedKind, &Kind)) 2204 return Err; 2205 2206 // Upgrade old-style byval attribute to one with a type, even if it's 2207 // nullptr. We will have to insert the real type when we associate 2208 // this AttributeList with a function. 2209 if (Kind == Attribute::ByVal) 2210 B.addByValAttr(nullptr); 2211 else if (Kind == Attribute::StructRet) 2212 B.addStructRetAttr(nullptr); 2213 else if (Kind == Attribute::InAlloca) 2214 B.addInAllocaAttr(nullptr); 2215 else if (Kind == Attribute::UWTable) 2216 B.addUWTableAttr(UWTableKind::Default); 2217 else if (Attribute::isEnumAttrKind(Kind)) 2218 B.addAttribute(Kind); 2219 else 2220 return error("Not an enum attribute"); 2221 } else if (Record[i] == 1) { // Integer attribute 2222 Attribute::AttrKind Kind; 2223 if (Error Err = parseAttrKind(Record[++i], &Kind)) 2224 return Err; 2225 if (!Attribute::isIntAttrKind(Kind)) 2226 return error("Not an int attribute"); 2227 if (Kind == Attribute::Alignment) 2228 B.addAlignmentAttr(Record[++i]); 2229 else if (Kind == Attribute::StackAlignment) 2230 B.addStackAlignmentAttr(Record[++i]); 2231 else if (Kind == Attribute::Dereferenceable) 2232 B.addDereferenceableAttr(Record[++i]); 2233 else if (Kind == Attribute::DereferenceableOrNull) 2234 B.addDereferenceableOrNullAttr(Record[++i]); 2235 else if (Kind == Attribute::AllocSize) 2236 B.addAllocSizeAttrFromRawRepr(Record[++i]); 2237 else if (Kind == Attribute::VScaleRange) 2238 B.addVScaleRangeAttrFromRawRepr(Record[++i]); 2239 else if (Kind == Attribute::UWTable) 2240 B.addUWTableAttr(UWTableKind(Record[++i])); 2241 else if (Kind == Attribute::AllocKind) 2242 B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i])); 2243 else if (Kind == Attribute::Memory) 2244 B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i])); 2245 else if (Kind == Attribute::NoFPClass) 2246 B.addNoFPClassAttr( 2247 static_cast<FPClassTest>(Record[++i] & fcAllFlags)); 2248 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute 2249 bool HasValue = (Record[i++] == 4); 2250 SmallString<64> KindStr; 2251 SmallString<64> ValStr; 2252 2253 while (Record[i] != 0 && i != e) 2254 KindStr += Record[i++]; 2255 assert(Record[i] == 0 && "Kind string not null terminated"); 2256 2257 if (HasValue) { 2258 // Has a value associated with it. 2259 ++i; // Skip the '0' that terminates the "kind" string. 2260 while (Record[i] != 0 && i != e) 2261 ValStr += Record[i++]; 2262 assert(Record[i] == 0 && "Value string not null terminated"); 2263 } 2264 2265 B.addAttribute(KindStr.str(), ValStr.str()); 2266 } else if (Record[i] == 5 || Record[i] == 6) { 2267 bool HasType = Record[i] == 6; 2268 Attribute::AttrKind Kind; 2269 if (Error Err = parseAttrKind(Record[++i], &Kind)) 2270 return Err; 2271 if (!Attribute::isTypeAttrKind(Kind)) 2272 return error("Not a type attribute"); 2273 2274 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr); 2275 } else { 2276 return error("Invalid attribute group entry"); 2277 } 2278 } 2279 2280 if (ME != MemoryEffects::unknown()) 2281 B.addMemoryAttr(ME); 2282 2283 UpgradeAttributes(B); 2284 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B); 2285 break; 2286 } 2287 } 2288 } 2289 } 2290 2291 Error BitcodeReader::parseTypeTable() { 2292 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 2293 return Err; 2294 2295 return parseTypeTableBody(); 2296 } 2297 2298 Error BitcodeReader::parseTypeTableBody() { 2299 if (!TypeList.empty()) 2300 return error("Invalid multiple blocks"); 2301 2302 SmallVector<uint64_t, 64> Record; 2303 unsigned NumRecords = 0; 2304 2305 SmallString<64> TypeName; 2306 2307 // Read all the records for this type table. 2308 while (true) { 2309 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2310 if (!MaybeEntry) 2311 return MaybeEntry.takeError(); 2312 BitstreamEntry Entry = MaybeEntry.get(); 2313 2314 switch (Entry.Kind) { 2315 case BitstreamEntry::SubBlock: // Handled for us already. 2316 case BitstreamEntry::Error: 2317 return error("Malformed block"); 2318 case BitstreamEntry::EndBlock: 2319 if (NumRecords != TypeList.size()) 2320 return error("Malformed block"); 2321 return Error::success(); 2322 case BitstreamEntry::Record: 2323 // The interesting case. 2324 break; 2325 } 2326 2327 // Read a record. 2328 Record.clear(); 2329 Type *ResultTy = nullptr; 2330 SmallVector<unsigned> ContainedIDs; 2331 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2332 if (!MaybeRecord) 2333 return MaybeRecord.takeError(); 2334 switch (MaybeRecord.get()) { 2335 default: 2336 return error("Invalid value"); 2337 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 2338 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 2339 // type list. This allows us to reserve space. 2340 if (Record.empty()) 2341 return error("Invalid numentry record"); 2342 TypeList.resize(Record[0]); 2343 continue; 2344 case bitc::TYPE_CODE_VOID: // VOID 2345 ResultTy = Type::getVoidTy(Context); 2346 break; 2347 case bitc::TYPE_CODE_HALF: // HALF 2348 ResultTy = Type::getHalfTy(Context); 2349 break; 2350 case bitc::TYPE_CODE_BFLOAT: // BFLOAT 2351 ResultTy = Type::getBFloatTy(Context); 2352 break; 2353 case bitc::TYPE_CODE_FLOAT: // FLOAT 2354 ResultTy = Type::getFloatTy(Context); 2355 break; 2356 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 2357 ResultTy = Type::getDoubleTy(Context); 2358 break; 2359 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 2360 ResultTy = Type::getX86_FP80Ty(Context); 2361 break; 2362 case bitc::TYPE_CODE_FP128: // FP128 2363 ResultTy = Type::getFP128Ty(Context); 2364 break; 2365 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 2366 ResultTy = Type::getPPC_FP128Ty(Context); 2367 break; 2368 case bitc::TYPE_CODE_LABEL: // LABEL 2369 ResultTy = Type::getLabelTy(Context); 2370 break; 2371 case bitc::TYPE_CODE_METADATA: // METADATA 2372 ResultTy = Type::getMetadataTy(Context); 2373 break; 2374 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 2375 ResultTy = Type::getX86_MMXTy(Context); 2376 break; 2377 case bitc::TYPE_CODE_X86_AMX: // X86_AMX 2378 ResultTy = Type::getX86_AMXTy(Context); 2379 break; 2380 case bitc::TYPE_CODE_TOKEN: // TOKEN 2381 ResultTy = Type::getTokenTy(Context); 2382 break; 2383 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 2384 if (Record.empty()) 2385 return error("Invalid integer record"); 2386 2387 uint64_t NumBits = Record[0]; 2388 if (NumBits < IntegerType::MIN_INT_BITS || 2389 NumBits > IntegerType::MAX_INT_BITS) 2390 return error("Bitwidth for integer type out of range"); 2391 ResultTy = IntegerType::get(Context, NumBits); 2392 break; 2393 } 2394 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 2395 // [pointee type, address space] 2396 if (Record.empty()) 2397 return error("Invalid pointer record"); 2398 unsigned AddressSpace = 0; 2399 if (Record.size() == 2) 2400 AddressSpace = Record[1]; 2401 ResultTy = getTypeByID(Record[0]); 2402 if (!ResultTy || 2403 !PointerType::isValidElementType(ResultTy)) 2404 return error("Invalid type"); 2405 ContainedIDs.push_back(Record[0]); 2406 ResultTy = PointerType::get(ResultTy, AddressSpace); 2407 break; 2408 } 2409 case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace] 2410 if (Record.size() != 1) 2411 return error("Invalid opaque pointer record"); 2412 unsigned AddressSpace = Record[0]; 2413 ResultTy = PointerType::get(Context, AddressSpace); 2414 break; 2415 } 2416 case bitc::TYPE_CODE_FUNCTION_OLD: { 2417 // Deprecated, but still needed to read old bitcode files. 2418 // FUNCTION: [vararg, attrid, retty, paramty x N] 2419 if (Record.size() < 3) 2420 return error("Invalid function record"); 2421 SmallVector<Type*, 8> ArgTys; 2422 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 2423 if (Type *T = getTypeByID(Record[i])) 2424 ArgTys.push_back(T); 2425 else 2426 break; 2427 } 2428 2429 ResultTy = getTypeByID(Record[2]); 2430 if (!ResultTy || ArgTys.size() < Record.size()-3) 2431 return error("Invalid type"); 2432 2433 ContainedIDs.append(Record.begin() + 2, Record.end()); 2434 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 2435 break; 2436 } 2437 case bitc::TYPE_CODE_FUNCTION: { 2438 // FUNCTION: [vararg, retty, paramty x N] 2439 if (Record.size() < 2) 2440 return error("Invalid function record"); 2441 SmallVector<Type*, 8> ArgTys; 2442 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 2443 if (Type *T = getTypeByID(Record[i])) { 2444 if (!FunctionType::isValidArgumentType(T)) 2445 return error("Invalid function argument type"); 2446 ArgTys.push_back(T); 2447 } 2448 else 2449 break; 2450 } 2451 2452 ResultTy = getTypeByID(Record[1]); 2453 if (!ResultTy || ArgTys.size() < Record.size()-2) 2454 return error("Invalid type"); 2455 2456 ContainedIDs.append(Record.begin() + 1, Record.end()); 2457 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 2458 break; 2459 } 2460 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 2461 if (Record.empty()) 2462 return error("Invalid anon struct record"); 2463 SmallVector<Type*, 8> EltTys; 2464 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 2465 if (Type *T = getTypeByID(Record[i])) 2466 EltTys.push_back(T); 2467 else 2468 break; 2469 } 2470 if (EltTys.size() != Record.size()-1) 2471 return error("Invalid type"); 2472 ContainedIDs.append(Record.begin() + 1, Record.end()); 2473 ResultTy = StructType::get(Context, EltTys, Record[0]); 2474 break; 2475 } 2476 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 2477 if (convertToString(Record, 0, TypeName)) 2478 return error("Invalid struct name record"); 2479 continue; 2480 2481 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 2482 if (Record.empty()) 2483 return error("Invalid named struct record"); 2484 2485 if (NumRecords >= TypeList.size()) 2486 return error("Invalid TYPE table"); 2487 2488 // Check to see if this was forward referenced, if so fill in the temp. 2489 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 2490 if (Res) { 2491 Res->setName(TypeName); 2492 TypeList[NumRecords] = nullptr; 2493 } else // Otherwise, create a new struct. 2494 Res = createIdentifiedStructType(Context, TypeName); 2495 TypeName.clear(); 2496 2497 SmallVector<Type*, 8> EltTys; 2498 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 2499 if (Type *T = getTypeByID(Record[i])) 2500 EltTys.push_back(T); 2501 else 2502 break; 2503 } 2504 if (EltTys.size() != Record.size()-1) 2505 return error("Invalid named struct record"); 2506 Res->setBody(EltTys, Record[0]); 2507 ContainedIDs.append(Record.begin() + 1, Record.end()); 2508 ResultTy = Res; 2509 break; 2510 } 2511 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 2512 if (Record.size() != 1) 2513 return error("Invalid opaque type record"); 2514 2515 if (NumRecords >= TypeList.size()) 2516 return error("Invalid TYPE table"); 2517 2518 // Check to see if this was forward referenced, if so fill in the temp. 2519 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 2520 if (Res) { 2521 Res->setName(TypeName); 2522 TypeList[NumRecords] = nullptr; 2523 } else // Otherwise, create a new struct with no body. 2524 Res = createIdentifiedStructType(Context, TypeName); 2525 TypeName.clear(); 2526 ResultTy = Res; 2527 break; 2528 } 2529 case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...] 2530 if (Record.size() < 1) 2531 return error("Invalid target extension type record"); 2532 2533 if (NumRecords >= TypeList.size()) 2534 return error("Invalid TYPE table"); 2535 2536 if (Record[0] >= Record.size()) 2537 return error("Too many type parameters"); 2538 2539 unsigned NumTys = Record[0]; 2540 SmallVector<Type *, 4> TypeParams; 2541 SmallVector<unsigned, 8> IntParams; 2542 for (unsigned i = 0; i < NumTys; i++) { 2543 if (Type *T = getTypeByID(Record[i + 1])) 2544 TypeParams.push_back(T); 2545 else 2546 return error("Invalid type"); 2547 } 2548 2549 for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) { 2550 if (Record[i] > UINT_MAX) 2551 return error("Integer parameter too large"); 2552 IntParams.push_back(Record[i]); 2553 } 2554 ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams); 2555 TypeName.clear(); 2556 break; 2557 } 2558 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 2559 if (Record.size() < 2) 2560 return error("Invalid array type record"); 2561 ResultTy = getTypeByID(Record[1]); 2562 if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 2563 return error("Invalid type"); 2564 ContainedIDs.push_back(Record[1]); 2565 ResultTy = ArrayType::get(ResultTy, Record[0]); 2566 break; 2567 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or 2568 // [numelts, eltty, scalable] 2569 if (Record.size() < 2) 2570 return error("Invalid vector type record"); 2571 if (Record[0] == 0) 2572 return error("Invalid vector length"); 2573 ResultTy = getTypeByID(Record[1]); 2574 if (!ResultTy || !VectorType::isValidElementType(ResultTy)) 2575 return error("Invalid type"); 2576 bool Scalable = Record.size() > 2 ? Record[2] : false; 2577 ContainedIDs.push_back(Record[1]); 2578 ResultTy = VectorType::get(ResultTy, Record[0], Scalable); 2579 break; 2580 } 2581 2582 if (NumRecords >= TypeList.size()) 2583 return error("Invalid TYPE table"); 2584 if (TypeList[NumRecords]) 2585 return error( 2586 "Invalid TYPE table: Only named structs can be forward referenced"); 2587 assert(ResultTy && "Didn't read a type?"); 2588 TypeList[NumRecords] = ResultTy; 2589 if (!ContainedIDs.empty()) 2590 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs); 2591 ++NumRecords; 2592 } 2593 } 2594 2595 Error BitcodeReader::parseOperandBundleTags() { 2596 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 2597 return Err; 2598 2599 if (!BundleTags.empty()) 2600 return error("Invalid multiple blocks"); 2601 2602 SmallVector<uint64_t, 64> Record; 2603 2604 while (true) { 2605 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2606 if (!MaybeEntry) 2607 return MaybeEntry.takeError(); 2608 BitstreamEntry Entry = MaybeEntry.get(); 2609 2610 switch (Entry.Kind) { 2611 case BitstreamEntry::SubBlock: // Handled for us already. 2612 case BitstreamEntry::Error: 2613 return error("Malformed block"); 2614 case BitstreamEntry::EndBlock: 2615 return Error::success(); 2616 case BitstreamEntry::Record: 2617 // The interesting case. 2618 break; 2619 } 2620 2621 // Tags are implicitly mapped to integers by their order. 2622 2623 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2624 if (!MaybeRecord) 2625 return MaybeRecord.takeError(); 2626 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG) 2627 return error("Invalid operand bundle record"); 2628 2629 // OPERAND_BUNDLE_TAG: [strchr x N] 2630 BundleTags.emplace_back(); 2631 if (convertToString(Record, 0, BundleTags.back())) 2632 return error("Invalid operand bundle record"); 2633 Record.clear(); 2634 } 2635 } 2636 2637 Error BitcodeReader::parseSyncScopeNames() { 2638 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID)) 2639 return Err; 2640 2641 if (!SSIDs.empty()) 2642 return error("Invalid multiple synchronization scope names blocks"); 2643 2644 SmallVector<uint64_t, 64> Record; 2645 while (true) { 2646 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2647 if (!MaybeEntry) 2648 return MaybeEntry.takeError(); 2649 BitstreamEntry Entry = MaybeEntry.get(); 2650 2651 switch (Entry.Kind) { 2652 case BitstreamEntry::SubBlock: // Handled for us already. 2653 case BitstreamEntry::Error: 2654 return error("Malformed block"); 2655 case BitstreamEntry::EndBlock: 2656 if (SSIDs.empty()) 2657 return error("Invalid empty synchronization scope names block"); 2658 return Error::success(); 2659 case BitstreamEntry::Record: 2660 // The interesting case. 2661 break; 2662 } 2663 2664 // Synchronization scope names are implicitly mapped to synchronization 2665 // scope IDs by their order. 2666 2667 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2668 if (!MaybeRecord) 2669 return MaybeRecord.takeError(); 2670 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME) 2671 return error("Invalid sync scope record"); 2672 2673 SmallString<16> SSN; 2674 if (convertToString(Record, 0, SSN)) 2675 return error("Invalid sync scope record"); 2676 2677 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN)); 2678 Record.clear(); 2679 } 2680 } 2681 2682 /// Associate a value with its name from the given index in the provided record. 2683 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 2684 unsigned NameIndex, Triple &TT) { 2685 SmallString<128> ValueName; 2686 if (convertToString(Record, NameIndex, ValueName)) 2687 return error("Invalid record"); 2688 unsigned ValueID = Record[0]; 2689 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 2690 return error("Invalid record"); 2691 Value *V = ValueList[ValueID]; 2692 2693 StringRef NameStr(ValueName.data(), ValueName.size()); 2694 if (NameStr.contains(0)) 2695 return error("Invalid value name"); 2696 V->setName(NameStr); 2697 auto *GO = dyn_cast<GlobalObject>(V); 2698 if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT()) 2699 GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 2700 return V; 2701 } 2702 2703 /// Helper to note and return the current location, and jump to the given 2704 /// offset. 2705 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset, 2706 BitstreamCursor &Stream) { 2707 // Save the current parsing location so we can jump back at the end 2708 // of the VST read. 2709 uint64_t CurrentBit = Stream.GetCurrentBitNo(); 2710 if (Error JumpFailed = Stream.JumpToBit(Offset * 32)) 2711 return std::move(JumpFailed); 2712 Expected<BitstreamEntry> MaybeEntry = Stream.advance(); 2713 if (!MaybeEntry) 2714 return MaybeEntry.takeError(); 2715 if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock || 2716 MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID) 2717 return error("Expected value symbol table subblock"); 2718 return CurrentBit; 2719 } 2720 2721 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, 2722 Function *F, 2723 ArrayRef<uint64_t> Record) { 2724 // Note that we subtract 1 here because the offset is relative to one word 2725 // before the start of the identification or module block, which was 2726 // historically always the start of the regular bitcode header. 2727 uint64_t FuncWordOffset = Record[1] - 1; 2728 uint64_t FuncBitOffset = FuncWordOffset * 32; 2729 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 2730 // Set the LastFunctionBlockBit to point to the last function block. 2731 // Later when parsing is resumed after function materialization, 2732 // we can simply skip that last function block. 2733 if (FuncBitOffset > LastFunctionBlockBit) 2734 LastFunctionBlockBit = FuncBitOffset; 2735 } 2736 2737 /// Read a new-style GlobalValue symbol table. 2738 Error BitcodeReader::parseGlobalValueSymbolTable() { 2739 unsigned FuncBitcodeOffsetDelta = 2740 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 2741 2742 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 2743 return Err; 2744 2745 SmallVector<uint64_t, 64> Record; 2746 while (true) { 2747 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2748 if (!MaybeEntry) 2749 return MaybeEntry.takeError(); 2750 BitstreamEntry Entry = MaybeEntry.get(); 2751 2752 switch (Entry.Kind) { 2753 case BitstreamEntry::SubBlock: 2754 case BitstreamEntry::Error: 2755 return error("Malformed block"); 2756 case BitstreamEntry::EndBlock: 2757 return Error::success(); 2758 case BitstreamEntry::Record: 2759 break; 2760 } 2761 2762 Record.clear(); 2763 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2764 if (!MaybeRecord) 2765 return MaybeRecord.takeError(); 2766 switch (MaybeRecord.get()) { 2767 case bitc::VST_CODE_FNENTRY: { // [valueid, offset] 2768 unsigned ValueID = Record[0]; 2769 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 2770 return error("Invalid value reference in symbol table"); 2771 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, 2772 cast<Function>(ValueList[ValueID]), Record); 2773 break; 2774 } 2775 } 2776 } 2777 } 2778 2779 /// Parse the value symbol table at either the current parsing location or 2780 /// at the given bit offset if provided. 2781 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 2782 uint64_t CurrentBit; 2783 // Pass in the Offset to distinguish between calling for the module-level 2784 // VST (where we want to jump to the VST offset) and the function-level 2785 // VST (where we don't). 2786 if (Offset > 0) { 2787 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 2788 if (!MaybeCurrentBit) 2789 return MaybeCurrentBit.takeError(); 2790 CurrentBit = MaybeCurrentBit.get(); 2791 // If this module uses a string table, read this as a module-level VST. 2792 if (UseStrtab) { 2793 if (Error Err = parseGlobalValueSymbolTable()) 2794 return Err; 2795 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 2796 return JumpFailed; 2797 return Error::success(); 2798 } 2799 // Otherwise, the VST will be in a similar format to a function-level VST, 2800 // and will contain symbol names. 2801 } 2802 2803 // Compute the delta between the bitcode indices in the VST (the word offset 2804 // to the word-aligned ENTER_SUBBLOCK for the function block, and that 2805 // expected by the lazy reader. The reader's EnterSubBlock expects to have 2806 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 2807 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 2808 // just before entering the VST subblock because: 1) the EnterSubBlock 2809 // changes the AbbrevID width; 2) the VST block is nested within the same 2810 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 2811 // AbbrevID width before calling EnterSubBlock; and 3) when we want to 2812 // jump to the FUNCTION_BLOCK using this offset later, we don't want 2813 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 2814 unsigned FuncBitcodeOffsetDelta = 2815 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 2816 2817 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 2818 return Err; 2819 2820 SmallVector<uint64_t, 64> Record; 2821 2822 Triple TT(TheModule->getTargetTriple()); 2823 2824 // Read all the records for this value table. 2825 SmallString<128> ValueName; 2826 2827 while (true) { 2828 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 2829 if (!MaybeEntry) 2830 return MaybeEntry.takeError(); 2831 BitstreamEntry Entry = MaybeEntry.get(); 2832 2833 switch (Entry.Kind) { 2834 case BitstreamEntry::SubBlock: // Handled for us already. 2835 case BitstreamEntry::Error: 2836 return error("Malformed block"); 2837 case BitstreamEntry::EndBlock: 2838 if (Offset > 0) 2839 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 2840 return JumpFailed; 2841 return Error::success(); 2842 case BitstreamEntry::Record: 2843 // The interesting case. 2844 break; 2845 } 2846 2847 // Read a record. 2848 Record.clear(); 2849 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 2850 if (!MaybeRecord) 2851 return MaybeRecord.takeError(); 2852 switch (MaybeRecord.get()) { 2853 default: // Default behavior: unknown type. 2854 break; 2855 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 2856 Expected<Value *> ValOrErr = recordValue(Record, 1, TT); 2857 if (Error Err = ValOrErr.takeError()) 2858 return Err; 2859 ValOrErr.get(); 2860 break; 2861 } 2862 case bitc::VST_CODE_FNENTRY: { 2863 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 2864 Expected<Value *> ValOrErr = recordValue(Record, 2, TT); 2865 if (Error Err = ValOrErr.takeError()) 2866 return Err; 2867 Value *V = ValOrErr.get(); 2868 2869 // Ignore function offsets emitted for aliases of functions in older 2870 // versions of LLVM. 2871 if (auto *F = dyn_cast<Function>(V)) 2872 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record); 2873 break; 2874 } 2875 case bitc::VST_CODE_BBENTRY: { 2876 if (convertToString(Record, 1, ValueName)) 2877 return error("Invalid bbentry record"); 2878 BasicBlock *BB = getBasicBlock(Record[0]); 2879 if (!BB) 2880 return error("Invalid bbentry record"); 2881 2882 BB->setName(StringRef(ValueName.data(), ValueName.size())); 2883 ValueName.clear(); 2884 break; 2885 } 2886 } 2887 } 2888 } 2889 2890 /// Decode a signed value stored with the sign bit in the LSB for dense VBR 2891 /// encoding. 2892 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2893 if ((V & 1) == 0) 2894 return V >> 1; 2895 if (V != 1) 2896 return -(V >> 1); 2897 // There is no such thing as -0 with integers. "-0" really means MININT. 2898 return 1ULL << 63; 2899 } 2900 2901 /// Resolve all of the initializers for global values and aliases that we can. 2902 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() { 2903 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist; 2904 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist; 2905 std::vector<FunctionOperandInfo> FunctionOperandWorklist; 2906 2907 GlobalInitWorklist.swap(GlobalInits); 2908 IndirectSymbolInitWorklist.swap(IndirectSymbolInits); 2909 FunctionOperandWorklist.swap(FunctionOperands); 2910 2911 while (!GlobalInitWorklist.empty()) { 2912 unsigned ValID = GlobalInitWorklist.back().second; 2913 if (ValID >= ValueList.size()) { 2914 // Not ready to resolve this yet, it requires something later in the file. 2915 GlobalInits.push_back(GlobalInitWorklist.back()); 2916 } else { 2917 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2918 if (!MaybeC) 2919 return MaybeC.takeError(); 2920 GlobalInitWorklist.back().first->setInitializer(MaybeC.get()); 2921 } 2922 GlobalInitWorklist.pop_back(); 2923 } 2924 2925 while (!IndirectSymbolInitWorklist.empty()) { 2926 unsigned ValID = IndirectSymbolInitWorklist.back().second; 2927 if (ValID >= ValueList.size()) { 2928 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back()); 2929 } else { 2930 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2931 if (!MaybeC) 2932 return MaybeC.takeError(); 2933 Constant *C = MaybeC.get(); 2934 GlobalValue *GV = IndirectSymbolInitWorklist.back().first; 2935 if (auto *GA = dyn_cast<GlobalAlias>(GV)) { 2936 if (C->getType() != GV->getType()) 2937 return error("Alias and aliasee types don't match"); 2938 GA->setAliasee(C); 2939 } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) { 2940 GI->setResolver(C); 2941 } else { 2942 return error("Expected an alias or an ifunc"); 2943 } 2944 } 2945 IndirectSymbolInitWorklist.pop_back(); 2946 } 2947 2948 while (!FunctionOperandWorklist.empty()) { 2949 FunctionOperandInfo &Info = FunctionOperandWorklist.back(); 2950 if (Info.PersonalityFn) { 2951 unsigned ValID = Info.PersonalityFn - 1; 2952 if (ValID < ValueList.size()) { 2953 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2954 if (!MaybeC) 2955 return MaybeC.takeError(); 2956 Info.F->setPersonalityFn(MaybeC.get()); 2957 Info.PersonalityFn = 0; 2958 } 2959 } 2960 if (Info.Prefix) { 2961 unsigned ValID = Info.Prefix - 1; 2962 if (ValID < ValueList.size()) { 2963 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2964 if (!MaybeC) 2965 return MaybeC.takeError(); 2966 Info.F->setPrefixData(MaybeC.get()); 2967 Info.Prefix = 0; 2968 } 2969 } 2970 if (Info.Prologue) { 2971 unsigned ValID = Info.Prologue - 1; 2972 if (ValID < ValueList.size()) { 2973 Expected<Constant *> MaybeC = getValueForInitializer(ValID); 2974 if (!MaybeC) 2975 return MaybeC.takeError(); 2976 Info.F->setPrologueData(MaybeC.get()); 2977 Info.Prologue = 0; 2978 } 2979 } 2980 if (Info.PersonalityFn || Info.Prefix || Info.Prologue) 2981 FunctionOperands.push_back(Info); 2982 FunctionOperandWorklist.pop_back(); 2983 } 2984 2985 return Error::success(); 2986 } 2987 2988 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 2989 SmallVector<uint64_t, 8> Words(Vals.size()); 2990 transform(Vals, Words.begin(), 2991 BitcodeReader::decodeSignRotatedValue); 2992 2993 return APInt(TypeBits, Words); 2994 } 2995 2996 Error BitcodeReader::parseConstants() { 2997 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 2998 return Err; 2999 3000 SmallVector<uint64_t, 64> Record; 3001 3002 // Read all the records for this value table. 3003 Type *CurTy = Type::getInt32Ty(Context); 3004 unsigned Int32TyID = getVirtualTypeID(CurTy); 3005 unsigned CurTyID = Int32TyID; 3006 Type *CurElemTy = nullptr; 3007 unsigned NextCstNo = ValueList.size(); 3008 3009 while (true) { 3010 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 3011 if (!MaybeEntry) 3012 return MaybeEntry.takeError(); 3013 BitstreamEntry Entry = MaybeEntry.get(); 3014 3015 switch (Entry.Kind) { 3016 case BitstreamEntry::SubBlock: // Handled for us already. 3017 case BitstreamEntry::Error: 3018 return error("Malformed block"); 3019 case BitstreamEntry::EndBlock: 3020 if (NextCstNo != ValueList.size()) 3021 return error("Invalid constant reference"); 3022 return Error::success(); 3023 case BitstreamEntry::Record: 3024 // The interesting case. 3025 break; 3026 } 3027 3028 // Read a record. 3029 Record.clear(); 3030 Type *VoidType = Type::getVoidTy(Context); 3031 Value *V = nullptr; 3032 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 3033 if (!MaybeBitCode) 3034 return MaybeBitCode.takeError(); 3035 switch (unsigned BitCode = MaybeBitCode.get()) { 3036 default: // Default behavior: unknown constant 3037 case bitc::CST_CODE_UNDEF: // UNDEF 3038 V = UndefValue::get(CurTy); 3039 break; 3040 case bitc::CST_CODE_POISON: // POISON 3041 V = PoisonValue::get(CurTy); 3042 break; 3043 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 3044 if (Record.empty()) 3045 return error("Invalid settype record"); 3046 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 3047 return error("Invalid settype record"); 3048 if (TypeList[Record[0]] == VoidType) 3049 return error("Invalid constant type"); 3050 CurTyID = Record[0]; 3051 CurTy = TypeList[CurTyID]; 3052 CurElemTy = getPtrElementTypeByID(CurTyID); 3053 continue; // Skip the ValueList manipulation. 3054 case bitc::CST_CODE_NULL: // NULL 3055 if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy()) 3056 return error("Invalid type for a constant null value"); 3057 if (auto *TETy = dyn_cast<TargetExtType>(CurTy)) 3058 if (!TETy->hasProperty(TargetExtType::HasZeroInit)) 3059 return error("Invalid type for a constant null value"); 3060 V = Constant::getNullValue(CurTy); 3061 break; 3062 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 3063 if (!CurTy->isIntOrIntVectorTy() || Record.empty()) 3064 return error("Invalid integer const record"); 3065 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 3066 break; 3067 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 3068 if (!CurTy->isIntOrIntVectorTy() || Record.empty()) 3069 return error("Invalid wide integer const record"); 3070 3071 auto *ScalarTy = cast<IntegerType>(CurTy->getScalarType()); 3072 APInt VInt = readWideAPInt(Record, ScalarTy->getBitWidth()); 3073 V = ConstantInt::get(CurTy, VInt); 3074 break; 3075 } 3076 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 3077 if (Record.empty()) 3078 return error("Invalid float const record"); 3079 3080 auto *ScalarTy = CurTy->getScalarType(); 3081 if (ScalarTy->isHalfTy()) 3082 V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEhalf(), 3083 APInt(16, (uint16_t)Record[0]))); 3084 else if (ScalarTy->isBFloatTy()) 3085 V = ConstantFP::get( 3086 CurTy, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0]))); 3087 else if (ScalarTy->isFloatTy()) 3088 V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEsingle(), 3089 APInt(32, (uint32_t)Record[0]))); 3090 else if (ScalarTy->isDoubleTy()) 3091 V = ConstantFP::get( 3092 CurTy, APFloat(APFloat::IEEEdouble(), APInt(64, Record[0]))); 3093 else if (ScalarTy->isX86_FP80Ty()) { 3094 // Bits are not stored the same way as a normal i80 APInt, compensate. 3095 uint64_t Rearrange[2]; 3096 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 3097 Rearrange[1] = Record[0] >> 48; 3098 V = ConstantFP::get( 3099 CurTy, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange))); 3100 } else if (ScalarTy->isFP128Ty()) 3101 V = ConstantFP::get(CurTy, 3102 APFloat(APFloat::IEEEquad(), APInt(128, Record))); 3103 else if (ScalarTy->isPPC_FP128Ty()) 3104 V = ConstantFP::get( 3105 CurTy, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record))); 3106 else 3107 V = UndefValue::get(CurTy); 3108 break; 3109 } 3110 3111 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 3112 if (Record.empty()) 3113 return error("Invalid aggregate record"); 3114 3115 unsigned Size = Record.size(); 3116 SmallVector<unsigned, 16> Elts; 3117 for (unsigned i = 0; i != Size; ++i) 3118 Elts.push_back(Record[i]); 3119 3120 if (isa<StructType>(CurTy)) { 3121 V = BitcodeConstant::create( 3122 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts); 3123 } else if (isa<ArrayType>(CurTy)) { 3124 V = BitcodeConstant::create(Alloc, CurTy, 3125 BitcodeConstant::ConstantArrayOpcode, Elts); 3126 } else if (isa<VectorType>(CurTy)) { 3127 V = BitcodeConstant::create( 3128 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts); 3129 } else { 3130 V = UndefValue::get(CurTy); 3131 } 3132 break; 3133 } 3134 case bitc::CST_CODE_STRING: // STRING: [values] 3135 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 3136 if (Record.empty()) 3137 return error("Invalid string record"); 3138 3139 SmallString<16> Elts(Record.begin(), Record.end()); 3140 V = ConstantDataArray::getString(Context, Elts, 3141 BitCode == bitc::CST_CODE_CSTRING); 3142 break; 3143 } 3144 case bitc::CST_CODE_DATA: {// DATA: [n x value] 3145 if (Record.empty()) 3146 return error("Invalid data record"); 3147 3148 Type *EltTy; 3149 if (auto *Array = dyn_cast<ArrayType>(CurTy)) 3150 EltTy = Array->getElementType(); 3151 else 3152 EltTy = cast<VectorType>(CurTy)->getElementType(); 3153 if (EltTy->isIntegerTy(8)) { 3154 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 3155 if (isa<VectorType>(CurTy)) 3156 V = ConstantDataVector::get(Context, Elts); 3157 else 3158 V = ConstantDataArray::get(Context, Elts); 3159 } else if (EltTy->isIntegerTy(16)) { 3160 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3161 if (isa<VectorType>(CurTy)) 3162 V = ConstantDataVector::get(Context, Elts); 3163 else 3164 V = ConstantDataArray::get(Context, Elts); 3165 } else if (EltTy->isIntegerTy(32)) { 3166 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3167 if (isa<VectorType>(CurTy)) 3168 V = ConstantDataVector::get(Context, Elts); 3169 else 3170 V = ConstantDataArray::get(Context, Elts); 3171 } else if (EltTy->isIntegerTy(64)) { 3172 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3173 if (isa<VectorType>(CurTy)) 3174 V = ConstantDataVector::get(Context, Elts); 3175 else 3176 V = ConstantDataArray::get(Context, Elts); 3177 } else if (EltTy->isHalfTy()) { 3178 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3179 if (isa<VectorType>(CurTy)) 3180 V = ConstantDataVector::getFP(EltTy, Elts); 3181 else 3182 V = ConstantDataArray::getFP(EltTy, Elts); 3183 } else if (EltTy->isBFloatTy()) { 3184 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 3185 if (isa<VectorType>(CurTy)) 3186 V = ConstantDataVector::getFP(EltTy, Elts); 3187 else 3188 V = ConstantDataArray::getFP(EltTy, Elts); 3189 } else if (EltTy->isFloatTy()) { 3190 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 3191 if (isa<VectorType>(CurTy)) 3192 V = ConstantDataVector::getFP(EltTy, Elts); 3193 else 3194 V = ConstantDataArray::getFP(EltTy, Elts); 3195 } else if (EltTy->isDoubleTy()) { 3196 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 3197 if (isa<VectorType>(CurTy)) 3198 V = ConstantDataVector::getFP(EltTy, Elts); 3199 else 3200 V = ConstantDataArray::getFP(EltTy, Elts); 3201 } else { 3202 return error("Invalid type for value"); 3203 } 3204 break; 3205 } 3206 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] 3207 if (Record.size() < 2) 3208 return error("Invalid unary op constexpr record"); 3209 int Opc = getDecodedUnaryOpcode(Record[0], CurTy); 3210 if (Opc < 0) { 3211 V = UndefValue::get(CurTy); // Unknown unop. 3212 } else { 3213 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]); 3214 } 3215 break; 3216 } 3217 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 3218 if (Record.size() < 3) 3219 return error("Invalid binary op constexpr record"); 3220 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 3221 if (Opc < 0) { 3222 V = UndefValue::get(CurTy); // Unknown binop. 3223 } else { 3224 uint8_t Flags = 0; 3225 if (Record.size() >= 4) { 3226 if (Opc == Instruction::Add || 3227 Opc == Instruction::Sub || 3228 Opc == Instruction::Mul || 3229 Opc == Instruction::Shl) { 3230 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 3231 Flags |= OverflowingBinaryOperator::NoSignedWrap; 3232 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3233 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 3234 } else if (Opc == Instruction::SDiv || 3235 Opc == Instruction::UDiv || 3236 Opc == Instruction::LShr || 3237 Opc == Instruction::AShr) { 3238 if (Record[3] & (1 << bitc::PEO_EXACT)) 3239 Flags |= PossiblyExactOperator::IsExact; 3240 } 3241 } 3242 V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags}, 3243 {(unsigned)Record[1], (unsigned)Record[2]}); 3244 } 3245 break; 3246 } 3247 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 3248 if (Record.size() < 3) 3249 return error("Invalid cast constexpr record"); 3250 int Opc = getDecodedCastOpcode(Record[0]); 3251 if (Opc < 0) { 3252 V = UndefValue::get(CurTy); // Unknown cast. 3253 } else { 3254 unsigned OpTyID = Record[1]; 3255 Type *OpTy = getTypeByID(OpTyID); 3256 if (!OpTy) 3257 return error("Invalid cast constexpr record"); 3258 V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]); 3259 } 3260 break; 3261 } 3262 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] 3263 case bitc::CST_CODE_CE_GEP: // [ty, n x operands] 3264 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x 3265 // operands] 3266 if (Record.size() < 2) 3267 return error("Constant GEP record must have at least two elements"); 3268 unsigned OpNum = 0; 3269 Type *PointeeType = nullptr; 3270 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX || 3271 Record.size() % 2) 3272 PointeeType = getTypeByID(Record[OpNum++]); 3273 3274 bool InBounds = false; 3275 std::optional<unsigned> InRangeIndex; 3276 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) { 3277 uint64_t Op = Record[OpNum++]; 3278 InBounds = Op & 1; 3279 InRangeIndex = Op >> 1; 3280 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 3281 InBounds = true; 3282 3283 SmallVector<unsigned, 16> Elts; 3284 unsigned BaseTypeID = Record[OpNum]; 3285 while (OpNum != Record.size()) { 3286 unsigned ElTyID = Record[OpNum++]; 3287 Type *ElTy = getTypeByID(ElTyID); 3288 if (!ElTy) 3289 return error("Invalid getelementptr constexpr record"); 3290 Elts.push_back(Record[OpNum++]); 3291 } 3292 3293 if (Elts.size() < 1) 3294 return error("Invalid gep with no operands"); 3295 3296 Type *BaseType = getTypeByID(BaseTypeID); 3297 if (isa<VectorType>(BaseType)) { 3298 BaseTypeID = getContainedTypeID(BaseTypeID, 0); 3299 BaseType = getTypeByID(BaseTypeID); 3300 } 3301 3302 PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType); 3303 if (!OrigPtrTy) 3304 return error("GEP base operand must be pointer or vector of pointer"); 3305 3306 if (!PointeeType) { 3307 PointeeType = getPtrElementTypeByID(BaseTypeID); 3308 if (!PointeeType) 3309 return error("Missing element type for old-style constant GEP"); 3310 } 3311 3312 V = BitcodeConstant::create(Alloc, CurTy, 3313 {Instruction::GetElementPtr, InBounds, 3314 InRangeIndex.value_or(-1), PointeeType}, 3315 Elts); 3316 break; 3317 } 3318 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 3319 if (Record.size() < 3) 3320 return error("Invalid select constexpr record"); 3321 3322 V = BitcodeConstant::create( 3323 Alloc, CurTy, Instruction::Select, 3324 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); 3325 break; 3326 } 3327 case bitc::CST_CODE_CE_EXTRACTELT 3328 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 3329 if (Record.size() < 3) 3330 return error("Invalid extractelement constexpr record"); 3331 unsigned OpTyID = Record[0]; 3332 VectorType *OpTy = 3333 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID)); 3334 if (!OpTy) 3335 return error("Invalid extractelement constexpr record"); 3336 unsigned IdxRecord; 3337 if (Record.size() == 4) { 3338 unsigned IdxTyID = Record[2]; 3339 Type *IdxTy = getTypeByID(IdxTyID); 3340 if (!IdxTy) 3341 return error("Invalid extractelement constexpr record"); 3342 IdxRecord = Record[3]; 3343 } else { 3344 // Deprecated, but still needed to read old bitcode files. 3345 IdxRecord = Record[2]; 3346 } 3347 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement, 3348 {(unsigned)Record[1], IdxRecord}); 3349 break; 3350 } 3351 case bitc::CST_CODE_CE_INSERTELT 3352 : { // CE_INSERTELT: [opval, opval, opty, opval] 3353 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3354 if (Record.size() < 3 || !OpTy) 3355 return error("Invalid insertelement constexpr record"); 3356 unsigned IdxRecord; 3357 if (Record.size() == 4) { 3358 unsigned IdxTyID = Record[2]; 3359 Type *IdxTy = getTypeByID(IdxTyID); 3360 if (!IdxTy) 3361 return error("Invalid insertelement constexpr record"); 3362 IdxRecord = Record[3]; 3363 } else { 3364 // Deprecated, but still needed to read old bitcode files. 3365 IdxRecord = Record[2]; 3366 } 3367 V = BitcodeConstant::create( 3368 Alloc, CurTy, Instruction::InsertElement, 3369 {(unsigned)Record[0], (unsigned)Record[1], IdxRecord}); 3370 break; 3371 } 3372 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 3373 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 3374 if (Record.size() < 3 || !OpTy) 3375 return error("Invalid shufflevector constexpr record"); 3376 V = BitcodeConstant::create( 3377 Alloc, CurTy, Instruction::ShuffleVector, 3378 {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]}); 3379 break; 3380 } 3381 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 3382 VectorType *RTy = dyn_cast<VectorType>(CurTy); 3383 VectorType *OpTy = 3384 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 3385 if (Record.size() < 4 || !RTy || !OpTy) 3386 return error("Invalid shufflevector constexpr record"); 3387 V = BitcodeConstant::create( 3388 Alloc, CurTy, Instruction::ShuffleVector, 3389 {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]}); 3390 break; 3391 } 3392 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 3393 if (Record.size() < 4) 3394 return error("Invalid cmp constexpt record"); 3395 unsigned OpTyID = Record[0]; 3396 Type *OpTy = getTypeByID(OpTyID); 3397 if (!OpTy) 3398 return error("Invalid cmp constexpr record"); 3399 V = BitcodeConstant::create( 3400 Alloc, CurTy, 3401 {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp 3402 : Instruction::ICmp), 3403 (uint8_t)Record[3]}, 3404 {(unsigned)Record[1], (unsigned)Record[2]}); 3405 break; 3406 } 3407 // This maintains backward compatibility, pre-asm dialect keywords. 3408 // Deprecated, but still needed to read old bitcode files. 3409 case bitc::CST_CODE_INLINEASM_OLD: { 3410 if (Record.size() < 2) 3411 return error("Invalid inlineasm record"); 3412 std::string AsmStr, ConstrStr; 3413 bool HasSideEffects = Record[0] & 1; 3414 bool IsAlignStack = Record[0] >> 1; 3415 unsigned AsmStrSize = Record[1]; 3416 if (2+AsmStrSize >= Record.size()) 3417 return error("Invalid inlineasm record"); 3418 unsigned ConstStrSize = Record[2+AsmStrSize]; 3419 if (3+AsmStrSize+ConstStrSize > Record.size()) 3420 return error("Invalid inlineasm record"); 3421 3422 for (unsigned i = 0; i != AsmStrSize; ++i) 3423 AsmStr += (char)Record[2+i]; 3424 for (unsigned i = 0; i != ConstStrSize; ++i) 3425 ConstrStr += (char)Record[3+AsmStrSize+i]; 3426 UpgradeInlineAsmString(&AsmStr); 3427 if (!CurElemTy) 3428 return error("Missing element type for old-style inlineasm"); 3429 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 3430 HasSideEffects, IsAlignStack); 3431 break; 3432 } 3433 // This version adds support for the asm dialect keywords (e.g., 3434 // inteldialect). 3435 case bitc::CST_CODE_INLINEASM_OLD2: { 3436 if (Record.size() < 2) 3437 return error("Invalid inlineasm record"); 3438 std::string AsmStr, ConstrStr; 3439 bool HasSideEffects = Record[0] & 1; 3440 bool IsAlignStack = (Record[0] >> 1) & 1; 3441 unsigned AsmDialect = Record[0] >> 2; 3442 unsigned AsmStrSize = Record[1]; 3443 if (2+AsmStrSize >= Record.size()) 3444 return error("Invalid inlineasm record"); 3445 unsigned ConstStrSize = Record[2+AsmStrSize]; 3446 if (3+AsmStrSize+ConstStrSize > Record.size()) 3447 return error("Invalid inlineasm record"); 3448 3449 for (unsigned i = 0; i != AsmStrSize; ++i) 3450 AsmStr += (char)Record[2+i]; 3451 for (unsigned i = 0; i != ConstStrSize; ++i) 3452 ConstrStr += (char)Record[3+AsmStrSize+i]; 3453 UpgradeInlineAsmString(&AsmStr); 3454 if (!CurElemTy) 3455 return error("Missing element type for old-style inlineasm"); 3456 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 3457 HasSideEffects, IsAlignStack, 3458 InlineAsm::AsmDialect(AsmDialect)); 3459 break; 3460 } 3461 // This version adds support for the unwind keyword. 3462 case bitc::CST_CODE_INLINEASM_OLD3: { 3463 if (Record.size() < 2) 3464 return error("Invalid inlineasm record"); 3465 unsigned OpNum = 0; 3466 std::string AsmStr, ConstrStr; 3467 bool HasSideEffects = Record[OpNum] & 1; 3468 bool IsAlignStack = (Record[OpNum] >> 1) & 1; 3469 unsigned AsmDialect = (Record[OpNum] >> 2) & 1; 3470 bool CanThrow = (Record[OpNum] >> 3) & 1; 3471 ++OpNum; 3472 unsigned AsmStrSize = Record[OpNum]; 3473 ++OpNum; 3474 if (OpNum + AsmStrSize >= Record.size()) 3475 return error("Invalid inlineasm record"); 3476 unsigned ConstStrSize = Record[OpNum + AsmStrSize]; 3477 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) 3478 return error("Invalid inlineasm record"); 3479 3480 for (unsigned i = 0; i != AsmStrSize; ++i) 3481 AsmStr += (char)Record[OpNum + i]; 3482 ++OpNum; 3483 for (unsigned i = 0; i != ConstStrSize; ++i) 3484 ConstrStr += (char)Record[OpNum + AsmStrSize + i]; 3485 UpgradeInlineAsmString(&AsmStr); 3486 if (!CurElemTy) 3487 return error("Missing element type for old-style inlineasm"); 3488 V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr, 3489 HasSideEffects, IsAlignStack, 3490 InlineAsm::AsmDialect(AsmDialect), CanThrow); 3491 break; 3492 } 3493 // This version adds explicit function type. 3494 case bitc::CST_CODE_INLINEASM: { 3495 if (Record.size() < 3) 3496 return error("Invalid inlineasm record"); 3497 unsigned OpNum = 0; 3498 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum])); 3499 ++OpNum; 3500 if (!FnTy) 3501 return error("Invalid inlineasm record"); 3502 std::string AsmStr, ConstrStr; 3503 bool HasSideEffects = Record[OpNum] & 1; 3504 bool IsAlignStack = (Record[OpNum] >> 1) & 1; 3505 unsigned AsmDialect = (Record[OpNum] >> 2) & 1; 3506 bool CanThrow = (Record[OpNum] >> 3) & 1; 3507 ++OpNum; 3508 unsigned AsmStrSize = Record[OpNum]; 3509 ++OpNum; 3510 if (OpNum + AsmStrSize >= Record.size()) 3511 return error("Invalid inlineasm record"); 3512 unsigned ConstStrSize = Record[OpNum + AsmStrSize]; 3513 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size()) 3514 return error("Invalid inlineasm record"); 3515 3516 for (unsigned i = 0; i != AsmStrSize; ++i) 3517 AsmStr += (char)Record[OpNum + i]; 3518 ++OpNum; 3519 for (unsigned i = 0; i != ConstStrSize; ++i) 3520 ConstrStr += (char)Record[OpNum + AsmStrSize + i]; 3521 UpgradeInlineAsmString(&AsmStr); 3522 V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 3523 InlineAsm::AsmDialect(AsmDialect), CanThrow); 3524 break; 3525 } 3526 case bitc::CST_CODE_BLOCKADDRESS:{ 3527 if (Record.size() < 3) 3528 return error("Invalid blockaddress record"); 3529 unsigned FnTyID = Record[0]; 3530 Type *FnTy = getTypeByID(FnTyID); 3531 if (!FnTy) 3532 return error("Invalid blockaddress record"); 3533 V = BitcodeConstant::create( 3534 Alloc, CurTy, 3535 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]}, 3536 Record[1]); 3537 break; 3538 } 3539 case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: { 3540 if (Record.size() < 2) 3541 return error("Invalid dso_local record"); 3542 unsigned GVTyID = Record[0]; 3543 Type *GVTy = getTypeByID(GVTyID); 3544 if (!GVTy) 3545 return error("Invalid dso_local record"); 3546 V = BitcodeConstant::create( 3547 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]); 3548 break; 3549 } 3550 case bitc::CST_CODE_NO_CFI_VALUE: { 3551 if (Record.size() < 2) 3552 return error("Invalid no_cfi record"); 3553 unsigned GVTyID = Record[0]; 3554 Type *GVTy = getTypeByID(GVTyID); 3555 if (!GVTy) 3556 return error("Invalid no_cfi record"); 3557 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode, 3558 Record[1]); 3559 break; 3560 } 3561 } 3562 3563 assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID"); 3564 if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID)) 3565 return Err; 3566 ++NextCstNo; 3567 } 3568 } 3569 3570 Error BitcodeReader::parseUseLists() { 3571 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 3572 return Err; 3573 3574 // Read all the records. 3575 SmallVector<uint64_t, 64> Record; 3576 3577 while (true) { 3578 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 3579 if (!MaybeEntry) 3580 return MaybeEntry.takeError(); 3581 BitstreamEntry Entry = MaybeEntry.get(); 3582 3583 switch (Entry.Kind) { 3584 case BitstreamEntry::SubBlock: // Handled for us already. 3585 case BitstreamEntry::Error: 3586 return error("Malformed block"); 3587 case BitstreamEntry::EndBlock: 3588 return Error::success(); 3589 case BitstreamEntry::Record: 3590 // The interesting case. 3591 break; 3592 } 3593 3594 // Read a use list record. 3595 Record.clear(); 3596 bool IsBB = false; 3597 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 3598 if (!MaybeRecord) 3599 return MaybeRecord.takeError(); 3600 switch (MaybeRecord.get()) { 3601 default: // Default behavior: unknown type. 3602 break; 3603 case bitc::USELIST_CODE_BB: 3604 IsBB = true; 3605 [[fallthrough]]; 3606 case bitc::USELIST_CODE_DEFAULT: { 3607 unsigned RecordLength = Record.size(); 3608 if (RecordLength < 3) 3609 // Records should have at least an ID and two indexes. 3610 return error("Invalid record"); 3611 unsigned ID = Record.pop_back_val(); 3612 3613 Value *V; 3614 if (IsBB) { 3615 assert(ID < FunctionBBs.size() && "Basic block not found"); 3616 V = FunctionBBs[ID]; 3617 } else 3618 V = ValueList[ID]; 3619 unsigned NumUses = 0; 3620 SmallDenseMap<const Use *, unsigned, 16> Order; 3621 for (const Use &U : V->materialized_uses()) { 3622 if (++NumUses > Record.size()) 3623 break; 3624 Order[&U] = Record[NumUses - 1]; 3625 } 3626 if (Order.size() != Record.size() || NumUses > Record.size()) 3627 // Mismatches can happen if the functions are being materialized lazily 3628 // (out-of-order), or a value has been upgraded. 3629 break; 3630 3631 V->sortUseList([&](const Use &L, const Use &R) { 3632 return Order.lookup(&L) < Order.lookup(&R); 3633 }); 3634 break; 3635 } 3636 } 3637 } 3638 } 3639 3640 /// When we see the block for metadata, remember where it is and then skip it. 3641 /// This lets us lazily deserialize the metadata. 3642 Error BitcodeReader::rememberAndSkipMetadata() { 3643 // Save the current stream state. 3644 uint64_t CurBit = Stream.GetCurrentBitNo(); 3645 DeferredMetadataInfo.push_back(CurBit); 3646 3647 // Skip over the block for now. 3648 if (Error Err = Stream.SkipBlock()) 3649 return Err; 3650 return Error::success(); 3651 } 3652 3653 Error BitcodeReader::materializeMetadata() { 3654 for (uint64_t BitPos : DeferredMetadataInfo) { 3655 // Move the bit stream to the saved position. 3656 if (Error JumpFailed = Stream.JumpToBit(BitPos)) 3657 return JumpFailed; 3658 if (Error Err = MDLoader->parseModuleMetadata()) 3659 return Err; 3660 } 3661 3662 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level 3663 // metadata. Only upgrade if the new option doesn't exist to avoid upgrade 3664 // multiple times. 3665 if (!TheModule->getNamedMetadata("llvm.linker.options")) { 3666 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) { 3667 NamedMDNode *LinkerOpts = 3668 TheModule->getOrInsertNamedMetadata("llvm.linker.options"); 3669 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands()) 3670 LinkerOpts->addOperand(cast<MDNode>(MDOptions)); 3671 } 3672 } 3673 3674 DeferredMetadataInfo.clear(); 3675 return Error::success(); 3676 } 3677 3678 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3679 3680 /// When we see the block for a function body, remember where it is and then 3681 /// skip it. This lets us lazily deserialize the functions. 3682 Error BitcodeReader::rememberAndSkipFunctionBody() { 3683 // Get the function we are talking about. 3684 if (FunctionsWithBodies.empty()) 3685 return error("Insufficient function protos"); 3686 3687 Function *Fn = FunctionsWithBodies.back(); 3688 FunctionsWithBodies.pop_back(); 3689 3690 // Save the current stream state. 3691 uint64_t CurBit = Stream.GetCurrentBitNo(); 3692 assert( 3693 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 3694 "Mismatch between VST and scanned function offsets"); 3695 DeferredFunctionInfo[Fn] = CurBit; 3696 3697 // Skip over the function block for now. 3698 if (Error Err = Stream.SkipBlock()) 3699 return Err; 3700 return Error::success(); 3701 } 3702 3703 Error BitcodeReader::globalCleanup() { 3704 // Patch the initializers for globals and aliases up. 3705 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 3706 return Err; 3707 if (!GlobalInits.empty() || !IndirectSymbolInits.empty()) 3708 return error("Malformed global initializer set"); 3709 3710 // Look for intrinsic functions which need to be upgraded at some point 3711 // and functions that need to have their function attributes upgraded. 3712 for (Function &F : *TheModule) { 3713 MDLoader->upgradeDebugIntrinsics(F); 3714 Function *NewFn; 3715 if (UpgradeIntrinsicFunction(&F, NewFn)) 3716 UpgradedIntrinsics[&F] = NewFn; 3717 // Look for functions that rely on old function attribute behavior. 3718 UpgradeFunctionAttributes(F); 3719 } 3720 3721 // Look for global variables which need to be renamed. 3722 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables; 3723 for (GlobalVariable &GV : TheModule->globals()) 3724 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV)) 3725 UpgradedVariables.emplace_back(&GV, Upgraded); 3726 for (auto &Pair : UpgradedVariables) { 3727 Pair.first->eraseFromParent(); 3728 TheModule->insertGlobalVariable(Pair.second); 3729 } 3730 3731 // Force deallocation of memory for these vectors to favor the client that 3732 // want lazy deserialization. 3733 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits); 3734 std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits); 3735 return Error::success(); 3736 } 3737 3738 /// Support for lazy parsing of function bodies. This is required if we 3739 /// either have an old bitcode file without a VST forward declaration record, 3740 /// or if we have an anonymous function being materialized, since anonymous 3741 /// functions do not have a name and are therefore not in the VST. 3742 Error BitcodeReader::rememberAndSkipFunctionBodies() { 3743 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit)) 3744 return JumpFailed; 3745 3746 if (Stream.AtEndOfStream()) 3747 return error("Could not find function in stream"); 3748 3749 if (!SeenFirstFunctionBody) 3750 return error("Trying to materialize functions before seeing function blocks"); 3751 3752 // An old bitcode file with the symbol table at the end would have 3753 // finished the parse greedily. 3754 assert(SeenValueSymbolTable); 3755 3756 SmallVector<uint64_t, 64> Record; 3757 3758 while (true) { 3759 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 3760 if (!MaybeEntry) 3761 return MaybeEntry.takeError(); 3762 llvm::BitstreamEntry Entry = MaybeEntry.get(); 3763 3764 switch (Entry.Kind) { 3765 default: 3766 return error("Expect SubBlock"); 3767 case BitstreamEntry::SubBlock: 3768 switch (Entry.ID) { 3769 default: 3770 return error("Expect function block"); 3771 case bitc::FUNCTION_BLOCK_ID: 3772 if (Error Err = rememberAndSkipFunctionBody()) 3773 return Err; 3774 NextUnreadBit = Stream.GetCurrentBitNo(); 3775 return Error::success(); 3776 } 3777 } 3778 } 3779 } 3780 3781 Error BitcodeReaderBase::readBlockInfo() { 3782 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo = 3783 Stream.ReadBlockInfoBlock(); 3784 if (!MaybeNewBlockInfo) 3785 return MaybeNewBlockInfo.takeError(); 3786 std::optional<BitstreamBlockInfo> NewBlockInfo = 3787 std::move(MaybeNewBlockInfo.get()); 3788 if (!NewBlockInfo) 3789 return error("Malformed block"); 3790 BlockInfo = std::move(*NewBlockInfo); 3791 return Error::success(); 3792 } 3793 3794 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) { 3795 // v1: [selection_kind, name] 3796 // v2: [strtab_offset, strtab_size, selection_kind] 3797 StringRef Name; 3798 std::tie(Name, Record) = readNameFromStrtab(Record); 3799 3800 if (Record.empty()) 3801 return error("Invalid record"); 3802 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 3803 std::string OldFormatName; 3804 if (!UseStrtab) { 3805 if (Record.size() < 2) 3806 return error("Invalid record"); 3807 unsigned ComdatNameSize = Record[1]; 3808 if (ComdatNameSize > Record.size() - 2) 3809 return error("Comdat name size too large"); 3810 OldFormatName.reserve(ComdatNameSize); 3811 for (unsigned i = 0; i != ComdatNameSize; ++i) 3812 OldFormatName += (char)Record[2 + i]; 3813 Name = OldFormatName; 3814 } 3815 Comdat *C = TheModule->getOrInsertComdat(Name); 3816 C->setSelectionKind(SK); 3817 ComdatList.push_back(C); 3818 return Error::success(); 3819 } 3820 3821 static void inferDSOLocal(GlobalValue *GV) { 3822 // infer dso_local from linkage and visibility if it is not encoded. 3823 if (GV->hasLocalLinkage() || 3824 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())) 3825 GV->setDSOLocal(true); 3826 } 3827 3828 GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) { 3829 GlobalValue::SanitizerMetadata Meta; 3830 if (V & (1 << 0)) 3831 Meta.NoAddress = true; 3832 if (V & (1 << 1)) 3833 Meta.NoHWAddress = true; 3834 if (V & (1 << 2)) 3835 Meta.Memtag = true; 3836 if (V & (1 << 3)) 3837 Meta.IsDynInit = true; 3838 return Meta; 3839 } 3840 3841 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) { 3842 // v1: [pointer type, isconst, initid, linkage, alignment, section, 3843 // visibility, threadlocal, unnamed_addr, externally_initialized, 3844 // dllstorageclass, comdat, attributes, preemption specifier, 3845 // partition strtab offset, partition strtab size] (name in VST) 3846 // v2: [strtab_offset, strtab_size, v1] 3847 // v3: [v2, code_model] 3848 StringRef Name; 3849 std::tie(Name, Record) = readNameFromStrtab(Record); 3850 3851 if (Record.size() < 6) 3852 return error("Invalid record"); 3853 unsigned TyID = Record[0]; 3854 Type *Ty = getTypeByID(TyID); 3855 if (!Ty) 3856 return error("Invalid record"); 3857 bool isConstant = Record[1] & 1; 3858 bool explicitType = Record[1] & 2; 3859 unsigned AddressSpace; 3860 if (explicitType) { 3861 AddressSpace = Record[1] >> 2; 3862 } else { 3863 if (!Ty->isPointerTy()) 3864 return error("Invalid type for value"); 3865 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3866 TyID = getContainedTypeID(TyID); 3867 Ty = getTypeByID(TyID); 3868 if (!Ty) 3869 return error("Missing element type for old-style global"); 3870 } 3871 3872 uint64_t RawLinkage = Record[3]; 3873 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3874 MaybeAlign Alignment; 3875 if (Error Err = parseAlignmentValue(Record[4], Alignment)) 3876 return Err; 3877 std::string Section; 3878 if (Record[5]) { 3879 if (Record[5] - 1 >= SectionTable.size()) 3880 return error("Invalid ID"); 3881 Section = SectionTable[Record[5] - 1]; 3882 } 3883 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 3884 // Local linkage must have default visibility. 3885 // auto-upgrade `hidden` and `protected` for old bitcode. 3886 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 3887 Visibility = getDecodedVisibility(Record[6]); 3888 3889 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3890 if (Record.size() > 7) 3891 TLM = getDecodedThreadLocalMode(Record[7]); 3892 3893 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 3894 if (Record.size() > 8) 3895 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]); 3896 3897 bool ExternallyInitialized = false; 3898 if (Record.size() > 9) 3899 ExternallyInitialized = Record[9]; 3900 3901 GlobalVariable *NewGV = 3902 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name, 3903 nullptr, TLM, AddressSpace, ExternallyInitialized); 3904 if (Alignment) 3905 NewGV->setAlignment(*Alignment); 3906 if (!Section.empty()) 3907 NewGV->setSection(Section); 3908 NewGV->setVisibility(Visibility); 3909 NewGV->setUnnamedAddr(UnnamedAddr); 3910 3911 if (Record.size() > 10) { 3912 // A GlobalValue with local linkage cannot have a DLL storage class. 3913 if (!NewGV->hasLocalLinkage()) { 3914 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3915 } 3916 } else { 3917 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3918 } 3919 3920 ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID)); 3921 3922 // Remember which value to use for the global initializer. 3923 if (unsigned InitID = Record[2]) 3924 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1)); 3925 3926 if (Record.size() > 11) { 3927 if (unsigned ComdatID = Record[11]) { 3928 if (ComdatID > ComdatList.size()) 3929 return error("Invalid global variable comdat ID"); 3930 NewGV->setComdat(ComdatList[ComdatID - 1]); 3931 } 3932 } else if (hasImplicitComdat(RawLinkage)) { 3933 ImplicitComdatObjects.insert(NewGV); 3934 } 3935 3936 if (Record.size() > 12) { 3937 auto AS = getAttributes(Record[12]).getFnAttrs(); 3938 NewGV->setAttributes(AS); 3939 } 3940 3941 if (Record.size() > 13) { 3942 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13])); 3943 } 3944 inferDSOLocal(NewGV); 3945 3946 // Check whether we have enough values to read a partition name. 3947 if (Record.size() > 15) 3948 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15])); 3949 3950 if (Record.size() > 16 && Record[16]) { 3951 llvm::GlobalValue::SanitizerMetadata Meta = 3952 deserializeSanitizerMetadata(Record[16]); 3953 NewGV->setSanitizerMetadata(Meta); 3954 } 3955 3956 if (Record.size() > 17 && Record[17]) { 3957 if (auto CM = getDecodedCodeModel(Record[17])) 3958 NewGV->setCodeModel(*CM); 3959 else 3960 return error("Invalid global variable code model"); 3961 } 3962 3963 return Error::success(); 3964 } 3965 3966 void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) { 3967 if (ValueTypeCallback) { 3968 (*ValueTypeCallback)( 3969 F, TypeID, [this](unsigned I) { return getTypeByID(I); }, 3970 [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); }); 3971 } 3972 } 3973 3974 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) { 3975 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section, 3976 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat, 3977 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST) 3978 // v2: [strtab_offset, strtab_size, v1] 3979 StringRef Name; 3980 std::tie(Name, Record) = readNameFromStrtab(Record); 3981 3982 if (Record.size() < 8) 3983 return error("Invalid record"); 3984 unsigned FTyID = Record[0]; 3985 Type *FTy = getTypeByID(FTyID); 3986 if (!FTy) 3987 return error("Invalid record"); 3988 if (isa<PointerType>(FTy)) { 3989 FTyID = getContainedTypeID(FTyID, 0); 3990 FTy = getTypeByID(FTyID); 3991 if (!FTy) 3992 return error("Missing element type for old-style function"); 3993 } 3994 3995 if (!isa<FunctionType>(FTy)) 3996 return error("Invalid type for value"); 3997 auto CC = static_cast<CallingConv::ID>(Record[1]); 3998 if (CC & ~CallingConv::MaxID) 3999 return error("Invalid calling convention ID"); 4000 4001 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace(); 4002 if (Record.size() > 16) 4003 AddrSpace = Record[16]; 4004 4005 Function *Func = 4006 Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage, 4007 AddrSpace, Name, TheModule); 4008 4009 assert(Func->getFunctionType() == FTy && 4010 "Incorrect fully specified type provided for function"); 4011 FunctionTypeIDs[Func] = FTyID; 4012 4013 Func->setCallingConv(CC); 4014 bool isProto = Record[2]; 4015 uint64_t RawLinkage = Record[3]; 4016 Func->setLinkage(getDecodedLinkage(RawLinkage)); 4017 Func->setAttributes(getAttributes(Record[4])); 4018 callValueTypeCallback(Func, FTyID); 4019 4020 // Upgrade any old-style byval or sret without a type by propagating the 4021 // argument's pointee type. There should be no opaque pointers where the byval 4022 // type is implicit. 4023 for (unsigned i = 0; i != Func->arg_size(); ++i) { 4024 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 4025 Attribute::InAlloca}) { 4026 if (!Func->hasParamAttribute(i, Kind)) 4027 continue; 4028 4029 if (Func->getParamAttribute(i, Kind).getValueAsType()) 4030 continue; 4031 4032 Func->removeParamAttr(i, Kind); 4033 4034 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1); 4035 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID); 4036 if (!PtrEltTy) 4037 return error("Missing param element type for attribute upgrade"); 4038 4039 Attribute NewAttr; 4040 switch (Kind) { 4041 case Attribute::ByVal: 4042 NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 4043 break; 4044 case Attribute::StructRet: 4045 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 4046 break; 4047 case Attribute::InAlloca: 4048 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 4049 break; 4050 default: 4051 llvm_unreachable("not an upgraded type attribute"); 4052 } 4053 4054 Func->addParamAttr(i, NewAttr); 4055 } 4056 } 4057 4058 if (Func->getCallingConv() == CallingConv::X86_INTR && 4059 !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) { 4060 unsigned ParamTypeID = getContainedTypeID(FTyID, 1); 4061 Type *ByValTy = getPtrElementTypeByID(ParamTypeID); 4062 if (!ByValTy) 4063 return error("Missing param element type for x86_intrcc upgrade"); 4064 Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy); 4065 Func->addParamAttr(0, NewAttr); 4066 } 4067 4068 MaybeAlign Alignment; 4069 if (Error Err = parseAlignmentValue(Record[5], Alignment)) 4070 return Err; 4071 if (Alignment) 4072 Func->setAlignment(*Alignment); 4073 if (Record[6]) { 4074 if (Record[6] - 1 >= SectionTable.size()) 4075 return error("Invalid ID"); 4076 Func->setSection(SectionTable[Record[6] - 1]); 4077 } 4078 // Local linkage must have default visibility. 4079 // auto-upgrade `hidden` and `protected` for old bitcode. 4080 if (!Func->hasLocalLinkage()) 4081 Func->setVisibility(getDecodedVisibility(Record[7])); 4082 if (Record.size() > 8 && Record[8]) { 4083 if (Record[8] - 1 >= GCTable.size()) 4084 return error("Invalid ID"); 4085 Func->setGC(GCTable[Record[8] - 1]); 4086 } 4087 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None; 4088 if (Record.size() > 9) 4089 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]); 4090 Func->setUnnamedAddr(UnnamedAddr); 4091 4092 FunctionOperandInfo OperandInfo = {Func, 0, 0, 0}; 4093 if (Record.size() > 10) 4094 OperandInfo.Prologue = Record[10]; 4095 4096 if (Record.size() > 11) { 4097 // A GlobalValue with local linkage cannot have a DLL storage class. 4098 if (!Func->hasLocalLinkage()) { 4099 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 4100 } 4101 } else { 4102 upgradeDLLImportExportLinkage(Func, RawLinkage); 4103 } 4104 4105 if (Record.size() > 12) { 4106 if (unsigned ComdatID = Record[12]) { 4107 if (ComdatID > ComdatList.size()) 4108 return error("Invalid function comdat ID"); 4109 Func->setComdat(ComdatList[ComdatID - 1]); 4110 } 4111 } else if (hasImplicitComdat(RawLinkage)) { 4112 ImplicitComdatObjects.insert(Func); 4113 } 4114 4115 if (Record.size() > 13) 4116 OperandInfo.Prefix = Record[13]; 4117 4118 if (Record.size() > 14) 4119 OperandInfo.PersonalityFn = Record[14]; 4120 4121 if (Record.size() > 15) { 4122 Func->setDSOLocal(getDecodedDSOLocal(Record[15])); 4123 } 4124 inferDSOLocal(Func); 4125 4126 // Record[16] is the address space number. 4127 4128 // Check whether we have enough values to read a partition name. Also make 4129 // sure Strtab has enough values. 4130 if (Record.size() > 18 && Strtab.data() && 4131 Record[17] + Record[18] <= Strtab.size()) { 4132 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18])); 4133 } 4134 4135 ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID)); 4136 4137 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue) 4138 FunctionOperands.push_back(OperandInfo); 4139 4140 // If this is a function with a body, remember the prototype we are 4141 // creating now, so that we can match up the body with them later. 4142 if (!isProto) { 4143 Func->setIsMaterializable(true); 4144 FunctionsWithBodies.push_back(Func); 4145 DeferredFunctionInfo[Func] = 0; 4146 } 4147 return Error::success(); 4148 } 4149 4150 Error BitcodeReader::parseGlobalIndirectSymbolRecord( 4151 unsigned BitCode, ArrayRef<uint64_t> Record) { 4152 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST) 4153 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 4154 // dllstorageclass, threadlocal, unnamed_addr, 4155 // preemption specifier] (name in VST) 4156 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage, 4157 // visibility, dllstorageclass, threadlocal, unnamed_addr, 4158 // preemption specifier] (name in VST) 4159 // v2: [strtab_offset, strtab_size, v1] 4160 StringRef Name; 4161 std::tie(Name, Record) = readNameFromStrtab(Record); 4162 4163 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD; 4164 if (Record.size() < (3 + (unsigned)NewRecord)) 4165 return error("Invalid record"); 4166 unsigned OpNum = 0; 4167 unsigned TypeID = Record[OpNum++]; 4168 Type *Ty = getTypeByID(TypeID); 4169 if (!Ty) 4170 return error("Invalid record"); 4171 4172 unsigned AddrSpace; 4173 if (!NewRecord) { 4174 auto *PTy = dyn_cast<PointerType>(Ty); 4175 if (!PTy) 4176 return error("Invalid type for value"); 4177 AddrSpace = PTy->getAddressSpace(); 4178 TypeID = getContainedTypeID(TypeID); 4179 Ty = getTypeByID(TypeID); 4180 if (!Ty) 4181 return error("Missing element type for old-style indirect symbol"); 4182 } else { 4183 AddrSpace = Record[OpNum++]; 4184 } 4185 4186 auto Val = Record[OpNum++]; 4187 auto Linkage = Record[OpNum++]; 4188 GlobalValue *NewGA; 4189 if (BitCode == bitc::MODULE_CODE_ALIAS || 4190 BitCode == bitc::MODULE_CODE_ALIAS_OLD) 4191 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 4192 TheModule); 4193 else 4194 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name, 4195 nullptr, TheModule); 4196 4197 // Local linkage must have default visibility. 4198 // auto-upgrade `hidden` and `protected` for old bitcode. 4199 if (OpNum != Record.size()) { 4200 auto VisInd = OpNum++; 4201 if (!NewGA->hasLocalLinkage()) 4202 NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 4203 } 4204 if (BitCode == bitc::MODULE_CODE_ALIAS || 4205 BitCode == bitc::MODULE_CODE_ALIAS_OLD) { 4206 if (OpNum != Record.size()) { 4207 auto S = Record[OpNum++]; 4208 // A GlobalValue with local linkage cannot have a DLL storage class. 4209 if (!NewGA->hasLocalLinkage()) 4210 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S)); 4211 } 4212 else 4213 upgradeDLLImportExportLinkage(NewGA, Linkage); 4214 if (OpNum != Record.size()) 4215 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 4216 if (OpNum != Record.size()) 4217 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++])); 4218 } 4219 if (OpNum != Record.size()) 4220 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++])); 4221 inferDSOLocal(NewGA); 4222 4223 // Check whether we have enough values to read a partition name. 4224 if (OpNum + 1 < Record.size()) { 4225 // Check Strtab has enough values for the partition. 4226 if (Record[OpNum] + Record[OpNum + 1] > Strtab.size()) 4227 return error("Malformed partition, too large."); 4228 NewGA->setPartition( 4229 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1])); 4230 OpNum += 2; 4231 } 4232 4233 ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID)); 4234 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val)); 4235 return Error::success(); 4236 } 4237 4238 Error BitcodeReader::parseModule(uint64_t ResumeBit, 4239 bool ShouldLazyLoadMetadata, 4240 ParserCallbacks Callbacks) { 4241 this->ValueTypeCallback = std::move(Callbacks.ValueType); 4242 if (ResumeBit) { 4243 if (Error JumpFailed = Stream.JumpToBit(ResumeBit)) 4244 return JumpFailed; 4245 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 4246 return Err; 4247 4248 SmallVector<uint64_t, 64> Record; 4249 4250 // Parts of bitcode parsing depend on the datalayout. Make sure we 4251 // finalize the datalayout before we run any of that code. 4252 bool ResolvedDataLayout = false; 4253 // In order to support importing modules with illegal data layout strings, 4254 // delay parsing the data layout string until after upgrades and overrides 4255 // have been applied, allowing to fix illegal data layout strings. 4256 // Initialize to the current module's layout string in case none is specified. 4257 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr(); 4258 4259 auto ResolveDataLayout = [&]() -> Error { 4260 if (ResolvedDataLayout) 4261 return Error::success(); 4262 4263 // Datalayout and triple can't be parsed after this point. 4264 ResolvedDataLayout = true; 4265 4266 // Auto-upgrade the layout string 4267 TentativeDataLayoutStr = llvm::UpgradeDataLayoutString( 4268 TentativeDataLayoutStr, TheModule->getTargetTriple()); 4269 4270 // Apply override 4271 if (Callbacks.DataLayout) { 4272 if (auto LayoutOverride = (*Callbacks.DataLayout)( 4273 TheModule->getTargetTriple(), TentativeDataLayoutStr)) 4274 TentativeDataLayoutStr = *LayoutOverride; 4275 } 4276 4277 // Now the layout string is finalized in TentativeDataLayoutStr. Parse it. 4278 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr); 4279 if (!MaybeDL) 4280 return MaybeDL.takeError(); 4281 4282 TheModule->setDataLayout(MaybeDL.get()); 4283 return Error::success(); 4284 }; 4285 4286 // Read all the records for this module. 4287 while (true) { 4288 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4289 if (!MaybeEntry) 4290 return MaybeEntry.takeError(); 4291 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4292 4293 switch (Entry.Kind) { 4294 case BitstreamEntry::Error: 4295 return error("Malformed block"); 4296 case BitstreamEntry::EndBlock: 4297 if (Error Err = ResolveDataLayout()) 4298 return Err; 4299 return globalCleanup(); 4300 4301 case BitstreamEntry::SubBlock: 4302 switch (Entry.ID) { 4303 default: // Skip unknown content. 4304 if (Error Err = Stream.SkipBlock()) 4305 return Err; 4306 break; 4307 case bitc::BLOCKINFO_BLOCK_ID: 4308 if (Error Err = readBlockInfo()) 4309 return Err; 4310 break; 4311 case bitc::PARAMATTR_BLOCK_ID: 4312 if (Error Err = parseAttributeBlock()) 4313 return Err; 4314 break; 4315 case bitc::PARAMATTR_GROUP_BLOCK_ID: 4316 if (Error Err = parseAttributeGroupBlock()) 4317 return Err; 4318 break; 4319 case bitc::TYPE_BLOCK_ID_NEW: 4320 if (Error Err = parseTypeTable()) 4321 return Err; 4322 break; 4323 case bitc::VALUE_SYMTAB_BLOCK_ID: 4324 if (!SeenValueSymbolTable) { 4325 // Either this is an old form VST without function index and an 4326 // associated VST forward declaration record (which would have caused 4327 // the VST to be jumped to and parsed before it was encountered 4328 // normally in the stream), or there were no function blocks to 4329 // trigger an earlier parsing of the VST. 4330 assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 4331 if (Error Err = parseValueSymbolTable()) 4332 return Err; 4333 SeenValueSymbolTable = true; 4334 } else { 4335 // We must have had a VST forward declaration record, which caused 4336 // the parser to jump to and parse the VST earlier. 4337 assert(VSTOffset > 0); 4338 if (Error Err = Stream.SkipBlock()) 4339 return Err; 4340 } 4341 break; 4342 case bitc::CONSTANTS_BLOCK_ID: 4343 if (Error Err = parseConstants()) 4344 return Err; 4345 if (Error Err = resolveGlobalAndIndirectSymbolInits()) 4346 return Err; 4347 break; 4348 case bitc::METADATA_BLOCK_ID: 4349 if (ShouldLazyLoadMetadata) { 4350 if (Error Err = rememberAndSkipMetadata()) 4351 return Err; 4352 break; 4353 } 4354 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 4355 if (Error Err = MDLoader->parseModuleMetadata()) 4356 return Err; 4357 break; 4358 case bitc::METADATA_KIND_BLOCK_ID: 4359 if (Error Err = MDLoader->parseMetadataKinds()) 4360 return Err; 4361 break; 4362 case bitc::FUNCTION_BLOCK_ID: 4363 if (Error Err = ResolveDataLayout()) 4364 return Err; 4365 4366 // If this is the first function body we've seen, reverse the 4367 // FunctionsWithBodies list. 4368 if (!SeenFirstFunctionBody) { 4369 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 4370 if (Error Err = globalCleanup()) 4371 return Err; 4372 SeenFirstFunctionBody = true; 4373 } 4374 4375 if (VSTOffset > 0) { 4376 // If we have a VST forward declaration record, make sure we 4377 // parse the VST now if we haven't already. It is needed to 4378 // set up the DeferredFunctionInfo vector for lazy reading. 4379 if (!SeenValueSymbolTable) { 4380 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset)) 4381 return Err; 4382 SeenValueSymbolTable = true; 4383 // Fall through so that we record the NextUnreadBit below. 4384 // This is necessary in case we have an anonymous function that 4385 // is later materialized. Since it will not have a VST entry we 4386 // need to fall back to the lazy parse to find its offset. 4387 } else { 4388 // If we have a VST forward declaration record, but have already 4389 // parsed the VST (just above, when the first function body was 4390 // encountered here), then we are resuming the parse after 4391 // materializing functions. The ResumeBit points to the 4392 // start of the last function block recorded in the 4393 // DeferredFunctionInfo map. Skip it. 4394 if (Error Err = Stream.SkipBlock()) 4395 return Err; 4396 continue; 4397 } 4398 } 4399 4400 // Support older bitcode files that did not have the function 4401 // index in the VST, nor a VST forward declaration record, as 4402 // well as anonymous functions that do not have VST entries. 4403 // Build the DeferredFunctionInfo vector on the fly. 4404 if (Error Err = rememberAndSkipFunctionBody()) 4405 return Err; 4406 4407 // Suspend parsing when we reach the function bodies. Subsequent 4408 // materialization calls will resume it when necessary. If the bitcode 4409 // file is old, the symbol table will be at the end instead and will not 4410 // have been seen yet. In this case, just finish the parse now. 4411 if (SeenValueSymbolTable) { 4412 NextUnreadBit = Stream.GetCurrentBitNo(); 4413 // After the VST has been parsed, we need to make sure intrinsic name 4414 // are auto-upgraded. 4415 return globalCleanup(); 4416 } 4417 break; 4418 case bitc::USELIST_BLOCK_ID: 4419 if (Error Err = parseUseLists()) 4420 return Err; 4421 break; 4422 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 4423 if (Error Err = parseOperandBundleTags()) 4424 return Err; 4425 break; 4426 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID: 4427 if (Error Err = parseSyncScopeNames()) 4428 return Err; 4429 break; 4430 } 4431 continue; 4432 4433 case BitstreamEntry::Record: 4434 // The interesting case. 4435 break; 4436 } 4437 4438 // Read a record. 4439 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 4440 if (!MaybeBitCode) 4441 return MaybeBitCode.takeError(); 4442 switch (unsigned BitCode = MaybeBitCode.get()) { 4443 default: break; // Default behavior, ignore unknown content. 4444 case bitc::MODULE_CODE_VERSION: { 4445 Expected<unsigned> VersionOrErr = parseVersionRecord(Record); 4446 if (!VersionOrErr) 4447 return VersionOrErr.takeError(); 4448 UseRelativeIDs = *VersionOrErr >= 1; 4449 break; 4450 } 4451 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 4452 if (ResolvedDataLayout) 4453 return error("target triple too late in module"); 4454 std::string S; 4455 if (convertToString(Record, 0, S)) 4456 return error("Invalid record"); 4457 TheModule->setTargetTriple(S); 4458 break; 4459 } 4460 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 4461 if (ResolvedDataLayout) 4462 return error("datalayout too late in module"); 4463 if (convertToString(Record, 0, TentativeDataLayoutStr)) 4464 return error("Invalid record"); 4465 break; 4466 } 4467 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 4468 std::string S; 4469 if (convertToString(Record, 0, S)) 4470 return error("Invalid record"); 4471 TheModule->setModuleInlineAsm(S); 4472 break; 4473 } 4474 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 4475 // Deprecated, but still needed to read old bitcode files. 4476 std::string S; 4477 if (convertToString(Record, 0, S)) 4478 return error("Invalid record"); 4479 // Ignore value. 4480 break; 4481 } 4482 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 4483 std::string S; 4484 if (convertToString(Record, 0, S)) 4485 return error("Invalid record"); 4486 SectionTable.push_back(S); 4487 break; 4488 } 4489 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 4490 std::string S; 4491 if (convertToString(Record, 0, S)) 4492 return error("Invalid record"); 4493 GCTable.push_back(S); 4494 break; 4495 } 4496 case bitc::MODULE_CODE_COMDAT: 4497 if (Error Err = parseComdatRecord(Record)) 4498 return Err; 4499 break; 4500 // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC} 4501 // written by ThinLinkBitcodeWriter. See 4502 // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each 4503 // record 4504 // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714) 4505 case bitc::MODULE_CODE_GLOBALVAR: 4506 if (Error Err = parseGlobalVarRecord(Record)) 4507 return Err; 4508 break; 4509 case bitc::MODULE_CODE_FUNCTION: 4510 if (Error Err = ResolveDataLayout()) 4511 return Err; 4512 if (Error Err = parseFunctionRecord(Record)) 4513 return Err; 4514 break; 4515 case bitc::MODULE_CODE_IFUNC: 4516 case bitc::MODULE_CODE_ALIAS: 4517 case bitc::MODULE_CODE_ALIAS_OLD: 4518 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record)) 4519 return Err; 4520 break; 4521 /// MODULE_CODE_VSTOFFSET: [offset] 4522 case bitc::MODULE_CODE_VSTOFFSET: 4523 if (Record.empty()) 4524 return error("Invalid record"); 4525 // Note that we subtract 1 here because the offset is relative to one word 4526 // before the start of the identification or module block, which was 4527 // historically always the start of the regular bitcode header. 4528 VSTOffset = Record[0] - 1; 4529 break; 4530 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 4531 case bitc::MODULE_CODE_SOURCE_FILENAME: 4532 SmallString<128> ValueName; 4533 if (convertToString(Record, 0, ValueName)) 4534 return error("Invalid record"); 4535 TheModule->setSourceFileName(ValueName); 4536 break; 4537 } 4538 Record.clear(); 4539 } 4540 this->ValueTypeCallback = std::nullopt; 4541 return Error::success(); 4542 } 4543 4544 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata, 4545 bool IsImporting, 4546 ParserCallbacks Callbacks) { 4547 TheModule = M; 4548 MetadataLoaderCallbacks MDCallbacks; 4549 MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); }; 4550 MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) { 4551 return getContainedTypeID(I, J); 4552 }; 4553 MDCallbacks.MDType = Callbacks.MDType; 4554 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks); 4555 return parseModule(0, ShouldLazyLoadMetadata, Callbacks); 4556 } 4557 4558 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 4559 if (!isa<PointerType>(PtrType)) 4560 return error("Load/Store operand is not a pointer type"); 4561 if (!PointerType::isLoadableOrStorableType(ValType)) 4562 return error("Cannot load/store from pointer"); 4563 return Error::success(); 4564 } 4565 4566 Error BitcodeReader::propagateAttributeTypes(CallBase *CB, 4567 ArrayRef<unsigned> ArgTyIDs) { 4568 AttributeList Attrs = CB->getAttributes(); 4569 for (unsigned i = 0; i != CB->arg_size(); ++i) { 4570 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet, 4571 Attribute::InAlloca}) { 4572 if (!Attrs.hasParamAttr(i, Kind) || 4573 Attrs.getParamAttr(i, Kind).getValueAsType()) 4574 continue; 4575 4576 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]); 4577 if (!PtrEltTy) 4578 return error("Missing element type for typed attribute upgrade"); 4579 4580 Attribute NewAttr; 4581 switch (Kind) { 4582 case Attribute::ByVal: 4583 NewAttr = Attribute::getWithByValType(Context, PtrEltTy); 4584 break; 4585 case Attribute::StructRet: 4586 NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy); 4587 break; 4588 case Attribute::InAlloca: 4589 NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy); 4590 break; 4591 default: 4592 llvm_unreachable("not an upgraded type attribute"); 4593 } 4594 4595 Attrs = Attrs.addParamAttribute(Context, i, NewAttr); 4596 } 4597 } 4598 4599 if (CB->isInlineAsm()) { 4600 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); 4601 unsigned ArgNo = 0; 4602 for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 4603 if (!CI.hasArg()) 4604 continue; 4605 4606 if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) { 4607 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); 4608 if (!ElemTy) 4609 return error("Missing element type for inline asm upgrade"); 4610 Attrs = Attrs.addParamAttribute( 4611 Context, ArgNo, 4612 Attribute::get(Context, Attribute::ElementType, ElemTy)); 4613 } 4614 4615 ArgNo++; 4616 } 4617 } 4618 4619 switch (CB->getIntrinsicID()) { 4620 case Intrinsic::preserve_array_access_index: 4621 case Intrinsic::preserve_struct_access_index: 4622 case Intrinsic::aarch64_ldaxr: 4623 case Intrinsic::aarch64_ldxr: 4624 case Intrinsic::aarch64_stlxr: 4625 case Intrinsic::aarch64_stxr: 4626 case Intrinsic::arm_ldaex: 4627 case Intrinsic::arm_ldrex: 4628 case Intrinsic::arm_stlex: 4629 case Intrinsic::arm_strex: { 4630 unsigned ArgNo; 4631 switch (CB->getIntrinsicID()) { 4632 case Intrinsic::aarch64_stlxr: 4633 case Intrinsic::aarch64_stxr: 4634 case Intrinsic::arm_stlex: 4635 case Intrinsic::arm_strex: 4636 ArgNo = 1; 4637 break; 4638 default: 4639 ArgNo = 0; 4640 break; 4641 } 4642 if (!Attrs.getParamElementType(ArgNo)) { 4643 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]); 4644 if (!ElTy) 4645 return error("Missing element type for elementtype upgrade"); 4646 Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy); 4647 Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr); 4648 } 4649 break; 4650 } 4651 default: 4652 break; 4653 } 4654 4655 CB->setAttributes(Attrs); 4656 return Error::success(); 4657 } 4658 4659 /// Lazily parse the specified function body block. 4660 Error BitcodeReader::parseFunctionBody(Function *F) { 4661 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 4662 return Err; 4663 4664 // Unexpected unresolved metadata when parsing function. 4665 if (MDLoader->hasFwdRefs()) 4666 return error("Invalid function metadata: incoming forward references"); 4667 4668 InstructionList.clear(); 4669 unsigned ModuleValueListSize = ValueList.size(); 4670 unsigned ModuleMDLoaderSize = MDLoader->size(); 4671 4672 // Add all the function arguments to the value table. 4673 unsigned ArgNo = 0; 4674 unsigned FTyID = FunctionTypeIDs[F]; 4675 for (Argument &I : F->args()) { 4676 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1); 4677 assert(I.getType() == getTypeByID(ArgTyID) && 4678 "Incorrect fully specified type for Function Argument"); 4679 ValueList.push_back(&I, ArgTyID); 4680 ++ArgNo; 4681 } 4682 unsigned NextValueNo = ValueList.size(); 4683 BasicBlock *CurBB = nullptr; 4684 unsigned CurBBNo = 0; 4685 // Block into which constant expressions from phi nodes are materialized. 4686 BasicBlock *PhiConstExprBB = nullptr; 4687 // Edge blocks for phi nodes into which constant expressions have been 4688 // expanded. 4689 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4> 4690 ConstExprEdgeBBs; 4691 4692 DebugLoc LastLoc; 4693 auto getLastInstruction = [&]() -> Instruction * { 4694 if (CurBB && !CurBB->empty()) 4695 return &CurBB->back(); 4696 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 4697 !FunctionBBs[CurBBNo - 1]->empty()) 4698 return &FunctionBBs[CurBBNo - 1]->back(); 4699 return nullptr; 4700 }; 4701 4702 std::vector<OperandBundleDef> OperandBundles; 4703 4704 // Read all the records. 4705 SmallVector<uint64_t, 64> Record; 4706 4707 while (true) { 4708 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 4709 if (!MaybeEntry) 4710 return MaybeEntry.takeError(); 4711 llvm::BitstreamEntry Entry = MaybeEntry.get(); 4712 4713 switch (Entry.Kind) { 4714 case BitstreamEntry::Error: 4715 return error("Malformed block"); 4716 case BitstreamEntry::EndBlock: 4717 goto OutOfRecordLoop; 4718 4719 case BitstreamEntry::SubBlock: 4720 switch (Entry.ID) { 4721 default: // Skip unknown content. 4722 if (Error Err = Stream.SkipBlock()) 4723 return Err; 4724 break; 4725 case bitc::CONSTANTS_BLOCK_ID: 4726 if (Error Err = parseConstants()) 4727 return Err; 4728 NextValueNo = ValueList.size(); 4729 break; 4730 case bitc::VALUE_SYMTAB_BLOCK_ID: 4731 if (Error Err = parseValueSymbolTable()) 4732 return Err; 4733 break; 4734 case bitc::METADATA_ATTACHMENT_ID: 4735 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList)) 4736 return Err; 4737 break; 4738 case bitc::METADATA_BLOCK_ID: 4739 assert(DeferredMetadataInfo.empty() && 4740 "Must read all module-level metadata before function-level"); 4741 if (Error Err = MDLoader->parseFunctionMetadata()) 4742 return Err; 4743 break; 4744 case bitc::USELIST_BLOCK_ID: 4745 if (Error Err = parseUseLists()) 4746 return Err; 4747 break; 4748 } 4749 continue; 4750 4751 case BitstreamEntry::Record: 4752 // The interesting case. 4753 break; 4754 } 4755 4756 // Read a record. 4757 Record.clear(); 4758 Instruction *I = nullptr; 4759 unsigned ResTypeID = InvalidTypeID; 4760 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 4761 if (!MaybeBitCode) 4762 return MaybeBitCode.takeError(); 4763 switch (unsigned BitCode = MaybeBitCode.get()) { 4764 default: // Default behavior: reject 4765 return error("Invalid value"); 4766 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4767 if (Record.empty() || Record[0] == 0) 4768 return error("Invalid record"); 4769 // Create all the basic blocks for the function. 4770 FunctionBBs.resize(Record[0]); 4771 4772 // See if anything took the address of blocks in this function. 4773 auto BBFRI = BasicBlockFwdRefs.find(F); 4774 if (BBFRI == BasicBlockFwdRefs.end()) { 4775 for (BasicBlock *&BB : FunctionBBs) 4776 BB = BasicBlock::Create(Context, "", F); 4777 } else { 4778 auto &BBRefs = BBFRI->second; 4779 // Check for invalid basic block references. 4780 if (BBRefs.size() > FunctionBBs.size()) 4781 return error("Invalid ID"); 4782 assert(!BBRefs.empty() && "Unexpected empty array"); 4783 assert(!BBRefs.front() && "Invalid reference to entry block"); 4784 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4785 ++I) 4786 if (I < RE && BBRefs[I]) { 4787 BBRefs[I]->insertInto(F); 4788 FunctionBBs[I] = BBRefs[I]; 4789 } else { 4790 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4791 } 4792 4793 // Erase from the table. 4794 BasicBlockFwdRefs.erase(BBFRI); 4795 } 4796 4797 CurBB = FunctionBBs[0]; 4798 continue; 4799 } 4800 4801 case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...] 4802 // The record should not be emitted if it's an empty list. 4803 if (Record.empty()) 4804 return error("Invalid record"); 4805 // When we have the RARE case of a BlockAddress Constant that is not 4806 // scoped to the Function it refers to, we need to conservatively 4807 // materialize the referred to Function, regardless of whether or not 4808 // that Function will ultimately be linked, otherwise users of 4809 // BitcodeReader might start splicing out Function bodies such that we 4810 // might no longer be able to materialize the BlockAddress since the 4811 // BasicBlock (and entire body of the Function) the BlockAddress refers 4812 // to may have been moved. In the case that the user of BitcodeReader 4813 // decides ultimately not to link the Function body, materializing here 4814 // could be considered wasteful, but it's better than a deserialization 4815 // failure as described. This keeps BitcodeReader unaware of complex 4816 // linkage policy decisions such as those use by LTO, leaving those 4817 // decisions "one layer up." 4818 for (uint64_t ValID : Record) 4819 if (auto *F = dyn_cast<Function>(ValueList[ValID])) 4820 BackwardRefFunctions.push_back(F); 4821 else 4822 return error("Invalid record"); 4823 4824 continue; 4825 4826 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4827 // This record indicates that the last instruction is at the same 4828 // location as the previous instruction with a location. 4829 I = getLastInstruction(); 4830 4831 if (!I) 4832 return error("Invalid record"); 4833 I->setDebugLoc(LastLoc); 4834 I = nullptr; 4835 continue; 4836 4837 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4838 I = getLastInstruction(); 4839 if (!I || Record.size() < 4) 4840 return error("Invalid record"); 4841 4842 unsigned Line = Record[0], Col = Record[1]; 4843 unsigned ScopeID = Record[2], IAID = Record[3]; 4844 bool isImplicitCode = Record.size() == 5 && Record[4]; 4845 4846 MDNode *Scope = nullptr, *IA = nullptr; 4847 if (ScopeID) { 4848 Scope = dyn_cast_or_null<MDNode>( 4849 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1)); 4850 if (!Scope) 4851 return error("Invalid record"); 4852 } 4853 if (IAID) { 4854 IA = dyn_cast_or_null<MDNode>( 4855 MDLoader->getMetadataFwdRefOrLoad(IAID - 1)); 4856 if (!IA) 4857 return error("Invalid record"); 4858 } 4859 LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA, 4860 isImplicitCode); 4861 I->setDebugLoc(LastLoc); 4862 I = nullptr; 4863 continue; 4864 } 4865 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] 4866 unsigned OpNum = 0; 4867 Value *LHS; 4868 unsigned TypeID; 4869 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || 4870 OpNum+1 > Record.size()) 4871 return error("Invalid record"); 4872 4873 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); 4874 if (Opc == -1) 4875 return error("Invalid record"); 4876 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS); 4877 ResTypeID = TypeID; 4878 InstructionList.push_back(I); 4879 if (OpNum < Record.size()) { 4880 if (isa<FPMathOperator>(I)) { 4881 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4882 if (FMF.any()) 4883 I->setFastMathFlags(FMF); 4884 } 4885 } 4886 break; 4887 } 4888 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4889 unsigned OpNum = 0; 4890 Value *LHS, *RHS; 4891 unsigned TypeID; 4892 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) || 4893 popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS, 4894 CurBB) || 4895 OpNum+1 > Record.size()) 4896 return error("Invalid record"); 4897 4898 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4899 if (Opc == -1) 4900 return error("Invalid record"); 4901 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4902 ResTypeID = TypeID; 4903 InstructionList.push_back(I); 4904 if (OpNum < Record.size()) { 4905 if (Opc == Instruction::Add || 4906 Opc == Instruction::Sub || 4907 Opc == Instruction::Mul || 4908 Opc == Instruction::Shl) { 4909 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4910 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4911 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4912 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4913 } else if (Opc == Instruction::SDiv || 4914 Opc == Instruction::UDiv || 4915 Opc == Instruction::LShr || 4916 Opc == Instruction::AShr) { 4917 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4918 cast<BinaryOperator>(I)->setIsExact(true); 4919 } else if (Opc == Instruction::Or) { 4920 if (Record[OpNum] & (1 << bitc::PDI_DISJOINT)) 4921 cast<PossiblyDisjointInst>(I)->setIsDisjoint(true); 4922 } else if (isa<FPMathOperator>(I)) { 4923 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4924 if (FMF.any()) 4925 I->setFastMathFlags(FMF); 4926 } 4927 } 4928 break; 4929 } 4930 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4931 unsigned OpNum = 0; 4932 Value *Op; 4933 unsigned OpTypeID; 4934 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 4935 OpNum + 1 > Record.size()) 4936 return error("Invalid record"); 4937 4938 ResTypeID = Record[OpNum++]; 4939 Type *ResTy = getTypeByID(ResTypeID); 4940 int Opc = getDecodedCastOpcode(Record[OpNum++]); 4941 4942 if (Opc == -1 || !ResTy) 4943 return error("Invalid record"); 4944 Instruction *Temp = nullptr; 4945 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4946 if (Temp) { 4947 InstructionList.push_back(Temp); 4948 assert(CurBB && "No current BB?"); 4949 Temp->insertInto(CurBB, CurBB->end()); 4950 } 4951 } else { 4952 auto CastOp = (Instruction::CastOps)Opc; 4953 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4954 return error("Invalid cast"); 4955 I = CastInst::Create(CastOp, Op, ResTy); 4956 } 4957 if (OpNum < Record.size() && isa<PossiblyNonNegInst>(I) && 4958 (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))) 4959 I->setNonNeg(true); 4960 InstructionList.push_back(I); 4961 break; 4962 } 4963 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4964 case bitc::FUNC_CODE_INST_GEP_OLD: 4965 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4966 unsigned OpNum = 0; 4967 4968 unsigned TyID; 4969 Type *Ty; 4970 bool InBounds; 4971 4972 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4973 InBounds = Record[OpNum++]; 4974 TyID = Record[OpNum++]; 4975 Ty = getTypeByID(TyID); 4976 } else { 4977 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4978 TyID = InvalidTypeID; 4979 Ty = nullptr; 4980 } 4981 4982 Value *BasePtr; 4983 unsigned BasePtrTypeID; 4984 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID, 4985 CurBB)) 4986 return error("Invalid record"); 4987 4988 if (!Ty) { 4989 TyID = getContainedTypeID(BasePtrTypeID); 4990 if (BasePtr->getType()->isVectorTy()) 4991 TyID = getContainedTypeID(TyID); 4992 Ty = getTypeByID(TyID); 4993 } 4994 4995 SmallVector<Value*, 16> GEPIdx; 4996 while (OpNum != Record.size()) { 4997 Value *Op; 4998 unsigned OpTypeID; 4999 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5000 return error("Invalid record"); 5001 GEPIdx.push_back(Op); 5002 } 5003 5004 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 5005 5006 ResTypeID = TyID; 5007 if (cast<GEPOperator>(I)->getNumIndices() != 0) { 5008 auto GTI = std::next(gep_type_begin(I)); 5009 for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) { 5010 unsigned SubType = 0; 5011 if (GTI.isStruct()) { 5012 ConstantInt *IdxC = 5013 Idx->getType()->isVectorTy() 5014 ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue()) 5015 : cast<ConstantInt>(Idx); 5016 SubType = IdxC->getZExtValue(); 5017 } 5018 ResTypeID = getContainedTypeID(ResTypeID, SubType); 5019 ++GTI; 5020 } 5021 } 5022 5023 // At this point ResTypeID is the result element type. We need a pointer 5024 // or vector of pointer to it. 5025 ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID); 5026 if (I->getType()->isVectorTy()) 5027 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 5028 5029 InstructionList.push_back(I); 5030 if (InBounds) 5031 cast<GetElementPtrInst>(I)->setIsInBounds(true); 5032 break; 5033 } 5034 5035 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 5036 // EXTRACTVAL: [opty, opval, n x indices] 5037 unsigned OpNum = 0; 5038 Value *Agg; 5039 unsigned AggTypeID; 5040 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 5041 return error("Invalid record"); 5042 Type *Ty = Agg->getType(); 5043 5044 unsigned RecSize = Record.size(); 5045 if (OpNum == RecSize) 5046 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 5047 5048 SmallVector<unsigned, 4> EXTRACTVALIdx; 5049 ResTypeID = AggTypeID; 5050 for (; OpNum != RecSize; ++OpNum) { 5051 bool IsArray = Ty->isArrayTy(); 5052 bool IsStruct = Ty->isStructTy(); 5053 uint64_t Index = Record[OpNum]; 5054 5055 if (!IsStruct && !IsArray) 5056 return error("EXTRACTVAL: Invalid type"); 5057 if ((unsigned)Index != Index) 5058 return error("Invalid value"); 5059 if (IsStruct && Index >= Ty->getStructNumElements()) 5060 return error("EXTRACTVAL: Invalid struct index"); 5061 if (IsArray && Index >= Ty->getArrayNumElements()) 5062 return error("EXTRACTVAL: Invalid array index"); 5063 EXTRACTVALIdx.push_back((unsigned)Index); 5064 5065 if (IsStruct) { 5066 Ty = Ty->getStructElementType(Index); 5067 ResTypeID = getContainedTypeID(ResTypeID, Index); 5068 } else { 5069 Ty = Ty->getArrayElementType(); 5070 ResTypeID = getContainedTypeID(ResTypeID); 5071 } 5072 } 5073 5074 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 5075 InstructionList.push_back(I); 5076 break; 5077 } 5078 5079 case bitc::FUNC_CODE_INST_INSERTVAL: { 5080 // INSERTVAL: [opty, opval, opty, opval, n x indices] 5081 unsigned OpNum = 0; 5082 Value *Agg; 5083 unsigned AggTypeID; 5084 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB)) 5085 return error("Invalid record"); 5086 Value *Val; 5087 unsigned ValTypeID; 5088 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 5089 return error("Invalid record"); 5090 5091 unsigned RecSize = Record.size(); 5092 if (OpNum == RecSize) 5093 return error("INSERTVAL: Invalid instruction with 0 indices"); 5094 5095 SmallVector<unsigned, 4> INSERTVALIdx; 5096 Type *CurTy = Agg->getType(); 5097 for (; OpNum != RecSize; ++OpNum) { 5098 bool IsArray = CurTy->isArrayTy(); 5099 bool IsStruct = CurTy->isStructTy(); 5100 uint64_t Index = Record[OpNum]; 5101 5102 if (!IsStruct && !IsArray) 5103 return error("INSERTVAL: Invalid type"); 5104 if ((unsigned)Index != Index) 5105 return error("Invalid value"); 5106 if (IsStruct && Index >= CurTy->getStructNumElements()) 5107 return error("INSERTVAL: Invalid struct index"); 5108 if (IsArray && Index >= CurTy->getArrayNumElements()) 5109 return error("INSERTVAL: Invalid array index"); 5110 5111 INSERTVALIdx.push_back((unsigned)Index); 5112 if (IsStruct) 5113 CurTy = CurTy->getStructElementType(Index); 5114 else 5115 CurTy = CurTy->getArrayElementType(); 5116 } 5117 5118 if (CurTy != Val->getType()) 5119 return error("Inserted value type doesn't match aggregate type"); 5120 5121 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 5122 ResTypeID = AggTypeID; 5123 InstructionList.push_back(I); 5124 break; 5125 } 5126 5127 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 5128 // obsolete form of select 5129 // handles select i1 ... in old bitcode 5130 unsigned OpNum = 0; 5131 Value *TrueVal, *FalseVal, *Cond; 5132 unsigned TypeID; 5133 Type *CondType = Type::getInt1Ty(Context); 5134 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID, 5135 CurBB) || 5136 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID, 5137 FalseVal, CurBB) || 5138 popValue(Record, OpNum, NextValueNo, CondType, 5139 getVirtualTypeID(CondType), Cond, CurBB)) 5140 return error("Invalid record"); 5141 5142 I = SelectInst::Create(Cond, TrueVal, FalseVal); 5143 ResTypeID = TypeID; 5144 InstructionList.push_back(I); 5145 break; 5146 } 5147 5148 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 5149 // new form of select 5150 // handles select i1 or select [N x i1] 5151 unsigned OpNum = 0; 5152 Value *TrueVal, *FalseVal, *Cond; 5153 unsigned ValTypeID, CondTypeID; 5154 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID, 5155 CurBB) || 5156 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID, 5157 FalseVal, CurBB) || 5158 getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB)) 5159 return error("Invalid record"); 5160 5161 // select condition can be either i1 or [N x i1] 5162 if (VectorType* vector_type = 5163 dyn_cast<VectorType>(Cond->getType())) { 5164 // expect <n x i1> 5165 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 5166 return error("Invalid type for value"); 5167 } else { 5168 // expect i1 5169 if (Cond->getType() != Type::getInt1Ty(Context)) 5170 return error("Invalid type for value"); 5171 } 5172 5173 I = SelectInst::Create(Cond, TrueVal, FalseVal); 5174 ResTypeID = ValTypeID; 5175 InstructionList.push_back(I); 5176 if (OpNum < Record.size() && isa<FPMathOperator>(I)) { 5177 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 5178 if (FMF.any()) 5179 I->setFastMathFlags(FMF); 5180 } 5181 break; 5182 } 5183 5184 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 5185 unsigned OpNum = 0; 5186 Value *Vec, *Idx; 5187 unsigned VecTypeID, IdxTypeID; 5188 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) || 5189 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 5190 return error("Invalid record"); 5191 if (!Vec->getType()->isVectorTy()) 5192 return error("Invalid type for value"); 5193 I = ExtractElementInst::Create(Vec, Idx); 5194 ResTypeID = getContainedTypeID(VecTypeID); 5195 InstructionList.push_back(I); 5196 break; 5197 } 5198 5199 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 5200 unsigned OpNum = 0; 5201 Value *Vec, *Elt, *Idx; 5202 unsigned VecTypeID, IdxTypeID; 5203 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB)) 5204 return error("Invalid record"); 5205 if (!Vec->getType()->isVectorTy()) 5206 return error("Invalid type for value"); 5207 if (popValue(Record, OpNum, NextValueNo, 5208 cast<VectorType>(Vec->getType())->getElementType(), 5209 getContainedTypeID(VecTypeID), Elt, CurBB) || 5210 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB)) 5211 return error("Invalid record"); 5212 I = InsertElementInst::Create(Vec, Elt, Idx); 5213 ResTypeID = VecTypeID; 5214 InstructionList.push_back(I); 5215 break; 5216 } 5217 5218 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 5219 unsigned OpNum = 0; 5220 Value *Vec1, *Vec2, *Mask; 5221 unsigned Vec1TypeID; 5222 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID, 5223 CurBB) || 5224 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID, 5225 Vec2, CurBB)) 5226 return error("Invalid record"); 5227 5228 unsigned MaskTypeID; 5229 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB)) 5230 return error("Invalid record"); 5231 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 5232 return error("Invalid type for value"); 5233 5234 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 5235 ResTypeID = 5236 getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID)); 5237 InstructionList.push_back(I); 5238 break; 5239 } 5240 5241 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 5242 // Old form of ICmp/FCmp returning bool 5243 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 5244 // both legal on vectors but had different behaviour. 5245 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 5246 // FCmp/ICmp returning bool or vector of bool 5247 5248 unsigned OpNum = 0; 5249 Value *LHS, *RHS; 5250 unsigned LHSTypeID; 5251 if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) || 5252 popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS, 5253 CurBB)) 5254 return error("Invalid record"); 5255 5256 if (OpNum >= Record.size()) 5257 return error( 5258 "Invalid record: operand number exceeded available operands"); 5259 5260 CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]); 5261 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 5262 FastMathFlags FMF; 5263 if (IsFP && Record.size() > OpNum+1) 5264 FMF = getDecodedFastMathFlags(Record[++OpNum]); 5265 5266 if (OpNum+1 != Record.size()) 5267 return error("Invalid record"); 5268 5269 if (IsFP) { 5270 if (!CmpInst::isFPPredicate(PredVal)) 5271 return error("Invalid fcmp predicate"); 5272 I = new FCmpInst(PredVal, LHS, RHS); 5273 } else { 5274 if (!CmpInst::isIntPredicate(PredVal)) 5275 return error("Invalid icmp predicate"); 5276 I = new ICmpInst(PredVal, LHS, RHS); 5277 } 5278 5279 ResTypeID = getVirtualTypeID(I->getType()->getScalarType()); 5280 if (LHS->getType()->isVectorTy()) 5281 ResTypeID = getVirtualTypeID(I->getType(), ResTypeID); 5282 5283 if (FMF.any()) 5284 I->setFastMathFlags(FMF); 5285 InstructionList.push_back(I); 5286 break; 5287 } 5288 5289 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 5290 { 5291 unsigned Size = Record.size(); 5292 if (Size == 0) { 5293 I = ReturnInst::Create(Context); 5294 InstructionList.push_back(I); 5295 break; 5296 } 5297 5298 unsigned OpNum = 0; 5299 Value *Op = nullptr; 5300 unsigned OpTypeID; 5301 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5302 return error("Invalid record"); 5303 if (OpNum != Record.size()) 5304 return error("Invalid record"); 5305 5306 I = ReturnInst::Create(Context, Op); 5307 InstructionList.push_back(I); 5308 break; 5309 } 5310 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 5311 if (Record.size() != 1 && Record.size() != 3) 5312 return error("Invalid record"); 5313 BasicBlock *TrueDest = getBasicBlock(Record[0]); 5314 if (!TrueDest) 5315 return error("Invalid record"); 5316 5317 if (Record.size() == 1) { 5318 I = BranchInst::Create(TrueDest); 5319 InstructionList.push_back(I); 5320 } 5321 else { 5322 BasicBlock *FalseDest = getBasicBlock(Record[1]); 5323 Type *CondType = Type::getInt1Ty(Context); 5324 Value *Cond = getValue(Record, 2, NextValueNo, CondType, 5325 getVirtualTypeID(CondType), CurBB); 5326 if (!FalseDest || !Cond) 5327 return error("Invalid record"); 5328 I = BranchInst::Create(TrueDest, FalseDest, Cond); 5329 InstructionList.push_back(I); 5330 } 5331 break; 5332 } 5333 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 5334 if (Record.size() != 1 && Record.size() != 2) 5335 return error("Invalid record"); 5336 unsigned Idx = 0; 5337 Type *TokenTy = Type::getTokenTy(Context); 5338 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5339 getVirtualTypeID(TokenTy), CurBB); 5340 if (!CleanupPad) 5341 return error("Invalid record"); 5342 BasicBlock *UnwindDest = nullptr; 5343 if (Record.size() == 2) { 5344 UnwindDest = getBasicBlock(Record[Idx++]); 5345 if (!UnwindDest) 5346 return error("Invalid record"); 5347 } 5348 5349 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 5350 InstructionList.push_back(I); 5351 break; 5352 } 5353 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 5354 if (Record.size() != 2) 5355 return error("Invalid record"); 5356 unsigned Idx = 0; 5357 Type *TokenTy = Type::getTokenTy(Context); 5358 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5359 getVirtualTypeID(TokenTy), CurBB); 5360 if (!CatchPad) 5361 return error("Invalid record"); 5362 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5363 if (!BB) 5364 return error("Invalid record"); 5365 5366 I = CatchReturnInst::Create(CatchPad, BB); 5367 InstructionList.push_back(I); 5368 break; 5369 } 5370 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 5371 // We must have, at minimum, the outer scope and the number of arguments. 5372 if (Record.size() < 2) 5373 return error("Invalid record"); 5374 5375 unsigned Idx = 0; 5376 5377 Type *TokenTy = Type::getTokenTy(Context); 5378 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5379 getVirtualTypeID(TokenTy), CurBB); 5380 if (!ParentPad) 5381 return error("Invalid record"); 5382 5383 unsigned NumHandlers = Record[Idx++]; 5384 5385 SmallVector<BasicBlock *, 2> Handlers; 5386 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 5387 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5388 if (!BB) 5389 return error("Invalid record"); 5390 Handlers.push_back(BB); 5391 } 5392 5393 BasicBlock *UnwindDest = nullptr; 5394 if (Idx + 1 == Record.size()) { 5395 UnwindDest = getBasicBlock(Record[Idx++]); 5396 if (!UnwindDest) 5397 return error("Invalid record"); 5398 } 5399 5400 if (Record.size() != Idx) 5401 return error("Invalid record"); 5402 5403 auto *CatchSwitch = 5404 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 5405 for (BasicBlock *Handler : Handlers) 5406 CatchSwitch->addHandler(Handler); 5407 I = CatchSwitch; 5408 ResTypeID = getVirtualTypeID(I->getType()); 5409 InstructionList.push_back(I); 5410 break; 5411 } 5412 case bitc::FUNC_CODE_INST_CATCHPAD: 5413 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 5414 // We must have, at minimum, the outer scope and the number of arguments. 5415 if (Record.size() < 2) 5416 return error("Invalid record"); 5417 5418 unsigned Idx = 0; 5419 5420 Type *TokenTy = Type::getTokenTy(Context); 5421 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy, 5422 getVirtualTypeID(TokenTy), CurBB); 5423 if (!ParentPad) 5424 return error("Invald record"); 5425 5426 unsigned NumArgOperands = Record[Idx++]; 5427 5428 SmallVector<Value *, 2> Args; 5429 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 5430 Value *Val; 5431 unsigned ValTypeID; 5432 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr)) 5433 return error("Invalid record"); 5434 Args.push_back(Val); 5435 } 5436 5437 if (Record.size() != Idx) 5438 return error("Invalid record"); 5439 5440 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 5441 I = CleanupPadInst::Create(ParentPad, Args); 5442 else 5443 I = CatchPadInst::Create(ParentPad, Args); 5444 ResTypeID = getVirtualTypeID(I->getType()); 5445 InstructionList.push_back(I); 5446 break; 5447 } 5448 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 5449 // Check magic 5450 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 5451 // "New" SwitchInst format with case ranges. The changes to write this 5452 // format were reverted but we still recognize bitcode that uses it. 5453 // Hopefully someday we will have support for case ranges and can use 5454 // this format again. 5455 5456 unsigned OpTyID = Record[1]; 5457 Type *OpTy = getTypeByID(OpTyID); 5458 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 5459 5460 Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB); 5461 BasicBlock *Default = getBasicBlock(Record[3]); 5462 if (!OpTy || !Cond || !Default) 5463 return error("Invalid record"); 5464 5465 unsigned NumCases = Record[4]; 5466 5467 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5468 InstructionList.push_back(SI); 5469 5470 unsigned CurIdx = 5; 5471 for (unsigned i = 0; i != NumCases; ++i) { 5472 SmallVector<ConstantInt*, 1> CaseVals; 5473 unsigned NumItems = Record[CurIdx++]; 5474 for (unsigned ci = 0; ci != NumItems; ++ci) { 5475 bool isSingleNumber = Record[CurIdx++]; 5476 5477 APInt Low; 5478 unsigned ActiveWords = 1; 5479 if (ValueBitWidth > 64) 5480 ActiveWords = Record[CurIdx++]; 5481 Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5482 ValueBitWidth); 5483 CurIdx += ActiveWords; 5484 5485 if (!isSingleNumber) { 5486 ActiveWords = 1; 5487 if (ValueBitWidth > 64) 5488 ActiveWords = Record[CurIdx++]; 5489 APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords), 5490 ValueBitWidth); 5491 CurIdx += ActiveWords; 5492 5493 // FIXME: It is not clear whether values in the range should be 5494 // compared as signed or unsigned values. The partially 5495 // implemented changes that used this format in the past used 5496 // unsigned comparisons. 5497 for ( ; Low.ule(High); ++Low) 5498 CaseVals.push_back(ConstantInt::get(Context, Low)); 5499 } else 5500 CaseVals.push_back(ConstantInt::get(Context, Low)); 5501 } 5502 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 5503 for (ConstantInt *Cst : CaseVals) 5504 SI->addCase(Cst, DestBB); 5505 } 5506 I = SI; 5507 break; 5508 } 5509 5510 // Old SwitchInst format without case ranges. 5511 5512 if (Record.size() < 3 || (Record.size() & 1) == 0) 5513 return error("Invalid record"); 5514 unsigned OpTyID = Record[0]; 5515 Type *OpTy = getTypeByID(OpTyID); 5516 Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 5517 BasicBlock *Default = getBasicBlock(Record[2]); 5518 if (!OpTy || !Cond || !Default) 5519 return error("Invalid record"); 5520 unsigned NumCases = (Record.size()-3)/2; 5521 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5522 InstructionList.push_back(SI); 5523 for (unsigned i = 0, e = NumCases; i != e; ++i) { 5524 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>( 5525 getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr)); 5526 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 5527 if (!CaseVal || !DestBB) { 5528 delete SI; 5529 return error("Invalid record"); 5530 } 5531 SI->addCase(CaseVal, DestBB); 5532 } 5533 I = SI; 5534 break; 5535 } 5536 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 5537 if (Record.size() < 2) 5538 return error("Invalid record"); 5539 unsigned OpTyID = Record[0]; 5540 Type *OpTy = getTypeByID(OpTyID); 5541 Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 5542 if (!OpTy || !Address) 5543 return error("Invalid record"); 5544 unsigned NumDests = Record.size()-2; 5545 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 5546 InstructionList.push_back(IBI); 5547 for (unsigned i = 0, e = NumDests; i != e; ++i) { 5548 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 5549 IBI->addDestination(DestBB); 5550 } else { 5551 delete IBI; 5552 return error("Invalid record"); 5553 } 5554 } 5555 I = IBI; 5556 break; 5557 } 5558 5559 case bitc::FUNC_CODE_INST_INVOKE: { 5560 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 5561 if (Record.size() < 4) 5562 return error("Invalid record"); 5563 unsigned OpNum = 0; 5564 AttributeList PAL = getAttributes(Record[OpNum++]); 5565 unsigned CCInfo = Record[OpNum++]; 5566 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 5567 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 5568 5569 unsigned FTyID = InvalidTypeID; 5570 FunctionType *FTy = nullptr; 5571 if ((CCInfo >> 13) & 1) { 5572 FTyID = Record[OpNum++]; 5573 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID)); 5574 if (!FTy) 5575 return error("Explicit invoke type is not a function type"); 5576 } 5577 5578 Value *Callee; 5579 unsigned CalleeTypeID; 5580 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 5581 CurBB)) 5582 return error("Invalid record"); 5583 5584 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 5585 if (!CalleeTy) 5586 return error("Callee is not a pointer"); 5587 if (!FTy) { 5588 FTyID = getContainedTypeID(CalleeTypeID); 5589 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5590 if (!FTy) 5591 return error("Callee is not of pointer to function type"); 5592 } 5593 if (Record.size() < FTy->getNumParams() + OpNum) 5594 return error("Insufficient operands to call"); 5595 5596 SmallVector<Value*, 16> Ops; 5597 SmallVector<unsigned, 16> ArgTyIDs; 5598 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5599 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 5600 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 5601 ArgTyID, CurBB)); 5602 ArgTyIDs.push_back(ArgTyID); 5603 if (!Ops.back()) 5604 return error("Invalid record"); 5605 } 5606 5607 if (!FTy->isVarArg()) { 5608 if (Record.size() != OpNum) 5609 return error("Invalid record"); 5610 } else { 5611 // Read type/value pairs for varargs params. 5612 while (OpNum != Record.size()) { 5613 Value *Op; 5614 unsigned OpTypeID; 5615 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5616 return error("Invalid record"); 5617 Ops.push_back(Op); 5618 ArgTyIDs.push_back(OpTypeID); 5619 } 5620 } 5621 5622 // Upgrade the bundles if needed. 5623 if (!OperandBundles.empty()) 5624 UpgradeOperandBundles(OperandBundles); 5625 5626 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops, 5627 OperandBundles); 5628 ResTypeID = getContainedTypeID(FTyID); 5629 OperandBundles.clear(); 5630 InstructionList.push_back(I); 5631 cast<InvokeInst>(I)->setCallingConv( 5632 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 5633 cast<InvokeInst>(I)->setAttributes(PAL); 5634 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 5635 I->deleteValue(); 5636 return Err; 5637 } 5638 5639 break; 5640 } 5641 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 5642 unsigned Idx = 0; 5643 Value *Val = nullptr; 5644 unsigned ValTypeID; 5645 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB)) 5646 return error("Invalid record"); 5647 I = ResumeInst::Create(Val); 5648 InstructionList.push_back(I); 5649 break; 5650 } 5651 case bitc::FUNC_CODE_INST_CALLBR: { 5652 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args] 5653 unsigned OpNum = 0; 5654 AttributeList PAL = getAttributes(Record[OpNum++]); 5655 unsigned CCInfo = Record[OpNum++]; 5656 5657 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]); 5658 unsigned NumIndirectDests = Record[OpNum++]; 5659 SmallVector<BasicBlock *, 16> IndirectDests; 5660 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i) 5661 IndirectDests.push_back(getBasicBlock(Record[OpNum++])); 5662 5663 unsigned FTyID = InvalidTypeID; 5664 FunctionType *FTy = nullptr; 5665 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 5666 FTyID = Record[OpNum++]; 5667 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5668 if (!FTy) 5669 return error("Explicit call type is not a function type"); 5670 } 5671 5672 Value *Callee; 5673 unsigned CalleeTypeID; 5674 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 5675 CurBB)) 5676 return error("Invalid record"); 5677 5678 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5679 if (!OpTy) 5680 return error("Callee is not a pointer type"); 5681 if (!FTy) { 5682 FTyID = getContainedTypeID(CalleeTypeID); 5683 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 5684 if (!FTy) 5685 return error("Callee is not of pointer to function type"); 5686 } 5687 if (Record.size() < FTy->getNumParams() + OpNum) 5688 return error("Insufficient operands to call"); 5689 5690 SmallVector<Value*, 16> Args; 5691 SmallVector<unsigned, 16> ArgTyIDs; 5692 // Read the fixed params. 5693 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5694 Value *Arg; 5695 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 5696 if (FTy->getParamType(i)->isLabelTy()) 5697 Arg = getBasicBlock(Record[OpNum]); 5698 else 5699 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i), 5700 ArgTyID, CurBB); 5701 if (!Arg) 5702 return error("Invalid record"); 5703 Args.push_back(Arg); 5704 ArgTyIDs.push_back(ArgTyID); 5705 } 5706 5707 // Read type/value pairs for varargs params. 5708 if (!FTy->isVarArg()) { 5709 if (OpNum != Record.size()) 5710 return error("Invalid record"); 5711 } else { 5712 while (OpNum != Record.size()) { 5713 Value *Op; 5714 unsigned OpTypeID; 5715 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 5716 return error("Invalid record"); 5717 Args.push_back(Op); 5718 ArgTyIDs.push_back(OpTypeID); 5719 } 5720 } 5721 5722 // Upgrade the bundles if needed. 5723 if (!OperandBundles.empty()) 5724 UpgradeOperandBundles(OperandBundles); 5725 5726 if (auto *IA = dyn_cast<InlineAsm>(Callee)) { 5727 InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints(); 5728 auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) { 5729 return CI.Type == InlineAsm::isLabel; 5730 }; 5731 if (none_of(ConstraintInfo, IsLabelConstraint)) { 5732 // Upgrade explicit blockaddress arguments to label constraints. 5733 // Verify that the last arguments are blockaddress arguments that 5734 // match the indirect destinations. Clang always generates callbr 5735 // in this form. We could support reordering with more effort. 5736 unsigned FirstBlockArg = Args.size() - IndirectDests.size(); 5737 for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) { 5738 unsigned LabelNo = ArgNo - FirstBlockArg; 5739 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]); 5740 if (!BA || BA->getFunction() != F || 5741 LabelNo > IndirectDests.size() || 5742 BA->getBasicBlock() != IndirectDests[LabelNo]) 5743 return error("callbr argument does not match indirect dest"); 5744 } 5745 5746 // Remove blockaddress arguments. 5747 Args.erase(Args.begin() + FirstBlockArg, Args.end()); 5748 ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end()); 5749 5750 // Recreate the function type with less arguments. 5751 SmallVector<Type *> ArgTys; 5752 for (Value *Arg : Args) 5753 ArgTys.push_back(Arg->getType()); 5754 FTy = 5755 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg()); 5756 5757 // Update constraint string to use label constraints. 5758 std::string Constraints = IA->getConstraintString(); 5759 unsigned ArgNo = 0; 5760 size_t Pos = 0; 5761 for (const auto &CI : ConstraintInfo) { 5762 if (CI.hasArg()) { 5763 if (ArgNo >= FirstBlockArg) 5764 Constraints.insert(Pos, "!"); 5765 ++ArgNo; 5766 } 5767 5768 // Go to next constraint in string. 5769 Pos = Constraints.find(',', Pos); 5770 if (Pos == std::string::npos) 5771 break; 5772 ++Pos; 5773 } 5774 5775 Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints, 5776 IA->hasSideEffects(), IA->isAlignStack(), 5777 IA->getDialect(), IA->canThrow()); 5778 } 5779 } 5780 5781 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args, 5782 OperandBundles); 5783 ResTypeID = getContainedTypeID(FTyID); 5784 OperandBundles.clear(); 5785 InstructionList.push_back(I); 5786 cast<CallBrInst>(I)->setCallingConv( 5787 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5788 cast<CallBrInst>(I)->setAttributes(PAL); 5789 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 5790 I->deleteValue(); 5791 return Err; 5792 } 5793 break; 5794 } 5795 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 5796 I = new UnreachableInst(Context); 5797 InstructionList.push_back(I); 5798 break; 5799 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5800 if (Record.empty()) 5801 return error("Invalid phi record"); 5802 // The first record specifies the type. 5803 unsigned TyID = Record[0]; 5804 Type *Ty = getTypeByID(TyID); 5805 if (!Ty) 5806 return error("Invalid phi record"); 5807 5808 // Phi arguments are pairs of records of [value, basic block]. 5809 // There is an optional final record for fast-math-flags if this phi has a 5810 // floating-point type. 5811 size_t NumArgs = (Record.size() - 1) / 2; 5812 PHINode *PN = PHINode::Create(Ty, NumArgs); 5813 if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) { 5814 PN->deleteValue(); 5815 return error("Invalid phi record"); 5816 } 5817 InstructionList.push_back(PN); 5818 5819 SmallDenseMap<BasicBlock *, Value *> Args; 5820 for (unsigned i = 0; i != NumArgs; i++) { 5821 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]); 5822 if (!BB) { 5823 PN->deleteValue(); 5824 return error("Invalid phi BB"); 5825 } 5826 5827 // Phi nodes may contain the same predecessor multiple times, in which 5828 // case the incoming value must be identical. Directly reuse the already 5829 // seen value here, to avoid expanding a constant expression multiple 5830 // times. 5831 auto It = Args.find(BB); 5832 if (It != Args.end()) { 5833 PN->addIncoming(It->second, BB); 5834 continue; 5835 } 5836 5837 // If there already is a block for this edge (from a different phi), 5838 // use it. 5839 BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB}); 5840 if (!EdgeBB) { 5841 // Otherwise, use a temporary block (that we will discard if it 5842 // turns out to be unnecessary). 5843 if (!PhiConstExprBB) 5844 PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F); 5845 EdgeBB = PhiConstExprBB; 5846 } 5847 5848 // With the new function encoding, it is possible that operands have 5849 // negative IDs (for forward references). Use a signed VBR 5850 // representation to keep the encoding small. 5851 Value *V; 5852 if (UseRelativeIDs) 5853 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 5854 else 5855 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB); 5856 if (!V) { 5857 PN->deleteValue(); 5858 PhiConstExprBB->eraseFromParent(); 5859 return error("Invalid phi record"); 5860 } 5861 5862 if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) { 5863 ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB}); 5864 PhiConstExprBB = nullptr; 5865 } 5866 PN->addIncoming(V, BB); 5867 Args.insert({BB, V}); 5868 } 5869 I = PN; 5870 ResTypeID = TyID; 5871 5872 // If there are an even number of records, the final record must be FMF. 5873 if (Record.size() % 2 == 0) { 5874 assert(isa<FPMathOperator>(I) && "Unexpected phi type"); 5875 FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]); 5876 if (FMF.any()) 5877 I->setFastMathFlags(FMF); 5878 } 5879 5880 break; 5881 } 5882 5883 case bitc::FUNC_CODE_INST_LANDINGPAD: 5884 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 5885 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 5886 unsigned Idx = 0; 5887 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 5888 if (Record.size() < 3) 5889 return error("Invalid record"); 5890 } else { 5891 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 5892 if (Record.size() < 4) 5893 return error("Invalid record"); 5894 } 5895 ResTypeID = Record[Idx++]; 5896 Type *Ty = getTypeByID(ResTypeID); 5897 if (!Ty) 5898 return error("Invalid record"); 5899 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 5900 Value *PersFn = nullptr; 5901 unsigned PersFnTypeID; 5902 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID, 5903 nullptr)) 5904 return error("Invalid record"); 5905 5906 if (!F->hasPersonalityFn()) 5907 F->setPersonalityFn(cast<Constant>(PersFn)); 5908 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 5909 return error("Personality function mismatch"); 5910 } 5911 5912 bool IsCleanup = !!Record[Idx++]; 5913 unsigned NumClauses = Record[Idx++]; 5914 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 5915 LP->setCleanup(IsCleanup); 5916 for (unsigned J = 0; J != NumClauses; ++J) { 5917 LandingPadInst::ClauseType CT = 5918 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 5919 Value *Val; 5920 unsigned ValTypeID; 5921 5922 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, 5923 nullptr)) { 5924 delete LP; 5925 return error("Invalid record"); 5926 } 5927 5928 assert((CT != LandingPadInst::Catch || 5929 !isa<ArrayType>(Val->getType())) && 5930 "Catch clause has a invalid type!"); 5931 assert((CT != LandingPadInst::Filter || 5932 isa<ArrayType>(Val->getType())) && 5933 "Filter clause has invalid type!"); 5934 LP->addClause(cast<Constant>(Val)); 5935 } 5936 5937 I = LP; 5938 InstructionList.push_back(I); 5939 break; 5940 } 5941 5942 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 5943 if (Record.size() != 4 && Record.size() != 5) 5944 return error("Invalid record"); 5945 using APV = AllocaPackedValues; 5946 const uint64_t Rec = Record[3]; 5947 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec); 5948 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec); 5949 unsigned TyID = Record[0]; 5950 Type *Ty = getTypeByID(TyID); 5951 if (!Bitfield::get<APV::ExplicitType>(Rec)) { 5952 TyID = getContainedTypeID(TyID); 5953 Ty = getTypeByID(TyID); 5954 if (!Ty) 5955 return error("Missing element type for old-style alloca"); 5956 } 5957 unsigned OpTyID = Record[1]; 5958 Type *OpTy = getTypeByID(OpTyID); 5959 Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB); 5960 MaybeAlign Align; 5961 uint64_t AlignExp = 5962 Bitfield::get<APV::AlignLower>(Rec) | 5963 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); 5964 if (Error Err = parseAlignmentValue(AlignExp, Align)) { 5965 return Err; 5966 } 5967 if (!Ty || !Size) 5968 return error("Invalid record"); 5969 5970 const DataLayout &DL = TheModule->getDataLayout(); 5971 unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace(); 5972 5973 SmallPtrSet<Type *, 4> Visited; 5974 if (!Align && !Ty->isSized(&Visited)) 5975 return error("alloca of unsized type"); 5976 if (!Align) 5977 Align = DL.getPrefTypeAlign(Ty); 5978 5979 if (!Size->getType()->isIntegerTy()) 5980 return error("alloca element count must have integer type"); 5981 5982 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 5983 AI->setUsedWithInAlloca(InAlloca); 5984 AI->setSwiftError(SwiftError); 5985 I = AI; 5986 ResTypeID = getVirtualTypeID(AI->getType(), TyID); 5987 InstructionList.push_back(I); 5988 break; 5989 } 5990 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 5991 unsigned OpNum = 0; 5992 Value *Op; 5993 unsigned OpTypeID; 5994 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 5995 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 5996 return error("Invalid record"); 5997 5998 if (!isa<PointerType>(Op->getType())) 5999 return error("Load operand is not a pointer type"); 6000 6001 Type *Ty = nullptr; 6002 if (OpNum + 3 == Record.size()) { 6003 ResTypeID = Record[OpNum++]; 6004 Ty = getTypeByID(ResTypeID); 6005 } else { 6006 ResTypeID = getContainedTypeID(OpTypeID); 6007 Ty = getTypeByID(ResTypeID); 6008 } 6009 6010 if (!Ty) 6011 return error("Missing load type"); 6012 6013 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 6014 return Err; 6015 6016 MaybeAlign Align; 6017 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6018 return Err; 6019 SmallPtrSet<Type *, 4> Visited; 6020 if (!Align && !Ty->isSized(&Visited)) 6021 return error("load of unsized type"); 6022 if (!Align) 6023 Align = TheModule->getDataLayout().getABITypeAlign(Ty); 6024 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 6025 InstructionList.push_back(I); 6026 break; 6027 } 6028 case bitc::FUNC_CODE_INST_LOADATOMIC: { 6029 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 6030 unsigned OpNum = 0; 6031 Value *Op; 6032 unsigned OpTypeID; 6033 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) || 6034 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 6035 return error("Invalid record"); 6036 6037 if (!isa<PointerType>(Op->getType())) 6038 return error("Load operand is not a pointer type"); 6039 6040 Type *Ty = nullptr; 6041 if (OpNum + 5 == Record.size()) { 6042 ResTypeID = Record[OpNum++]; 6043 Ty = getTypeByID(ResTypeID); 6044 } else { 6045 ResTypeID = getContainedTypeID(OpTypeID); 6046 Ty = getTypeByID(ResTypeID); 6047 } 6048 6049 if (!Ty) 6050 return error("Missing atomic load type"); 6051 6052 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 6053 return Err; 6054 6055 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6056 if (Ordering == AtomicOrdering::NotAtomic || 6057 Ordering == AtomicOrdering::Release || 6058 Ordering == AtomicOrdering::AcquireRelease) 6059 return error("Invalid record"); 6060 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 6061 return error("Invalid record"); 6062 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6063 6064 MaybeAlign Align; 6065 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6066 return Err; 6067 if (!Align) 6068 return error("Alignment missing from atomic load"); 6069 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 6070 InstructionList.push_back(I); 6071 break; 6072 } 6073 case bitc::FUNC_CODE_INST_STORE: 6074 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 6075 unsigned OpNum = 0; 6076 Value *Val, *Ptr; 6077 unsigned PtrTypeID, ValTypeID; 6078 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6079 return error("Invalid record"); 6080 6081 if (BitCode == bitc::FUNC_CODE_INST_STORE) { 6082 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6083 return error("Invalid record"); 6084 } else { 6085 ValTypeID = getContainedTypeID(PtrTypeID); 6086 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 6087 ValTypeID, Val, CurBB)) 6088 return error("Invalid record"); 6089 } 6090 6091 if (OpNum + 2 != Record.size()) 6092 return error("Invalid record"); 6093 6094 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 6095 return Err; 6096 MaybeAlign Align; 6097 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6098 return Err; 6099 SmallPtrSet<Type *, 4> Visited; 6100 if (!Align && !Val->getType()->isSized(&Visited)) 6101 return error("store of unsized type"); 6102 if (!Align) 6103 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 6104 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 6105 InstructionList.push_back(I); 6106 break; 6107 } 6108 case bitc::FUNC_CODE_INST_STOREATOMIC: 6109 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 6110 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 6111 unsigned OpNum = 0; 6112 Value *Val, *Ptr; 6113 unsigned PtrTypeID, ValTypeID; 6114 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) || 6115 !isa<PointerType>(Ptr->getType())) 6116 return error("Invalid record"); 6117 if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) { 6118 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6119 return error("Invalid record"); 6120 } else { 6121 ValTypeID = getContainedTypeID(PtrTypeID); 6122 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID), 6123 ValTypeID, Val, CurBB)) 6124 return error("Invalid record"); 6125 } 6126 6127 if (OpNum + 4 != Record.size()) 6128 return error("Invalid record"); 6129 6130 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 6131 return Err; 6132 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6133 if (Ordering == AtomicOrdering::NotAtomic || 6134 Ordering == AtomicOrdering::Acquire || 6135 Ordering == AtomicOrdering::AcquireRelease) 6136 return error("Invalid record"); 6137 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6138 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 6139 return error("Invalid record"); 6140 6141 MaybeAlign Align; 6142 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 6143 return Err; 6144 if (!Align) 6145 return error("Alignment missing from atomic store"); 6146 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 6147 InstructionList.push_back(I); 6148 break; 6149 } 6150 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 6151 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 6152 // failure_ordering?, weak?] 6153 const size_t NumRecords = Record.size(); 6154 unsigned OpNum = 0; 6155 Value *Ptr = nullptr; 6156 unsigned PtrTypeID; 6157 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6158 return error("Invalid record"); 6159 6160 if (!isa<PointerType>(Ptr->getType())) 6161 return error("Cmpxchg operand is not a pointer type"); 6162 6163 Value *Cmp = nullptr; 6164 unsigned CmpTypeID = getContainedTypeID(PtrTypeID); 6165 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID), 6166 CmpTypeID, Cmp, CurBB)) 6167 return error("Invalid record"); 6168 6169 Value *New = nullptr; 6170 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, 6171 New, CurBB) || 6172 NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 6173 return error("Invalid record"); 6174 6175 const AtomicOrdering SuccessOrdering = 6176 getDecodedOrdering(Record[OpNum + 1]); 6177 if (SuccessOrdering == AtomicOrdering::NotAtomic || 6178 SuccessOrdering == AtomicOrdering::Unordered) 6179 return error("Invalid record"); 6180 6181 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6182 6183 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6184 return Err; 6185 6186 const AtomicOrdering FailureOrdering = 6187 NumRecords < 7 6188 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 6189 : getDecodedOrdering(Record[OpNum + 3]); 6190 6191 if (FailureOrdering == AtomicOrdering::NotAtomic || 6192 FailureOrdering == AtomicOrdering::Unordered) 6193 return error("Invalid record"); 6194 6195 const Align Alignment( 6196 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6197 6198 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 6199 FailureOrdering, SSID); 6200 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 6201 6202 if (NumRecords < 8) { 6203 // Before weak cmpxchgs existed, the instruction simply returned the 6204 // value loaded from memory, so bitcode files from that era will be 6205 // expecting the first component of a modern cmpxchg. 6206 I->insertInto(CurBB, CurBB->end()); 6207 I = ExtractValueInst::Create(I, 0); 6208 ResTypeID = CmpTypeID; 6209 } else { 6210 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 6211 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 6212 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 6213 } 6214 6215 InstructionList.push_back(I); 6216 break; 6217 } 6218 case bitc::FUNC_CODE_INST_CMPXCHG: { 6219 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 6220 // failure_ordering, weak, align?] 6221 const size_t NumRecords = Record.size(); 6222 unsigned OpNum = 0; 6223 Value *Ptr = nullptr; 6224 unsigned PtrTypeID; 6225 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6226 return error("Invalid record"); 6227 6228 if (!isa<PointerType>(Ptr->getType())) 6229 return error("Cmpxchg operand is not a pointer type"); 6230 6231 Value *Cmp = nullptr; 6232 unsigned CmpTypeID; 6233 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB)) 6234 return error("Invalid record"); 6235 6236 Value *Val = nullptr; 6237 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val, 6238 CurBB)) 6239 return error("Invalid record"); 6240 6241 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 6242 return error("Invalid record"); 6243 6244 const bool IsVol = Record[OpNum]; 6245 6246 const AtomicOrdering SuccessOrdering = 6247 getDecodedOrdering(Record[OpNum + 1]); 6248 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 6249 return error("Invalid cmpxchg success ordering"); 6250 6251 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 6252 6253 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 6254 return Err; 6255 6256 const AtomicOrdering FailureOrdering = 6257 getDecodedOrdering(Record[OpNum + 3]); 6258 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 6259 return error("Invalid cmpxchg failure ordering"); 6260 6261 const bool IsWeak = Record[OpNum + 4]; 6262 6263 MaybeAlign Alignment; 6264 6265 if (NumRecords == (OpNum + 6)) { 6266 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 6267 return Err; 6268 } 6269 if (!Alignment) 6270 Alignment = 6271 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 6272 6273 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 6274 FailureOrdering, SSID); 6275 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 6276 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 6277 6278 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context)); 6279 ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID}); 6280 6281 InstructionList.push_back(I); 6282 break; 6283 } 6284 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: 6285 case bitc::FUNC_CODE_INST_ATOMICRMW: { 6286 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] 6287 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] 6288 const size_t NumRecords = Record.size(); 6289 unsigned OpNum = 0; 6290 6291 Value *Ptr = nullptr; 6292 unsigned PtrTypeID; 6293 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB)) 6294 return error("Invalid record"); 6295 6296 if (!isa<PointerType>(Ptr->getType())) 6297 return error("Invalid record"); 6298 6299 Value *Val = nullptr; 6300 unsigned ValTypeID = InvalidTypeID; 6301 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { 6302 ValTypeID = getContainedTypeID(PtrTypeID); 6303 if (popValue(Record, OpNum, NextValueNo, 6304 getTypeByID(ValTypeID), ValTypeID, Val, CurBB)) 6305 return error("Invalid record"); 6306 } else { 6307 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB)) 6308 return error("Invalid record"); 6309 } 6310 6311 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 6312 return error("Invalid record"); 6313 6314 const AtomicRMWInst::BinOp Operation = 6315 getDecodedRMWOperation(Record[OpNum]); 6316 if (Operation < AtomicRMWInst::FIRST_BINOP || 6317 Operation > AtomicRMWInst::LAST_BINOP) 6318 return error("Invalid record"); 6319 6320 const bool IsVol = Record[OpNum + 1]; 6321 6322 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 6323 if (Ordering == AtomicOrdering::NotAtomic || 6324 Ordering == AtomicOrdering::Unordered) 6325 return error("Invalid record"); 6326 6327 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 6328 6329 MaybeAlign Alignment; 6330 6331 if (NumRecords == (OpNum + 5)) { 6332 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 6333 return Err; 6334 } 6335 6336 if (!Alignment) 6337 Alignment = 6338 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 6339 6340 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 6341 ResTypeID = ValTypeID; 6342 cast<AtomicRMWInst>(I)->setVolatile(IsVol); 6343 6344 InstructionList.push_back(I); 6345 break; 6346 } 6347 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 6348 if (2 != Record.size()) 6349 return error("Invalid record"); 6350 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 6351 if (Ordering == AtomicOrdering::NotAtomic || 6352 Ordering == AtomicOrdering::Unordered || 6353 Ordering == AtomicOrdering::Monotonic) 6354 return error("Invalid record"); 6355 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 6356 I = new FenceInst(Context, Ordering, SSID); 6357 InstructionList.push_back(I); 6358 break; 6359 } 6360 case bitc::FUNC_CODE_INST_CALL: { 6361 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 6362 if (Record.size() < 3) 6363 return error("Invalid record"); 6364 6365 unsigned OpNum = 0; 6366 AttributeList PAL = getAttributes(Record[OpNum++]); 6367 unsigned CCInfo = Record[OpNum++]; 6368 6369 FastMathFlags FMF; 6370 if ((CCInfo >> bitc::CALL_FMF) & 1) { 6371 FMF = getDecodedFastMathFlags(Record[OpNum++]); 6372 if (!FMF.any()) 6373 return error("Fast math flags indicator set for call with no FMF"); 6374 } 6375 6376 unsigned FTyID = InvalidTypeID; 6377 FunctionType *FTy = nullptr; 6378 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 6379 FTyID = Record[OpNum++]; 6380 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6381 if (!FTy) 6382 return error("Explicit call type is not a function type"); 6383 } 6384 6385 Value *Callee; 6386 unsigned CalleeTypeID; 6387 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID, 6388 CurBB)) 6389 return error("Invalid record"); 6390 6391 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 6392 if (!OpTy) 6393 return error("Callee is not a pointer type"); 6394 if (!FTy) { 6395 FTyID = getContainedTypeID(CalleeTypeID); 6396 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID)); 6397 if (!FTy) 6398 return error("Callee is not of pointer to function type"); 6399 } 6400 if (Record.size() < FTy->getNumParams() + OpNum) 6401 return error("Insufficient operands to call"); 6402 6403 SmallVector<Value*, 16> Args; 6404 SmallVector<unsigned, 16> ArgTyIDs; 6405 // Read the fixed params. 6406 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 6407 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1); 6408 if (FTy->getParamType(i)->isLabelTy()) 6409 Args.push_back(getBasicBlock(Record[OpNum])); 6410 else 6411 Args.push_back(getValue(Record, OpNum, NextValueNo, 6412 FTy->getParamType(i), ArgTyID, CurBB)); 6413 ArgTyIDs.push_back(ArgTyID); 6414 if (!Args.back()) 6415 return error("Invalid record"); 6416 } 6417 6418 // Read type/value pairs for varargs params. 6419 if (!FTy->isVarArg()) { 6420 if (OpNum != Record.size()) 6421 return error("Invalid record"); 6422 } else { 6423 while (OpNum != Record.size()) { 6424 Value *Op; 6425 unsigned OpTypeID; 6426 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6427 return error("Invalid record"); 6428 Args.push_back(Op); 6429 ArgTyIDs.push_back(OpTypeID); 6430 } 6431 } 6432 6433 // Upgrade the bundles if needed. 6434 if (!OperandBundles.empty()) 6435 UpgradeOperandBundles(OperandBundles); 6436 6437 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 6438 ResTypeID = getContainedTypeID(FTyID); 6439 OperandBundles.clear(); 6440 InstructionList.push_back(I); 6441 cast<CallInst>(I)->setCallingConv( 6442 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 6443 CallInst::TailCallKind TCK = CallInst::TCK_None; 6444 if (CCInfo & (1 << bitc::CALL_TAIL)) 6445 TCK = CallInst::TCK_Tail; 6446 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 6447 TCK = CallInst::TCK_MustTail; 6448 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 6449 TCK = CallInst::TCK_NoTail; 6450 cast<CallInst>(I)->setTailCallKind(TCK); 6451 cast<CallInst>(I)->setAttributes(PAL); 6452 if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) { 6453 I->deleteValue(); 6454 return Err; 6455 } 6456 if (FMF.any()) { 6457 if (!isa<FPMathOperator>(I)) 6458 return error("Fast-math-flags specified for call without " 6459 "floating-point scalar or vector return type"); 6460 I->setFastMathFlags(FMF); 6461 } 6462 break; 6463 } 6464 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 6465 if (Record.size() < 3) 6466 return error("Invalid record"); 6467 unsigned OpTyID = Record[0]; 6468 Type *OpTy = getTypeByID(OpTyID); 6469 Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB); 6470 ResTypeID = Record[2]; 6471 Type *ResTy = getTypeByID(ResTypeID); 6472 if (!OpTy || !Op || !ResTy) 6473 return error("Invalid record"); 6474 I = new VAArgInst(Op, ResTy); 6475 InstructionList.push_back(I); 6476 break; 6477 } 6478 6479 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 6480 // A call or an invoke can be optionally prefixed with some variable 6481 // number of operand bundle blocks. These blocks are read into 6482 // OperandBundles and consumed at the next call or invoke instruction. 6483 6484 if (Record.empty() || Record[0] >= BundleTags.size()) 6485 return error("Invalid record"); 6486 6487 std::vector<Value *> Inputs; 6488 6489 unsigned OpNum = 1; 6490 while (OpNum != Record.size()) { 6491 Value *Op; 6492 unsigned OpTypeID; 6493 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6494 return error("Invalid record"); 6495 Inputs.push_back(Op); 6496 } 6497 6498 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 6499 continue; 6500 } 6501 6502 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 6503 unsigned OpNum = 0; 6504 Value *Op = nullptr; 6505 unsigned OpTypeID; 6506 if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB)) 6507 return error("Invalid record"); 6508 if (OpNum != Record.size()) 6509 return error("Invalid record"); 6510 6511 I = new FreezeInst(Op); 6512 ResTypeID = OpTypeID; 6513 InstructionList.push_back(I); 6514 break; 6515 } 6516 } 6517 6518 // Add instruction to end of current BB. If there is no current BB, reject 6519 // this file. 6520 if (!CurBB) { 6521 I->deleteValue(); 6522 return error("Invalid instruction with no BB"); 6523 } 6524 if (!OperandBundles.empty()) { 6525 I->deleteValue(); 6526 return error("Operand bundles found with no consumer"); 6527 } 6528 I->insertInto(CurBB, CurBB->end()); 6529 6530 // If this was a terminator instruction, move to the next block. 6531 if (I->isTerminator()) { 6532 ++CurBBNo; 6533 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 6534 } 6535 6536 // Non-void values get registered in the value table for future use. 6537 if (!I->getType()->isVoidTy()) { 6538 assert(I->getType() == getTypeByID(ResTypeID) && 6539 "Incorrect result type ID"); 6540 if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID)) 6541 return Err; 6542 } 6543 } 6544 6545 OutOfRecordLoop: 6546 6547 if (!OperandBundles.empty()) 6548 return error("Operand bundles found with no consumer"); 6549 6550 // Check the function list for unresolved values. 6551 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 6552 if (!A->getParent()) { 6553 // We found at least one unresolved value. Nuke them all to avoid leaks. 6554 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 6555 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 6556 A->replaceAllUsesWith(PoisonValue::get(A->getType())); 6557 delete A; 6558 } 6559 } 6560 return error("Never resolved value found in function"); 6561 } 6562 } 6563 6564 // Unexpected unresolved metadata about to be dropped. 6565 if (MDLoader->hasFwdRefs()) 6566 return error("Invalid function metadata: outgoing forward refs"); 6567 6568 if (PhiConstExprBB) 6569 PhiConstExprBB->eraseFromParent(); 6570 6571 for (const auto &Pair : ConstExprEdgeBBs) { 6572 BasicBlock *From = Pair.first.first; 6573 BasicBlock *To = Pair.first.second; 6574 BasicBlock *EdgeBB = Pair.second; 6575 BranchInst::Create(To, EdgeBB); 6576 From->getTerminator()->replaceSuccessorWith(To, EdgeBB); 6577 To->replacePhiUsesWith(From, EdgeBB); 6578 EdgeBB->moveBefore(To); 6579 } 6580 6581 // Trim the value list down to the size it was before we parsed this function. 6582 ValueList.shrinkTo(ModuleValueListSize); 6583 MDLoader->shrinkTo(ModuleMDLoaderSize); 6584 std::vector<BasicBlock*>().swap(FunctionBBs); 6585 return Error::success(); 6586 } 6587 6588 /// Find the function body in the bitcode stream 6589 Error BitcodeReader::findFunctionInStream( 6590 Function *F, 6591 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 6592 while (DeferredFunctionInfoIterator->second == 0) { 6593 // This is the fallback handling for the old format bitcode that 6594 // didn't contain the function index in the VST, or when we have 6595 // an anonymous function which would not have a VST entry. 6596 // Assert that we have one of those two cases. 6597 assert(VSTOffset == 0 || !F->hasName()); 6598 // Parse the next body in the stream and set its position in the 6599 // DeferredFunctionInfo map. 6600 if (Error Err = rememberAndSkipFunctionBodies()) 6601 return Err; 6602 } 6603 return Error::success(); 6604 } 6605 6606 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 6607 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 6608 return SyncScope::ID(Val); 6609 if (Val >= SSIDs.size()) 6610 return SyncScope::System; // Map unknown synchronization scopes to system. 6611 return SSIDs[Val]; 6612 } 6613 6614 //===----------------------------------------------------------------------===// 6615 // GVMaterializer implementation 6616 //===----------------------------------------------------------------------===// 6617 6618 Error BitcodeReader::materialize(GlobalValue *GV) { 6619 Function *F = dyn_cast<Function>(GV); 6620 // If it's not a function or is already material, ignore the request. 6621 if (!F || !F->isMaterializable()) 6622 return Error::success(); 6623 6624 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 6625 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 6626 // If its position is recorded as 0, its body is somewhere in the stream 6627 // but we haven't seen it yet. 6628 if (DFII->second == 0) 6629 if (Error Err = findFunctionInStream(F, DFII)) 6630 return Err; 6631 6632 // Materialize metadata before parsing any function bodies. 6633 if (Error Err = materializeMetadata()) 6634 return Err; 6635 6636 // Move the bit stream to the saved position of the deferred function body. 6637 if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 6638 return JumpFailed; 6639 if (Error Err = parseFunctionBody(F)) 6640 return Err; 6641 F->setIsMaterializable(false); 6642 6643 if (StripDebugInfo) 6644 stripDebugInfo(*F); 6645 6646 // Upgrade any old intrinsic calls in the function. 6647 for (auto &I : UpgradedIntrinsics) { 6648 for (User *U : llvm::make_early_inc_range(I.first->materialized_users())) 6649 if (CallInst *CI = dyn_cast<CallInst>(U)) 6650 UpgradeIntrinsicCall(CI, I.second); 6651 } 6652 6653 // Finish fn->subprogram upgrade for materialized functions. 6654 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 6655 F->setSubprogram(SP); 6656 6657 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 6658 if (!MDLoader->isStrippingTBAA()) { 6659 for (auto &I : instructions(F)) { 6660 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 6661 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 6662 continue; 6663 MDLoader->setStripTBAA(true); 6664 stripTBAA(F->getParent()); 6665 } 6666 } 6667 6668 for (auto &I : instructions(F)) { 6669 // "Upgrade" older incorrect branch weights by dropping them. 6670 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 6671 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 6672 MDString *MDS = cast<MDString>(MD->getOperand(0)); 6673 StringRef ProfName = MDS->getString(); 6674 // Check consistency of !prof branch_weights metadata. 6675 if (!ProfName.equals("branch_weights")) 6676 continue; 6677 unsigned ExpectedNumOperands = 0; 6678 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 6679 ExpectedNumOperands = BI->getNumSuccessors(); 6680 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 6681 ExpectedNumOperands = SI->getNumSuccessors(); 6682 else if (isa<CallInst>(&I)) 6683 ExpectedNumOperands = 1; 6684 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 6685 ExpectedNumOperands = IBI->getNumDestinations(); 6686 else if (isa<SelectInst>(&I)) 6687 ExpectedNumOperands = 2; 6688 else 6689 continue; // ignore and continue. 6690 6691 // If branch weight doesn't match, just strip branch weight. 6692 if (MD->getNumOperands() != 1 + ExpectedNumOperands) 6693 I.setMetadata(LLVMContext::MD_prof, nullptr); 6694 } 6695 } 6696 6697 // Remove incompatible attributes on function calls. 6698 if (auto *CI = dyn_cast<CallBase>(&I)) { 6699 CI->removeRetAttrs(AttributeFuncs::typeIncompatible( 6700 CI->getFunctionType()->getReturnType())); 6701 6702 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) 6703 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( 6704 CI->getArgOperand(ArgNo)->getType())); 6705 } 6706 } 6707 6708 // Look for functions that rely on old function attribute behavior. 6709 UpgradeFunctionAttributes(*F); 6710 6711 // Bring in any functions that this function forward-referenced via 6712 // blockaddresses. 6713 return materializeForwardReferencedFunctions(); 6714 } 6715 6716 Error BitcodeReader::materializeModule() { 6717 if (Error Err = materializeMetadata()) 6718 return Err; 6719 6720 // Promise to materialize all forward references. 6721 WillMaterializeAllForwardRefs = true; 6722 6723 // Iterate over the module, deserializing any functions that are still on 6724 // disk. 6725 for (Function &F : *TheModule) { 6726 if (Error Err = materialize(&F)) 6727 return Err; 6728 } 6729 // At this point, if there are any function bodies, parse the rest of 6730 // the bits in the module past the last function block we have recorded 6731 // through either lazy scanning or the VST. 6732 if (LastFunctionBlockBit || NextUnreadBit) 6733 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 6734 ? LastFunctionBlockBit 6735 : NextUnreadBit)) 6736 return Err; 6737 6738 // Check that all block address forward references got resolved (as we 6739 // promised above). 6740 if (!BasicBlockFwdRefs.empty()) 6741 return error("Never resolved function from blockaddress"); 6742 6743 // Upgrade any intrinsic calls that slipped through (should not happen!) and 6744 // delete the old functions to clean up. We can't do this unless the entire 6745 // module is materialized because there could always be another function body 6746 // with calls to the old function. 6747 for (auto &I : UpgradedIntrinsics) { 6748 for (auto *U : I.first->users()) { 6749 if (CallInst *CI = dyn_cast<CallInst>(U)) 6750 UpgradeIntrinsicCall(CI, I.second); 6751 } 6752 if (!I.first->use_empty()) 6753 I.first->replaceAllUsesWith(I.second); 6754 I.first->eraseFromParent(); 6755 } 6756 UpgradedIntrinsics.clear(); 6757 6758 UpgradeDebugInfo(*TheModule); 6759 6760 UpgradeModuleFlags(*TheModule); 6761 6762 UpgradeARCRuntime(*TheModule); 6763 6764 return Error::success(); 6765 } 6766 6767 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 6768 return IdentifiedStructTypes; 6769 } 6770 6771 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 6772 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 6773 StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing) 6774 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 6775 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {} 6776 6777 void ModuleSummaryIndexBitcodeReader::addThisModule() { 6778 TheIndex.addModule(ModulePath); 6779 } 6780 6781 ModuleSummaryIndex::ModuleInfo * 6782 ModuleSummaryIndexBitcodeReader::getThisModule() { 6783 return TheIndex.getModule(ModulePath); 6784 } 6785 6786 template <bool AllowNullValueInfo> 6787 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID> 6788 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 6789 auto VGI = ValueIdToValueInfoMap[ValueId]; 6790 // We can have a null value info for memprof callsite info records in 6791 // distributed ThinLTO index files when the callee function summary is not 6792 // included in the index. The bitcode writer records 0 in that case, 6793 // and the caller of this helper will set AllowNullValueInfo to true. 6794 assert(AllowNullValueInfo || std::get<0>(VGI)); 6795 return VGI; 6796 } 6797 6798 void ModuleSummaryIndexBitcodeReader::setValueGUID( 6799 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 6800 StringRef SourceFileName) { 6801 std::string GlobalId = 6802 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 6803 auto ValueGUID = GlobalValue::getGUID(GlobalId); 6804 auto OriginalNameID = ValueGUID; 6805 if (GlobalValue::isLocalLinkage(Linkage)) 6806 OriginalNameID = GlobalValue::getGUID(ValueName); 6807 if (PrintSummaryGUIDs) 6808 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 6809 << ValueName << "\n"; 6810 6811 // UseStrtab is false for legacy summary formats and value names are 6812 // created on stack. In that case we save the name in a string saver in 6813 // the index so that the value name can be recorded. 6814 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6815 TheIndex.getOrInsertValueInfo( 6816 ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 6817 OriginalNameID, ValueGUID); 6818 } 6819 6820 // Specialized value symbol table parser used when reading module index 6821 // blocks where we don't actually create global values. The parsed information 6822 // is saved in the bitcode reader for use when later parsing summaries. 6823 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 6824 uint64_t Offset, 6825 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 6826 // With a strtab the VST is not required to parse the summary. 6827 if (UseStrtab) 6828 return Error::success(); 6829 6830 assert(Offset > 0 && "Expected non-zero VST offset"); 6831 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 6832 if (!MaybeCurrentBit) 6833 return MaybeCurrentBit.takeError(); 6834 uint64_t CurrentBit = MaybeCurrentBit.get(); 6835 6836 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 6837 return Err; 6838 6839 SmallVector<uint64_t, 64> Record; 6840 6841 // Read all the records for this value table. 6842 SmallString<128> ValueName; 6843 6844 while (true) { 6845 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6846 if (!MaybeEntry) 6847 return MaybeEntry.takeError(); 6848 BitstreamEntry Entry = MaybeEntry.get(); 6849 6850 switch (Entry.Kind) { 6851 case BitstreamEntry::SubBlock: // Handled for us already. 6852 case BitstreamEntry::Error: 6853 return error("Malformed block"); 6854 case BitstreamEntry::EndBlock: 6855 // Done parsing VST, jump back to wherever we came from. 6856 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 6857 return JumpFailed; 6858 return Error::success(); 6859 case BitstreamEntry::Record: 6860 // The interesting case. 6861 break; 6862 } 6863 6864 // Read a record. 6865 Record.clear(); 6866 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6867 if (!MaybeRecord) 6868 return MaybeRecord.takeError(); 6869 switch (MaybeRecord.get()) { 6870 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 6871 break; 6872 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 6873 if (convertToString(Record, 1, ValueName)) 6874 return error("Invalid record"); 6875 unsigned ValueID = Record[0]; 6876 assert(!SourceFileName.empty()); 6877 auto VLI = ValueIdToLinkageMap.find(ValueID); 6878 assert(VLI != ValueIdToLinkageMap.end() && 6879 "No linkage found for VST entry?"); 6880 auto Linkage = VLI->second; 6881 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 6882 ValueName.clear(); 6883 break; 6884 } 6885 case bitc::VST_CODE_FNENTRY: { 6886 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 6887 if (convertToString(Record, 2, ValueName)) 6888 return error("Invalid record"); 6889 unsigned ValueID = Record[0]; 6890 assert(!SourceFileName.empty()); 6891 auto VLI = ValueIdToLinkageMap.find(ValueID); 6892 assert(VLI != ValueIdToLinkageMap.end() && 6893 "No linkage found for VST entry?"); 6894 auto Linkage = VLI->second; 6895 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 6896 ValueName.clear(); 6897 break; 6898 } 6899 case bitc::VST_CODE_COMBINED_ENTRY: { 6900 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 6901 unsigned ValueID = Record[0]; 6902 GlobalValue::GUID RefGUID = Record[1]; 6903 // The "original name", which is the second value of the pair will be 6904 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 6905 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 6906 TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 6907 break; 6908 } 6909 } 6910 } 6911 } 6912 6913 // Parse just the blocks needed for building the index out of the module. 6914 // At the end of this routine the module Index is populated with a map 6915 // from global value id to GlobalValueSummary objects. 6916 Error ModuleSummaryIndexBitcodeReader::parseModule() { 6917 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6918 return Err; 6919 6920 SmallVector<uint64_t, 64> Record; 6921 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 6922 unsigned ValueId = 0; 6923 6924 // Read the index for this module. 6925 while (true) { 6926 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6927 if (!MaybeEntry) 6928 return MaybeEntry.takeError(); 6929 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6930 6931 switch (Entry.Kind) { 6932 case BitstreamEntry::Error: 6933 return error("Malformed block"); 6934 case BitstreamEntry::EndBlock: 6935 return Error::success(); 6936 6937 case BitstreamEntry::SubBlock: 6938 switch (Entry.ID) { 6939 default: // Skip unknown content. 6940 if (Error Err = Stream.SkipBlock()) 6941 return Err; 6942 break; 6943 case bitc::BLOCKINFO_BLOCK_ID: 6944 // Need to parse these to get abbrev ids (e.g. for VST) 6945 if (Error Err = readBlockInfo()) 6946 return Err; 6947 break; 6948 case bitc::VALUE_SYMTAB_BLOCK_ID: 6949 // Should have been parsed earlier via VSTOffset, unless there 6950 // is no summary section. 6951 assert(((SeenValueSymbolTable && VSTOffset > 0) || 6952 !SeenGlobalValSummary) && 6953 "Expected early VST parse via VSTOffset record"); 6954 if (Error Err = Stream.SkipBlock()) 6955 return Err; 6956 break; 6957 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 6958 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 6959 // Add the module if it is a per-module index (has a source file name). 6960 if (!SourceFileName.empty()) 6961 addThisModule(); 6962 assert(!SeenValueSymbolTable && 6963 "Already read VST when parsing summary block?"); 6964 // We might not have a VST if there were no values in the 6965 // summary. An empty summary block generated when we are 6966 // performing ThinLTO compiles so we don't later invoke 6967 // the regular LTO process on them. 6968 if (VSTOffset > 0) { 6969 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 6970 return Err; 6971 SeenValueSymbolTable = true; 6972 } 6973 SeenGlobalValSummary = true; 6974 if (Error Err = parseEntireSummary(Entry.ID)) 6975 return Err; 6976 break; 6977 case bitc::MODULE_STRTAB_BLOCK_ID: 6978 if (Error Err = parseModuleStringTable()) 6979 return Err; 6980 break; 6981 } 6982 continue; 6983 6984 case BitstreamEntry::Record: { 6985 Record.clear(); 6986 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6987 if (!MaybeBitCode) 6988 return MaybeBitCode.takeError(); 6989 switch (MaybeBitCode.get()) { 6990 default: 6991 break; // Default behavior, ignore unknown content. 6992 case bitc::MODULE_CODE_VERSION: { 6993 if (Error Err = parseVersionRecord(Record).takeError()) 6994 return Err; 6995 break; 6996 } 6997 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 6998 case bitc::MODULE_CODE_SOURCE_FILENAME: { 6999 SmallString<128> ValueName; 7000 if (convertToString(Record, 0, ValueName)) 7001 return error("Invalid record"); 7002 SourceFileName = ValueName.c_str(); 7003 break; 7004 } 7005 /// MODULE_CODE_HASH: [5*i32] 7006 case bitc::MODULE_CODE_HASH: { 7007 if (Record.size() != 5) 7008 return error("Invalid hash length " + Twine(Record.size()).str()); 7009 auto &Hash = getThisModule()->second; 7010 int Pos = 0; 7011 for (auto &Val : Record) { 7012 assert(!(Val >> 32) && "Unexpected high bits set"); 7013 Hash[Pos++] = Val; 7014 } 7015 break; 7016 } 7017 /// MODULE_CODE_VSTOFFSET: [offset] 7018 case bitc::MODULE_CODE_VSTOFFSET: 7019 if (Record.empty()) 7020 return error("Invalid record"); 7021 // Note that we subtract 1 here because the offset is relative to one 7022 // word before the start of the identification or module block, which 7023 // was historically always the start of the regular bitcode header. 7024 VSTOffset = Record[0] - 1; 7025 break; 7026 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 7027 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 7028 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 7029 // v2: [strtab offset, strtab size, v1] 7030 case bitc::MODULE_CODE_GLOBALVAR: 7031 case bitc::MODULE_CODE_FUNCTION: 7032 case bitc::MODULE_CODE_ALIAS: { 7033 StringRef Name; 7034 ArrayRef<uint64_t> GVRecord; 7035 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 7036 if (GVRecord.size() <= 3) 7037 return error("Invalid record"); 7038 uint64_t RawLinkage = GVRecord[3]; 7039 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 7040 if (!UseStrtab) { 7041 ValueIdToLinkageMap[ValueId++] = Linkage; 7042 break; 7043 } 7044 7045 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 7046 break; 7047 } 7048 } 7049 } 7050 continue; 7051 } 7052 } 7053 } 7054 7055 std::vector<ValueInfo> 7056 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 7057 std::vector<ValueInfo> Ret; 7058 Ret.reserve(Record.size()); 7059 for (uint64_t RefValueId : Record) 7060 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId))); 7061 return Ret; 7062 } 7063 7064 std::vector<FunctionSummary::EdgeTy> 7065 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 7066 bool IsOldProfileFormat, 7067 bool HasProfile, bool HasRelBF) { 7068 std::vector<FunctionSummary::EdgeTy> Ret; 7069 Ret.reserve(Record.size()); 7070 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 7071 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 7072 bool HasTailCall = false; 7073 uint64_t RelBF = 0; 7074 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 7075 if (IsOldProfileFormat) { 7076 I += 1; // Skip old callsitecount field 7077 if (HasProfile) 7078 I += 1; // Skip old profilecount field 7079 } else if (HasProfile) 7080 std::tie(Hotness, HasTailCall) = 7081 getDecodedHotnessCallEdgeInfo(Record[++I]); 7082 else if (HasRelBF) 7083 getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall); 7084 Ret.push_back(FunctionSummary::EdgeTy{ 7085 Callee, CalleeInfo(Hotness, HasTailCall, RelBF)}); 7086 } 7087 return Ret; 7088 } 7089 7090 static void 7091 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 7092 WholeProgramDevirtResolution &Wpd) { 7093 uint64_t ArgNum = Record[Slot++]; 7094 WholeProgramDevirtResolution::ByArg &B = 7095 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 7096 Slot += ArgNum; 7097 7098 B.TheKind = 7099 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 7100 B.Info = Record[Slot++]; 7101 B.Byte = Record[Slot++]; 7102 B.Bit = Record[Slot++]; 7103 } 7104 7105 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 7106 StringRef Strtab, size_t &Slot, 7107 TypeIdSummary &TypeId) { 7108 uint64_t Id = Record[Slot++]; 7109 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 7110 7111 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 7112 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 7113 static_cast<size_t>(Record[Slot + 1])}; 7114 Slot += 2; 7115 7116 uint64_t ResByArgNum = Record[Slot++]; 7117 for (uint64_t I = 0; I != ResByArgNum; ++I) 7118 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 7119 } 7120 7121 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 7122 StringRef Strtab, 7123 ModuleSummaryIndex &TheIndex) { 7124 size_t Slot = 0; 7125 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 7126 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 7127 Slot += 2; 7128 7129 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 7130 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 7131 TypeId.TTRes.AlignLog2 = Record[Slot++]; 7132 TypeId.TTRes.SizeM1 = Record[Slot++]; 7133 TypeId.TTRes.BitMask = Record[Slot++]; 7134 TypeId.TTRes.InlineBits = Record[Slot++]; 7135 7136 while (Slot < Record.size()) 7137 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 7138 } 7139 7140 std::vector<FunctionSummary::ParamAccess> 7141 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 7142 auto ReadRange = [&]() { 7143 APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 7144 BitcodeReader::decodeSignRotatedValue(Record.front())); 7145 Record = Record.drop_front(); 7146 APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 7147 BitcodeReader::decodeSignRotatedValue(Record.front())); 7148 Record = Record.drop_front(); 7149 ConstantRange Range{Lower, Upper}; 7150 assert(!Range.isFullSet()); 7151 assert(!Range.isUpperSignWrapped()); 7152 return Range; 7153 }; 7154 7155 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 7156 while (!Record.empty()) { 7157 PendingParamAccesses.emplace_back(); 7158 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 7159 ParamAccess.ParamNo = Record.front(); 7160 Record = Record.drop_front(); 7161 ParamAccess.Use = ReadRange(); 7162 ParamAccess.Calls.resize(Record.front()); 7163 Record = Record.drop_front(); 7164 for (auto &Call : ParamAccess.Calls) { 7165 Call.ParamNo = Record.front(); 7166 Record = Record.drop_front(); 7167 Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front())); 7168 Record = Record.drop_front(); 7169 Call.Offsets = ReadRange(); 7170 } 7171 } 7172 return PendingParamAccesses; 7173 } 7174 7175 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 7176 ArrayRef<uint64_t> Record, size_t &Slot, 7177 TypeIdCompatibleVtableInfo &TypeId) { 7178 uint64_t Offset = Record[Slot++]; 7179 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++])); 7180 TypeId.push_back({Offset, Callee}); 7181 } 7182 7183 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 7184 ArrayRef<uint64_t> Record) { 7185 size_t Slot = 0; 7186 TypeIdCompatibleVtableInfo &TypeId = 7187 TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 7188 {Strtab.data() + Record[Slot], 7189 static_cast<size_t>(Record[Slot + 1])}); 7190 Slot += 2; 7191 7192 while (Slot < Record.size()) 7193 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 7194 } 7195 7196 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 7197 unsigned WOCnt) { 7198 // Readonly and writeonly refs are in the end of the refs list. 7199 assert(ROCnt + WOCnt <= Refs.size()); 7200 unsigned FirstWORef = Refs.size() - WOCnt; 7201 unsigned RefNo = FirstWORef - ROCnt; 7202 for (; RefNo < FirstWORef; ++RefNo) 7203 Refs[RefNo].setReadOnly(); 7204 for (; RefNo < Refs.size(); ++RefNo) 7205 Refs[RefNo].setWriteOnly(); 7206 } 7207 7208 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 7209 // objects in the index. 7210 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 7211 if (Error Err = Stream.EnterSubBlock(ID)) 7212 return Err; 7213 SmallVector<uint64_t, 64> Record; 7214 7215 // Parse version 7216 { 7217 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7218 if (!MaybeEntry) 7219 return MaybeEntry.takeError(); 7220 BitstreamEntry Entry = MaybeEntry.get(); 7221 7222 if (Entry.Kind != BitstreamEntry::Record) 7223 return error("Invalid Summary Block: record for version expected"); 7224 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 7225 if (!MaybeRecord) 7226 return MaybeRecord.takeError(); 7227 if (MaybeRecord.get() != bitc::FS_VERSION) 7228 return error("Invalid Summary Block: version expected"); 7229 } 7230 const uint64_t Version = Record[0]; 7231 const bool IsOldProfileFormat = Version == 1; 7232 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 7233 return error("Invalid summary version " + Twine(Version) + 7234 ". Version should be in the range [1-" + 7235 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 7236 "]."); 7237 Record.clear(); 7238 7239 // Keep around the last seen summary to be used when we see an optional 7240 // "OriginalName" attachement. 7241 GlobalValueSummary *LastSeenSummary = nullptr; 7242 GlobalValue::GUID LastSeenGUID = 0; 7243 7244 // We can expect to see any number of type ID information records before 7245 // each function summary records; these variables store the information 7246 // collected so far so that it can be used to create the summary object. 7247 std::vector<GlobalValue::GUID> PendingTypeTests; 7248 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 7249 PendingTypeCheckedLoadVCalls; 7250 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 7251 PendingTypeCheckedLoadConstVCalls; 7252 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 7253 7254 std::vector<CallsiteInfo> PendingCallsites; 7255 std::vector<AllocInfo> PendingAllocs; 7256 7257 while (true) { 7258 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7259 if (!MaybeEntry) 7260 return MaybeEntry.takeError(); 7261 BitstreamEntry Entry = MaybeEntry.get(); 7262 7263 switch (Entry.Kind) { 7264 case BitstreamEntry::SubBlock: // Handled for us already. 7265 case BitstreamEntry::Error: 7266 return error("Malformed block"); 7267 case BitstreamEntry::EndBlock: 7268 return Error::success(); 7269 case BitstreamEntry::Record: 7270 // The interesting case. 7271 break; 7272 } 7273 7274 // Read a record. The record format depends on whether this 7275 // is a per-module index or a combined index file. In the per-module 7276 // case the records contain the associated value's ID for correlation 7277 // with VST entries. In the combined index the correlation is done 7278 // via the bitcode offset of the summary records (which were saved 7279 // in the combined index VST entries). The records also contain 7280 // information used for ThinLTO renaming and importing. 7281 Record.clear(); 7282 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 7283 if (!MaybeBitCode) 7284 return MaybeBitCode.takeError(); 7285 switch (unsigned BitCode = MaybeBitCode.get()) { 7286 default: // Default behavior: ignore. 7287 break; 7288 case bitc::FS_FLAGS: { // [flags] 7289 TheIndex.setFlags(Record[0]); 7290 break; 7291 } 7292 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 7293 uint64_t ValueID = Record[0]; 7294 GlobalValue::GUID RefGUID = Record[1]; 7295 ValueIdToValueInfoMap[ValueID] = std::make_tuple( 7296 TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID); 7297 break; 7298 } 7299 // FS_PERMODULE is legacy and does not have support for the tail call flag. 7300 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 7301 // numrefs x valueid, n x (valueid)] 7302 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 7303 // numrefs x valueid, 7304 // n x (valueid, hotness+tailcall flags)] 7305 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 7306 // numrefs x valueid, 7307 // n x (valueid, relblockfreq+tailcall)] 7308 case bitc::FS_PERMODULE: 7309 case bitc::FS_PERMODULE_RELBF: 7310 case bitc::FS_PERMODULE_PROFILE: { 7311 unsigned ValueID = Record[0]; 7312 uint64_t RawFlags = Record[1]; 7313 unsigned InstCount = Record[2]; 7314 uint64_t RawFunFlags = 0; 7315 unsigned NumRefs = Record[3]; 7316 unsigned NumRORefs = 0, NumWORefs = 0; 7317 int RefListStartIndex = 4; 7318 if (Version >= 4) { 7319 RawFunFlags = Record[3]; 7320 NumRefs = Record[4]; 7321 RefListStartIndex = 5; 7322 if (Version >= 5) { 7323 NumRORefs = Record[5]; 7324 RefListStartIndex = 6; 7325 if (Version >= 7) { 7326 NumWORefs = Record[6]; 7327 RefListStartIndex = 7; 7328 } 7329 } 7330 } 7331 7332 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7333 // The module path string ref set in the summary must be owned by the 7334 // index's module string table. Since we don't have a module path 7335 // string table section in the per-module index, we create a single 7336 // module path string table entry with an empty (0) ID to take 7337 // ownership. 7338 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 7339 assert(Record.size() >= RefListStartIndex + NumRefs && 7340 "Record size inconsistent with number of references"); 7341 std::vector<ValueInfo> Refs = makeRefList( 7342 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7343 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 7344 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 7345 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 7346 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 7347 IsOldProfileFormat, HasProfile, HasRelBF); 7348 setSpecialRefs(Refs, NumRORefs, NumWORefs); 7349 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 7350 // In order to save memory, only record the memprof summaries if this is 7351 // the prevailing copy of a symbol. The linker doesn't resolve local 7352 // linkage values so don't check whether those are prevailing. 7353 auto LT = (GlobalValue::LinkageTypes)Flags.Linkage; 7354 if (IsPrevailing && 7355 !GlobalValue::isLocalLinkage(LT) && 7356 !IsPrevailing(std::get<2>(VIAndOriginalGUID))) { 7357 PendingCallsites.clear(); 7358 PendingAllocs.clear(); 7359 } 7360 auto FS = std::make_unique<FunctionSummary>( 7361 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 7362 std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 7363 std::move(PendingTypeTestAssumeVCalls), 7364 std::move(PendingTypeCheckedLoadVCalls), 7365 std::move(PendingTypeTestAssumeConstVCalls), 7366 std::move(PendingTypeCheckedLoadConstVCalls), 7367 std::move(PendingParamAccesses), std::move(PendingCallsites), 7368 std::move(PendingAllocs)); 7369 FS->setModulePath(getThisModule()->first()); 7370 FS->setOriginalName(std::get<1>(VIAndOriginalGUID)); 7371 TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID), 7372 std::move(FS)); 7373 break; 7374 } 7375 // FS_ALIAS: [valueid, flags, valueid] 7376 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 7377 // they expect all aliasee summaries to be available. 7378 case bitc::FS_ALIAS: { 7379 unsigned ValueID = Record[0]; 7380 uint64_t RawFlags = Record[1]; 7381 unsigned AliaseeID = Record[2]; 7382 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7383 auto AS = std::make_unique<AliasSummary>(Flags); 7384 // The module path string ref set in the summary must be owned by the 7385 // index's module string table. Since we don't have a module path 7386 // string table section in the per-module index, we create a single 7387 // module path string table entry with an empty (0) ID to take 7388 // ownership. 7389 AS->setModulePath(getThisModule()->first()); 7390 7391 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID)); 7392 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 7393 if (!AliaseeInModule) 7394 return error("Alias expects aliasee summary to be parsed"); 7395 AS->setAliasee(AliaseeVI, AliaseeInModule); 7396 7397 auto GUID = getValueInfoFromValueId(ValueID); 7398 AS->setOriginalName(std::get<1>(GUID)); 7399 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS)); 7400 break; 7401 } 7402 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 7403 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 7404 unsigned ValueID = Record[0]; 7405 uint64_t RawFlags = Record[1]; 7406 unsigned RefArrayStart = 2; 7407 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 7408 /* WriteOnly */ false, 7409 /* Constant */ false, 7410 GlobalObject::VCallVisibilityPublic); 7411 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7412 if (Version >= 5) { 7413 GVF = getDecodedGVarFlags(Record[2]); 7414 RefArrayStart = 3; 7415 } 7416 std::vector<ValueInfo> Refs = 7417 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 7418 auto FS = 7419 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7420 FS->setModulePath(getThisModule()->first()); 7421 auto GUID = getValueInfoFromValueId(ValueID); 7422 FS->setOriginalName(std::get<1>(GUID)); 7423 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS)); 7424 break; 7425 } 7426 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 7427 // numrefs, numrefs x valueid, 7428 // n x (valueid, offset)] 7429 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 7430 unsigned ValueID = Record[0]; 7431 uint64_t RawFlags = Record[1]; 7432 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 7433 unsigned NumRefs = Record[3]; 7434 unsigned RefListStartIndex = 4; 7435 unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 7436 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7437 std::vector<ValueInfo> Refs = makeRefList( 7438 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7439 VTableFuncList VTableFuncs; 7440 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 7441 ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I])); 7442 uint64_t Offset = Record[++I]; 7443 VTableFuncs.push_back({Callee, Offset}); 7444 } 7445 auto VS = 7446 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7447 VS->setModulePath(getThisModule()->first()); 7448 VS->setVTableFuncs(VTableFuncs); 7449 auto GUID = getValueInfoFromValueId(ValueID); 7450 VS->setOriginalName(std::get<1>(GUID)); 7451 TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS)); 7452 break; 7453 } 7454 // FS_COMBINED is legacy and does not have support for the tail call flag. 7455 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 7456 // numrefs x valueid, n x (valueid)] 7457 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 7458 // numrefs x valueid, 7459 // n x (valueid, hotness+tailcall flags)] 7460 case bitc::FS_COMBINED: 7461 case bitc::FS_COMBINED_PROFILE: { 7462 unsigned ValueID = Record[0]; 7463 uint64_t ModuleId = Record[1]; 7464 uint64_t RawFlags = Record[2]; 7465 unsigned InstCount = Record[3]; 7466 uint64_t RawFunFlags = 0; 7467 uint64_t EntryCount = 0; 7468 unsigned NumRefs = Record[4]; 7469 unsigned NumRORefs = 0, NumWORefs = 0; 7470 int RefListStartIndex = 5; 7471 7472 if (Version >= 4) { 7473 RawFunFlags = Record[4]; 7474 RefListStartIndex = 6; 7475 size_t NumRefsIndex = 5; 7476 if (Version >= 5) { 7477 unsigned NumRORefsOffset = 1; 7478 RefListStartIndex = 7; 7479 if (Version >= 6) { 7480 NumRefsIndex = 6; 7481 EntryCount = Record[5]; 7482 RefListStartIndex = 8; 7483 if (Version >= 7) { 7484 RefListStartIndex = 9; 7485 NumWORefs = Record[8]; 7486 NumRORefsOffset = 2; 7487 } 7488 } 7489 NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 7490 } 7491 NumRefs = Record[NumRefsIndex]; 7492 } 7493 7494 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7495 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 7496 assert(Record.size() >= RefListStartIndex + NumRefs && 7497 "Record size inconsistent with number of references"); 7498 std::vector<ValueInfo> Refs = makeRefList( 7499 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 7500 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 7501 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 7502 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 7503 IsOldProfileFormat, HasProfile, false); 7504 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7505 setSpecialRefs(Refs, NumRORefs, NumWORefs); 7506 auto FS = std::make_unique<FunctionSummary>( 7507 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 7508 std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 7509 std::move(PendingTypeTestAssumeVCalls), 7510 std::move(PendingTypeCheckedLoadVCalls), 7511 std::move(PendingTypeTestAssumeConstVCalls), 7512 std::move(PendingTypeCheckedLoadConstVCalls), 7513 std::move(PendingParamAccesses), std::move(PendingCallsites), 7514 std::move(PendingAllocs)); 7515 LastSeenSummary = FS.get(); 7516 LastSeenGUID = VI.getGUID(); 7517 FS->setModulePath(ModuleIdMap[ModuleId]); 7518 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 7519 break; 7520 } 7521 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 7522 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 7523 // they expect all aliasee summaries to be available. 7524 case bitc::FS_COMBINED_ALIAS: { 7525 unsigned ValueID = Record[0]; 7526 uint64_t ModuleId = Record[1]; 7527 uint64_t RawFlags = Record[2]; 7528 unsigned AliaseeValueId = Record[3]; 7529 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7530 auto AS = std::make_unique<AliasSummary>(Flags); 7531 LastSeenSummary = AS.get(); 7532 AS->setModulePath(ModuleIdMap[ModuleId]); 7533 7534 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId)); 7535 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 7536 AS->setAliasee(AliaseeVI, AliaseeInModule); 7537 7538 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7539 LastSeenGUID = VI.getGUID(); 7540 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 7541 break; 7542 } 7543 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 7544 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 7545 unsigned ValueID = Record[0]; 7546 uint64_t ModuleId = Record[1]; 7547 uint64_t RawFlags = Record[2]; 7548 unsigned RefArrayStart = 3; 7549 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 7550 /* WriteOnly */ false, 7551 /* Constant */ false, 7552 GlobalObject::VCallVisibilityPublic); 7553 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 7554 if (Version >= 5) { 7555 GVF = getDecodedGVarFlags(Record[3]); 7556 RefArrayStart = 4; 7557 } 7558 std::vector<ValueInfo> Refs = 7559 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 7560 auto FS = 7561 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 7562 LastSeenSummary = FS.get(); 7563 FS->setModulePath(ModuleIdMap[ModuleId]); 7564 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7565 LastSeenGUID = VI.getGUID(); 7566 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 7567 break; 7568 } 7569 // FS_COMBINED_ORIGINAL_NAME: [original_name] 7570 case bitc::FS_COMBINED_ORIGINAL_NAME: { 7571 uint64_t OriginalName = Record[0]; 7572 if (!LastSeenSummary) 7573 return error("Name attachment that does not follow a combined record"); 7574 LastSeenSummary->setOriginalName(OriginalName); 7575 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 7576 // Reset the LastSeenSummary 7577 LastSeenSummary = nullptr; 7578 LastSeenGUID = 0; 7579 break; 7580 } 7581 case bitc::FS_TYPE_TESTS: 7582 assert(PendingTypeTests.empty()); 7583 llvm::append_range(PendingTypeTests, Record); 7584 break; 7585 7586 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 7587 assert(PendingTypeTestAssumeVCalls.empty()); 7588 for (unsigned I = 0; I != Record.size(); I += 2) 7589 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 7590 break; 7591 7592 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 7593 assert(PendingTypeCheckedLoadVCalls.empty()); 7594 for (unsigned I = 0; I != Record.size(); I += 2) 7595 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 7596 break; 7597 7598 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 7599 PendingTypeTestAssumeConstVCalls.push_back( 7600 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 7601 break; 7602 7603 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 7604 PendingTypeCheckedLoadConstVCalls.push_back( 7605 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 7606 break; 7607 7608 case bitc::FS_CFI_FUNCTION_DEFS: { 7609 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 7610 for (unsigned I = 0; I != Record.size(); I += 2) 7611 CfiFunctionDefs.insert( 7612 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 7613 break; 7614 } 7615 7616 case bitc::FS_CFI_FUNCTION_DECLS: { 7617 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 7618 for (unsigned I = 0; I != Record.size(); I += 2) 7619 CfiFunctionDecls.insert( 7620 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 7621 break; 7622 } 7623 7624 case bitc::FS_TYPE_ID: 7625 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 7626 break; 7627 7628 case bitc::FS_TYPE_ID_METADATA: 7629 parseTypeIdCompatibleVtableSummaryRecord(Record); 7630 break; 7631 7632 case bitc::FS_BLOCK_COUNT: 7633 TheIndex.addBlockCount(Record[0]); 7634 break; 7635 7636 case bitc::FS_PARAM_ACCESS: { 7637 PendingParamAccesses = parseParamAccesses(Record); 7638 break; 7639 } 7640 7641 case bitc::FS_STACK_IDS: { // [n x stackid] 7642 // Save stack ids in the reader to consult when adding stack ids from the 7643 // lists in the stack node and alloc node entries. 7644 StackIds = ArrayRef<uint64_t>(Record); 7645 break; 7646 } 7647 7648 case bitc::FS_PERMODULE_CALLSITE_INFO: { 7649 unsigned ValueID = Record[0]; 7650 SmallVector<unsigned> StackIdList; 7651 for (auto R = Record.begin() + 1; R != Record.end(); R++) { 7652 assert(*R < StackIds.size()); 7653 StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R])); 7654 } 7655 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID)); 7656 PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)})); 7657 break; 7658 } 7659 7660 case bitc::FS_COMBINED_CALLSITE_INFO: { 7661 auto RecordIter = Record.begin(); 7662 unsigned ValueID = *RecordIter++; 7663 unsigned NumStackIds = *RecordIter++; 7664 unsigned NumVersions = *RecordIter++; 7665 assert(Record.size() == 3 + NumStackIds + NumVersions); 7666 SmallVector<unsigned> StackIdList; 7667 for (unsigned J = 0; J < NumStackIds; J++) { 7668 assert(*RecordIter < StackIds.size()); 7669 StackIdList.push_back( 7670 TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++])); 7671 } 7672 SmallVector<unsigned> Versions; 7673 for (unsigned J = 0; J < NumVersions; J++) 7674 Versions.push_back(*RecordIter++); 7675 ValueInfo VI = std::get<0>( 7676 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID)); 7677 PendingCallsites.push_back( 7678 CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)})); 7679 break; 7680 } 7681 7682 case bitc::FS_PERMODULE_ALLOC_INFO: { 7683 unsigned I = 0; 7684 std::vector<MIBInfo> MIBs; 7685 while (I < Record.size()) { 7686 assert(Record.size() - I >= 2); 7687 AllocationType AllocType = (AllocationType)Record[I++]; 7688 unsigned NumStackEntries = Record[I++]; 7689 assert(Record.size() - I >= NumStackEntries); 7690 SmallVector<unsigned> StackIdList; 7691 for (unsigned J = 0; J < NumStackEntries; J++) { 7692 assert(Record[I] < StackIds.size()); 7693 StackIdList.push_back( 7694 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7695 } 7696 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7697 } 7698 PendingAllocs.push_back(AllocInfo(std::move(MIBs))); 7699 break; 7700 } 7701 7702 case bitc::FS_COMBINED_ALLOC_INFO: { 7703 unsigned I = 0; 7704 std::vector<MIBInfo> MIBs; 7705 unsigned NumMIBs = Record[I++]; 7706 unsigned NumVersions = Record[I++]; 7707 unsigned MIBsRead = 0; 7708 while (MIBsRead++ < NumMIBs) { 7709 assert(Record.size() - I >= 2); 7710 AllocationType AllocType = (AllocationType)Record[I++]; 7711 unsigned NumStackEntries = Record[I++]; 7712 assert(Record.size() - I >= NumStackEntries); 7713 SmallVector<unsigned> StackIdList; 7714 for (unsigned J = 0; J < NumStackEntries; J++) { 7715 assert(Record[I] < StackIds.size()); 7716 StackIdList.push_back( 7717 TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]])); 7718 } 7719 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList))); 7720 } 7721 assert(Record.size() - I >= NumVersions); 7722 SmallVector<uint8_t> Versions; 7723 for (unsigned J = 0; J < NumVersions; J++) 7724 Versions.push_back(Record[I++]); 7725 PendingAllocs.push_back( 7726 AllocInfo(std::move(Versions), std::move(MIBs))); 7727 break; 7728 } 7729 } 7730 } 7731 llvm_unreachable("Exit infinite loop"); 7732 } 7733 7734 // Parse the module string table block into the Index. 7735 // This populates the ModulePathStringTable map in the index. 7736 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 7737 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 7738 return Err; 7739 7740 SmallVector<uint64_t, 64> Record; 7741 7742 SmallString<128> ModulePath; 7743 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 7744 7745 while (true) { 7746 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 7747 if (!MaybeEntry) 7748 return MaybeEntry.takeError(); 7749 BitstreamEntry Entry = MaybeEntry.get(); 7750 7751 switch (Entry.Kind) { 7752 case BitstreamEntry::SubBlock: // Handled for us already. 7753 case BitstreamEntry::Error: 7754 return error("Malformed block"); 7755 case BitstreamEntry::EndBlock: 7756 return Error::success(); 7757 case BitstreamEntry::Record: 7758 // The interesting case. 7759 break; 7760 } 7761 7762 Record.clear(); 7763 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 7764 if (!MaybeRecord) 7765 return MaybeRecord.takeError(); 7766 switch (MaybeRecord.get()) { 7767 default: // Default behavior: ignore. 7768 break; 7769 case bitc::MST_CODE_ENTRY: { 7770 // MST_ENTRY: [modid, namechar x N] 7771 uint64_t ModuleId = Record[0]; 7772 7773 if (convertToString(Record, 1, ModulePath)) 7774 return error("Invalid record"); 7775 7776 LastSeenModule = TheIndex.addModule(ModulePath); 7777 ModuleIdMap[ModuleId] = LastSeenModule->first(); 7778 7779 ModulePath.clear(); 7780 break; 7781 } 7782 /// MST_CODE_HASH: [5*i32] 7783 case bitc::MST_CODE_HASH: { 7784 if (Record.size() != 5) 7785 return error("Invalid hash length " + Twine(Record.size()).str()); 7786 if (!LastSeenModule) 7787 return error("Invalid hash that does not follow a module path"); 7788 int Pos = 0; 7789 for (auto &Val : Record) { 7790 assert(!(Val >> 32) && "Unexpected high bits set"); 7791 LastSeenModule->second[Pos++] = Val; 7792 } 7793 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 7794 LastSeenModule = nullptr; 7795 break; 7796 } 7797 } 7798 } 7799 llvm_unreachable("Exit infinite loop"); 7800 } 7801 7802 namespace { 7803 7804 // FIXME: This class is only here to support the transition to llvm::Error. It 7805 // will be removed once this transition is complete. Clients should prefer to 7806 // deal with the Error value directly, rather than converting to error_code. 7807 class BitcodeErrorCategoryType : public std::error_category { 7808 const char *name() const noexcept override { 7809 return "llvm.bitcode"; 7810 } 7811 7812 std::string message(int IE) const override { 7813 BitcodeError E = static_cast<BitcodeError>(IE); 7814 switch (E) { 7815 case BitcodeError::CorruptedBitcode: 7816 return "Corrupted bitcode"; 7817 } 7818 llvm_unreachable("Unknown error type!"); 7819 } 7820 }; 7821 7822 } // end anonymous namespace 7823 7824 const std::error_category &llvm::BitcodeErrorCategory() { 7825 static BitcodeErrorCategoryType ErrorCategory; 7826 return ErrorCategory; 7827 } 7828 7829 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 7830 unsigned Block, unsigned RecordID) { 7831 if (Error Err = Stream.EnterSubBlock(Block)) 7832 return std::move(Err); 7833 7834 StringRef Strtab; 7835 while (true) { 7836 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7837 if (!MaybeEntry) 7838 return MaybeEntry.takeError(); 7839 llvm::BitstreamEntry Entry = MaybeEntry.get(); 7840 7841 switch (Entry.Kind) { 7842 case BitstreamEntry::EndBlock: 7843 return Strtab; 7844 7845 case BitstreamEntry::Error: 7846 return error("Malformed block"); 7847 7848 case BitstreamEntry::SubBlock: 7849 if (Error Err = Stream.SkipBlock()) 7850 return std::move(Err); 7851 break; 7852 7853 case BitstreamEntry::Record: 7854 StringRef Blob; 7855 SmallVector<uint64_t, 1> Record; 7856 Expected<unsigned> MaybeRecord = 7857 Stream.readRecord(Entry.ID, Record, &Blob); 7858 if (!MaybeRecord) 7859 return MaybeRecord.takeError(); 7860 if (MaybeRecord.get() == RecordID) 7861 Strtab = Blob; 7862 break; 7863 } 7864 } 7865 } 7866 7867 //===----------------------------------------------------------------------===// 7868 // External interface 7869 //===----------------------------------------------------------------------===// 7870 7871 Expected<std::vector<BitcodeModule>> 7872 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 7873 auto FOrErr = getBitcodeFileContents(Buffer); 7874 if (!FOrErr) 7875 return FOrErr.takeError(); 7876 return std::move(FOrErr->Mods); 7877 } 7878 7879 Expected<BitcodeFileContents> 7880 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 7881 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7882 if (!StreamOrErr) 7883 return StreamOrErr.takeError(); 7884 BitstreamCursor &Stream = *StreamOrErr; 7885 7886 BitcodeFileContents F; 7887 while (true) { 7888 uint64_t BCBegin = Stream.getCurrentByteNo(); 7889 7890 // We may be consuming bitcode from a client that leaves garbage at the end 7891 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 7892 // the end that there cannot possibly be another module, stop looking. 7893 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 7894 return F; 7895 7896 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7897 if (!MaybeEntry) 7898 return MaybeEntry.takeError(); 7899 llvm::BitstreamEntry Entry = MaybeEntry.get(); 7900 7901 switch (Entry.Kind) { 7902 case BitstreamEntry::EndBlock: 7903 case BitstreamEntry::Error: 7904 return error("Malformed block"); 7905 7906 case BitstreamEntry::SubBlock: { 7907 uint64_t IdentificationBit = -1ull; 7908 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 7909 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 7910 if (Error Err = Stream.SkipBlock()) 7911 return std::move(Err); 7912 7913 { 7914 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 7915 if (!MaybeEntry) 7916 return MaybeEntry.takeError(); 7917 Entry = MaybeEntry.get(); 7918 } 7919 7920 if (Entry.Kind != BitstreamEntry::SubBlock || 7921 Entry.ID != bitc::MODULE_BLOCK_ID) 7922 return error("Malformed block"); 7923 } 7924 7925 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 7926 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 7927 if (Error Err = Stream.SkipBlock()) 7928 return std::move(Err); 7929 7930 F.Mods.push_back({Stream.getBitcodeBytes().slice( 7931 BCBegin, Stream.getCurrentByteNo() - BCBegin), 7932 Buffer.getBufferIdentifier(), IdentificationBit, 7933 ModuleBit}); 7934 continue; 7935 } 7936 7937 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 7938 Expected<StringRef> Strtab = 7939 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 7940 if (!Strtab) 7941 return Strtab.takeError(); 7942 // This string table is used by every preceding bitcode module that does 7943 // not have its own string table. A bitcode file may have multiple 7944 // string tables if it was created by binary concatenation, for example 7945 // with "llvm-cat -b". 7946 for (BitcodeModule &I : llvm::reverse(F.Mods)) { 7947 if (!I.Strtab.empty()) 7948 break; 7949 I.Strtab = *Strtab; 7950 } 7951 // Similarly, the string table is used by every preceding symbol table; 7952 // normally there will be just one unless the bitcode file was created 7953 // by binary concatenation. 7954 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 7955 F.StrtabForSymtab = *Strtab; 7956 continue; 7957 } 7958 7959 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 7960 Expected<StringRef> SymtabOrErr = 7961 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 7962 if (!SymtabOrErr) 7963 return SymtabOrErr.takeError(); 7964 7965 // We can expect the bitcode file to have multiple symbol tables if it 7966 // was created by binary concatenation. In that case we silently 7967 // ignore any subsequent symbol tables, which is fine because this is a 7968 // low level function. The client is expected to notice that the number 7969 // of modules in the symbol table does not match the number of modules 7970 // in the input file and regenerate the symbol table. 7971 if (F.Symtab.empty()) 7972 F.Symtab = *SymtabOrErr; 7973 continue; 7974 } 7975 7976 if (Error Err = Stream.SkipBlock()) 7977 return std::move(Err); 7978 continue; 7979 } 7980 case BitstreamEntry::Record: 7981 if (Error E = Stream.skipRecord(Entry.ID).takeError()) 7982 return std::move(E); 7983 continue; 7984 } 7985 } 7986 } 7987 7988 /// Get a lazy one-at-time loading module from bitcode. 7989 /// 7990 /// This isn't always used in a lazy context. In particular, it's also used by 7991 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 7992 /// in forward-referenced functions from block address references. 7993 /// 7994 /// \param[in] MaterializeAll Set to \c true if we should materialize 7995 /// everything. 7996 Expected<std::unique_ptr<Module>> 7997 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 7998 bool ShouldLazyLoadMetadata, bool IsImporting, 7999 ParserCallbacks Callbacks) { 8000 BitstreamCursor Stream(Buffer); 8001 8002 std::string ProducerIdentification; 8003 if (IdentificationBit != -1ull) { 8004 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 8005 return std::move(JumpFailed); 8006 if (Error E = 8007 readIdentificationBlock(Stream).moveInto(ProducerIdentification)) 8008 return std::move(E); 8009 } 8010 8011 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 8012 return std::move(JumpFailed); 8013 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 8014 Context); 8015 8016 std::unique_ptr<Module> M = 8017 std::make_unique<Module>(ModuleIdentifier, Context); 8018 M->setMaterializer(R); 8019 8020 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 8021 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 8022 IsImporting, Callbacks)) 8023 return std::move(Err); 8024 8025 if (MaterializeAll) { 8026 // Read in the entire module, and destroy the BitcodeReader. 8027 if (Error Err = M->materializeAll()) 8028 return std::move(Err); 8029 } else { 8030 // Resolve forward references from blockaddresses. 8031 if (Error Err = R->materializeForwardReferencedFunctions()) 8032 return std::move(Err); 8033 } 8034 8035 return std::move(M); 8036 } 8037 8038 Expected<std::unique_ptr<Module>> 8039 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 8040 bool IsImporting, ParserCallbacks Callbacks) { 8041 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 8042 Callbacks); 8043 } 8044 8045 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 8046 // We don't use ModuleIdentifier here because the client may need to control the 8047 // module path used in the combined summary (e.g. when reading summaries for 8048 // regular LTO modules). 8049 Error BitcodeModule::readSummary( 8050 ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, 8051 std::function<bool(GlobalValue::GUID)> IsPrevailing) { 8052 BitstreamCursor Stream(Buffer); 8053 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 8054 return JumpFailed; 8055 8056 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 8057 ModulePath, IsPrevailing); 8058 return R.parseModule(); 8059 } 8060 8061 // Parse the specified bitcode buffer, returning the function info index. 8062 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 8063 BitstreamCursor Stream(Buffer); 8064 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 8065 return std::move(JumpFailed); 8066 8067 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 8068 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 8069 ModuleIdentifier, 0); 8070 8071 if (Error Err = R.parseModule()) 8072 return std::move(Err); 8073 8074 return std::move(Index); 8075 } 8076 8077 static Expected<std::pair<bool, bool>> 8078 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, 8079 unsigned ID, 8080 BitcodeLTOInfo <OInfo) { 8081 if (Error Err = Stream.EnterSubBlock(ID)) 8082 return std::move(Err); 8083 SmallVector<uint64_t, 64> Record; 8084 8085 while (true) { 8086 BitstreamEntry Entry; 8087 std::pair<bool, bool> Result = {false,false}; 8088 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry)) 8089 return std::move(E); 8090 8091 switch (Entry.Kind) { 8092 case BitstreamEntry::SubBlock: // Handled for us already. 8093 case BitstreamEntry::Error: 8094 return error("Malformed block"); 8095 case BitstreamEntry::EndBlock: { 8096 // If no flags record found, set both flags to false. 8097 return Result; 8098 } 8099 case BitstreamEntry::Record: 8100 // The interesting case. 8101 break; 8102 } 8103 8104 // Look for the FS_FLAGS record. 8105 Record.clear(); 8106 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 8107 if (!MaybeBitCode) 8108 return MaybeBitCode.takeError(); 8109 switch (MaybeBitCode.get()) { 8110 default: // Default behavior: ignore. 8111 break; 8112 case bitc::FS_FLAGS: { // [flags] 8113 uint64_t Flags = Record[0]; 8114 // Scan flags. 8115 assert(Flags <= 0x2ff && "Unexpected bits in flag"); 8116 8117 bool EnableSplitLTOUnit = Flags & 0x8; 8118 bool UnifiedLTO = Flags & 0x200; 8119 Result = {EnableSplitLTOUnit, UnifiedLTO}; 8120 8121 return Result; 8122 } 8123 } 8124 } 8125 llvm_unreachable("Exit infinite loop"); 8126 } 8127 8128 // Check if the given bitcode buffer contains a global value summary block. 8129 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 8130 BitstreamCursor Stream(Buffer); 8131 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 8132 return std::move(JumpFailed); 8133 8134 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 8135 return std::move(Err); 8136 8137 while (true) { 8138 llvm::BitstreamEntry Entry; 8139 if (Error E = Stream.advance().moveInto(Entry)) 8140 return std::move(E); 8141 8142 switch (Entry.Kind) { 8143 case BitstreamEntry::Error: 8144 return error("Malformed block"); 8145 case BitstreamEntry::EndBlock: 8146 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 8147 /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false}; 8148 8149 case BitstreamEntry::SubBlock: 8150 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 8151 BitcodeLTOInfo LTOInfo; 8152 Expected<std::pair<bool, bool>> Flags = 8153 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8154 if (!Flags) 8155 return Flags.takeError(); 8156 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8157 LTOInfo.IsThinLTO = true; 8158 LTOInfo.HasSummary = true; 8159 return LTOInfo; 8160 } 8161 8162 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 8163 BitcodeLTOInfo LTOInfo; 8164 Expected<std::pair<bool, bool>> Flags = 8165 getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo); 8166 if (!Flags) 8167 return Flags.takeError(); 8168 std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get(); 8169 LTOInfo.IsThinLTO = false; 8170 LTOInfo.HasSummary = true; 8171 return LTOInfo; 8172 } 8173 8174 // Ignore other sub-blocks. 8175 if (Error Err = Stream.SkipBlock()) 8176 return std::move(Err); 8177 continue; 8178 8179 case BitstreamEntry::Record: 8180 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 8181 continue; 8182 else 8183 return StreamFailed.takeError(); 8184 } 8185 } 8186 } 8187 8188 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 8189 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 8190 if (!MsOrErr) 8191 return MsOrErr.takeError(); 8192 8193 if (MsOrErr->size() != 1) 8194 return error("Expected a single module"); 8195 8196 return (*MsOrErr)[0]; 8197 } 8198 8199 Expected<std::unique_ptr<Module>> 8200 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 8201 bool ShouldLazyLoadMetadata, bool IsImporting, 8202 ParserCallbacks Callbacks) { 8203 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8204 if (!BM) 8205 return BM.takeError(); 8206 8207 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting, 8208 Callbacks); 8209 } 8210 8211 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 8212 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 8213 bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) { 8214 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 8215 IsImporting, Callbacks); 8216 if (MOrErr) 8217 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 8218 return MOrErr; 8219 } 8220 8221 Expected<std::unique_ptr<Module>> 8222 BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) { 8223 return getModuleImpl(Context, true, false, false, Callbacks); 8224 // TODO: Restore the use-lists to the in-memory state when the bitcode was 8225 // written. We must defer until the Module has been fully materialized. 8226 } 8227 8228 Expected<std::unique_ptr<Module>> 8229 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 8230 ParserCallbacks Callbacks) { 8231 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8232 if (!BM) 8233 return BM.takeError(); 8234 8235 return BM->parseModule(Context, Callbacks); 8236 } 8237 8238 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 8239 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8240 if (!StreamOrErr) 8241 return StreamOrErr.takeError(); 8242 8243 return readTriple(*StreamOrErr); 8244 } 8245 8246 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 8247 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8248 if (!StreamOrErr) 8249 return StreamOrErr.takeError(); 8250 8251 return hasObjCCategory(*StreamOrErr); 8252 } 8253 8254 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 8255 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 8256 if (!StreamOrErr) 8257 return StreamOrErr.takeError(); 8258 8259 return readIdentificationCode(*StreamOrErr); 8260 } 8261 8262 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 8263 ModuleSummaryIndex &CombinedIndex) { 8264 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8265 if (!BM) 8266 return BM.takeError(); 8267 8268 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier()); 8269 } 8270 8271 Expected<std::unique_ptr<ModuleSummaryIndex>> 8272 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 8273 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8274 if (!BM) 8275 return BM.takeError(); 8276 8277 return BM->getSummary(); 8278 } 8279 8280 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 8281 Expected<BitcodeModule> BM = getSingleModule(Buffer); 8282 if (!BM) 8283 return BM.takeError(); 8284 8285 return BM->getLTOInfo(); 8286 } 8287 8288 Expected<std::unique_ptr<ModuleSummaryIndex>> 8289 llvm::getModuleSummaryIndexForFile(StringRef Path, 8290 bool IgnoreEmptyThinLTOIndexFile) { 8291 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 8292 MemoryBuffer::getFileOrSTDIN(Path); 8293 if (!FileOrErr) 8294 return errorCodeToError(FileOrErr.getError()); 8295 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 8296 return nullptr; 8297 return getModuleSummaryIndex(**FileOrErr); 8298 } 8299