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