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