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