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