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