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