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