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