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