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