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