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