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