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