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