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