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 || !VectorType::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 uint64_t AlignExp = 4934 Bitfield::get<APV::AlignLower>(Rec) | 4935 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits); 4936 if (Error Err = parseAlignmentValue(AlignExp, Align)) { 4937 return Err; 4938 } 4939 if (!Ty || !Size) 4940 return error("Invalid record"); 4941 4942 // FIXME: Make this an optional field. 4943 const DataLayout &DL = TheModule->getDataLayout(); 4944 unsigned AS = DL.getAllocaAddrSpace(); 4945 4946 SmallPtrSet<Type *, 4> Visited; 4947 if (!Align && !Ty->isSized(&Visited)) 4948 return error("alloca of unsized type"); 4949 if (!Align) 4950 Align = DL.getPrefTypeAlign(Ty); 4951 4952 AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align); 4953 AI->setUsedWithInAlloca(InAlloca); 4954 AI->setSwiftError(SwiftError); 4955 I = AI; 4956 InstructionList.push_back(I); 4957 break; 4958 } 4959 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4960 unsigned OpNum = 0; 4961 Value *Op; 4962 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4963 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 4964 return error("Invalid record"); 4965 4966 if (!isa<PointerType>(Op->getType())) 4967 return error("Load operand is not a pointer type"); 4968 4969 Type *Ty = nullptr; 4970 if (OpNum + 3 == Record.size()) { 4971 Ty = getTypeByID(Record[OpNum++]); 4972 } else { 4973 Ty = cast<PointerType>(Op->getType())->getElementType(); 4974 } 4975 4976 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 4977 return Err; 4978 4979 MaybeAlign Align; 4980 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 4981 return Err; 4982 SmallPtrSet<Type *, 4> Visited; 4983 if (!Align && !Ty->isSized(&Visited)) 4984 return error("load of unsized type"); 4985 if (!Align) 4986 Align = TheModule->getDataLayout().getABITypeAlign(Ty); 4987 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align); 4988 InstructionList.push_back(I); 4989 break; 4990 } 4991 case bitc::FUNC_CODE_INST_LOADATOMIC: { 4992 // LOADATOMIC: [opty, op, align, vol, ordering, ssid] 4993 unsigned OpNum = 0; 4994 Value *Op; 4995 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4996 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 4997 return error("Invalid record"); 4998 4999 if (!isa<PointerType>(Op->getType())) 5000 return error("Load operand is not a pointer type"); 5001 5002 Type *Ty = nullptr; 5003 if (OpNum + 5 == Record.size()) { 5004 Ty = getTypeByID(Record[OpNum++]); 5005 } else { 5006 Ty = cast<PointerType>(Op->getType())->getElementType(); 5007 } 5008 5009 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5010 return Err; 5011 5012 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5013 if (Ordering == AtomicOrdering::NotAtomic || 5014 Ordering == AtomicOrdering::Release || 5015 Ordering == AtomicOrdering::AcquireRelease) 5016 return error("Invalid record"); 5017 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5018 return error("Invalid record"); 5019 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5020 5021 MaybeAlign Align; 5022 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5023 return Err; 5024 if (!Align) 5025 return error("Alignment missing from atomic load"); 5026 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID); 5027 InstructionList.push_back(I); 5028 break; 5029 } 5030 case bitc::FUNC_CODE_INST_STORE: 5031 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 5032 unsigned OpNum = 0; 5033 Value *Val, *Ptr; 5034 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5035 (BitCode == bitc::FUNC_CODE_INST_STORE 5036 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5037 : popValue(Record, OpNum, NextValueNo, 5038 cast<PointerType>(Ptr->getType())->getElementType(), 5039 Val)) || 5040 OpNum + 2 != Record.size()) 5041 return error("Invalid record"); 5042 5043 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5044 return Err; 5045 MaybeAlign Align; 5046 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5047 return Err; 5048 SmallPtrSet<Type *, 4> Visited; 5049 if (!Align && !Val->getType()->isSized(&Visited)) 5050 return error("store of unsized type"); 5051 if (!Align) 5052 Align = TheModule->getDataLayout().getABITypeAlign(Val->getType()); 5053 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align); 5054 InstructionList.push_back(I); 5055 break; 5056 } 5057 case bitc::FUNC_CODE_INST_STOREATOMIC: 5058 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 5059 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid] 5060 unsigned OpNum = 0; 5061 Value *Val, *Ptr; 5062 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5063 !isa<PointerType>(Ptr->getType()) || 5064 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 5065 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5066 : popValue(Record, OpNum, NextValueNo, 5067 cast<PointerType>(Ptr->getType())->getElementType(), 5068 Val)) || 5069 OpNum + 4 != Record.size()) 5070 return error("Invalid record"); 5071 5072 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5073 return Err; 5074 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5075 if (Ordering == AtomicOrdering::NotAtomic || 5076 Ordering == AtomicOrdering::Acquire || 5077 Ordering == AtomicOrdering::AcquireRelease) 5078 return error("Invalid record"); 5079 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5080 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5081 return error("Invalid record"); 5082 5083 MaybeAlign Align; 5084 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5085 return Err; 5086 if (!Align) 5087 return error("Alignment missing from atomic store"); 5088 I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID); 5089 InstructionList.push_back(I); 5090 break; 5091 } 5092 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: { 5093 // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope, 5094 // failure_ordering?, weak?] 5095 const size_t NumRecords = Record.size(); 5096 unsigned OpNum = 0; 5097 Value *Ptr = nullptr; 5098 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) 5099 return error("Invalid record"); 5100 5101 if (!isa<PointerType>(Ptr->getType())) 5102 return error("Cmpxchg operand is not a pointer type"); 5103 5104 Value *Cmp = nullptr; 5105 if (popValue(Record, OpNum, NextValueNo, 5106 cast<PointerType>(Ptr->getType())->getPointerElementType(), 5107 Cmp)) 5108 return error("Invalid record"); 5109 5110 Value *New = nullptr; 5111 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5112 NumRecords < OpNum + 3 || NumRecords > OpNum + 5) 5113 return error("Invalid record"); 5114 5115 const AtomicOrdering SuccessOrdering = 5116 getDecodedOrdering(Record[OpNum + 1]); 5117 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5118 SuccessOrdering == AtomicOrdering::Unordered) 5119 return error("Invalid record"); 5120 5121 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 5122 5123 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5124 return Err; 5125 5126 const AtomicOrdering FailureOrdering = 5127 NumRecords < 7 5128 ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering) 5129 : getDecodedOrdering(Record[OpNum + 3]); 5130 5131 if (FailureOrdering == AtomicOrdering::NotAtomic || 5132 FailureOrdering == AtomicOrdering::Unordered) 5133 return error("Invalid record"); 5134 5135 const Align Alignment( 5136 TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 5137 5138 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering, 5139 FailureOrdering, SSID); 5140 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5141 5142 if (NumRecords < 8) { 5143 // Before weak cmpxchgs existed, the instruction simply returned the 5144 // value loaded from memory, so bitcode files from that era will be 5145 // expecting the first component of a modern cmpxchg. 5146 CurBB->getInstList().push_back(I); 5147 I = ExtractValueInst::Create(I, 0); 5148 } else { 5149 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]); 5150 } 5151 5152 InstructionList.push_back(I); 5153 break; 5154 } 5155 case bitc::FUNC_CODE_INST_CMPXCHG: { 5156 // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope, 5157 // failure_ordering, weak, align?] 5158 const size_t NumRecords = Record.size(); 5159 unsigned OpNum = 0; 5160 Value *Ptr = nullptr; 5161 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) 5162 return error("Invalid record"); 5163 5164 if (!isa<PointerType>(Ptr->getType())) 5165 return error("Cmpxchg operand is not a pointer type"); 5166 5167 Value *Cmp = nullptr; 5168 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp)) 5169 return error("Invalid record"); 5170 5171 Value *Val = nullptr; 5172 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val)) 5173 return error("Invalid record"); 5174 5175 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6) 5176 return error("Invalid record"); 5177 5178 const bool IsVol = Record[OpNum]; 5179 5180 const AtomicOrdering SuccessOrdering = 5181 getDecodedOrdering(Record[OpNum + 1]); 5182 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering)) 5183 return error("Invalid cmpxchg success ordering"); 5184 5185 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]); 5186 5187 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5188 return Err; 5189 5190 const AtomicOrdering FailureOrdering = 5191 getDecodedOrdering(Record[OpNum + 3]); 5192 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering)) 5193 return error("Invalid cmpxchg failure ordering"); 5194 5195 const bool IsWeak = Record[OpNum + 4]; 5196 5197 MaybeAlign Alignment; 5198 5199 if (NumRecords == (OpNum + 6)) { 5200 if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment)) 5201 return Err; 5202 } 5203 if (!Alignment) 5204 Alignment = 5205 Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType())); 5206 5207 I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering, 5208 FailureOrdering, SSID); 5209 cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol); 5210 cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak); 5211 5212 InstructionList.push_back(I); 5213 break; 5214 } 5215 case bitc::FUNC_CODE_INST_ATOMICRMW_OLD: 5216 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5217 // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?] 5218 // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?] 5219 const size_t NumRecords = Record.size(); 5220 unsigned OpNum = 0; 5221 5222 Value *Ptr = nullptr; 5223 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr)) 5224 return error("Invalid record"); 5225 5226 if (!isa<PointerType>(Ptr->getType())) 5227 return error("Invalid record"); 5228 5229 Value *Val = nullptr; 5230 if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) { 5231 if (popValue(Record, OpNum, NextValueNo, 5232 cast<PointerType>(Ptr->getType())->getPointerElementType(), 5233 Val)) 5234 return error("Invalid record"); 5235 } else { 5236 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 5237 return error("Invalid record"); 5238 } 5239 5240 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5))) 5241 return error("Invalid record"); 5242 5243 const AtomicRMWInst::BinOp Operation = 5244 getDecodedRMWOperation(Record[OpNum]); 5245 if (Operation < AtomicRMWInst::FIRST_BINOP || 5246 Operation > AtomicRMWInst::LAST_BINOP) 5247 return error("Invalid record"); 5248 5249 const bool IsVol = Record[OpNum + 1]; 5250 5251 const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5252 if (Ordering == AtomicOrdering::NotAtomic || 5253 Ordering == AtomicOrdering::Unordered) 5254 return error("Invalid record"); 5255 5256 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); 5257 5258 MaybeAlign Alignment; 5259 5260 if (NumRecords == (OpNum + 5)) { 5261 if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment)) 5262 return Err; 5263 } 5264 5265 if (!Alignment) 5266 Alignment = 5267 Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType())); 5268 5269 I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID); 5270 cast<AtomicRMWInst>(I)->setVolatile(IsVol); 5271 5272 InstructionList.push_back(I); 5273 break; 5274 } 5275 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid] 5276 if (2 != Record.size()) 5277 return error("Invalid record"); 5278 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5279 if (Ordering == AtomicOrdering::NotAtomic || 5280 Ordering == AtomicOrdering::Unordered || 5281 Ordering == AtomicOrdering::Monotonic) 5282 return error("Invalid record"); 5283 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]); 5284 I = new FenceInst(Context, Ordering, SSID); 5285 InstructionList.push_back(I); 5286 break; 5287 } 5288 case bitc::FUNC_CODE_INST_CALL: { 5289 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5290 if (Record.size() < 3) 5291 return error("Invalid record"); 5292 5293 unsigned OpNum = 0; 5294 AttributeList PAL = getAttributes(Record[OpNum++]); 5295 unsigned CCInfo = Record[OpNum++]; 5296 5297 FastMathFlags FMF; 5298 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5299 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5300 if (!FMF.any()) 5301 return error("Fast math flags indicator set for call with no FMF"); 5302 } 5303 5304 FunctionType *FTy = nullptr; 5305 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) { 5306 FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])); 5307 if (!FTy) 5308 return error("Explicit call type is not a function type"); 5309 } 5310 5311 Value *Callee; 5312 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5313 return error("Invalid record"); 5314 5315 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5316 if (!OpTy) 5317 return error("Callee is not a pointer type"); 5318 if (!FTy) { 5319 FTy = dyn_cast<FunctionType>( 5320 cast<PointerType>(Callee->getType())->getElementType()); 5321 if (!FTy) 5322 return error("Callee is not of pointer to function type"); 5323 } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy)) 5324 return error("Explicit call type does not match pointee type of " 5325 "callee operand"); 5326 if (Record.size() < FTy->getNumParams() + OpNum) 5327 return error("Insufficient operands to call"); 5328 5329 SmallVector<Value*, 16> Args; 5330 SmallVector<Type *, 16> ArgsTys; 5331 // Read the fixed params. 5332 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5333 if (FTy->getParamType(i)->isLabelTy()) 5334 Args.push_back(getBasicBlock(Record[OpNum])); 5335 else 5336 Args.push_back(getValue(Record, OpNum, NextValueNo, 5337 FTy->getParamType(i))); 5338 ArgsTys.push_back(FTy->getParamType(i)); 5339 if (!Args.back()) 5340 return error("Invalid record"); 5341 } 5342 5343 // Read type/value pairs for varargs params. 5344 if (!FTy->isVarArg()) { 5345 if (OpNum != Record.size()) 5346 return error("Invalid record"); 5347 } else { 5348 while (OpNum != Record.size()) { 5349 Value *Op; 5350 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5351 return error("Invalid record"); 5352 Args.push_back(Op); 5353 ArgsTys.push_back(Op->getType()); 5354 } 5355 } 5356 5357 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5358 OperandBundles.clear(); 5359 InstructionList.push_back(I); 5360 cast<CallInst>(I)->setCallingConv( 5361 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5362 CallInst::TailCallKind TCK = CallInst::TCK_None; 5363 if (CCInfo & 1 << bitc::CALL_TAIL) 5364 TCK = CallInst::TCK_Tail; 5365 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5366 TCK = CallInst::TCK_MustTail; 5367 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5368 TCK = CallInst::TCK_NoTail; 5369 cast<CallInst>(I)->setTailCallKind(TCK); 5370 cast<CallInst>(I)->setAttributes(PAL); 5371 propagateAttributeTypes(cast<CallBase>(I), ArgsTys); 5372 if (FMF.any()) { 5373 if (!isa<FPMathOperator>(I)) 5374 return error("Fast-math-flags specified for call without " 5375 "floating-point scalar or vector return type"); 5376 I->setFastMathFlags(FMF); 5377 } 5378 break; 5379 } 5380 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5381 if (Record.size() < 3) 5382 return error("Invalid record"); 5383 Type *OpTy = getTypeByID(Record[0]); 5384 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5385 Type *ResTy = getTypeByID(Record[2]); 5386 if (!OpTy || !Op || !ResTy) 5387 return error("Invalid record"); 5388 I = new VAArgInst(Op, ResTy); 5389 InstructionList.push_back(I); 5390 break; 5391 } 5392 5393 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5394 // A call or an invoke can be optionally prefixed with some variable 5395 // number of operand bundle blocks. These blocks are read into 5396 // OperandBundles and consumed at the next call or invoke instruction. 5397 5398 if (Record.empty() || Record[0] >= BundleTags.size()) 5399 return error("Invalid record"); 5400 5401 std::vector<Value *> Inputs; 5402 5403 unsigned OpNum = 1; 5404 while (OpNum != Record.size()) { 5405 Value *Op; 5406 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5407 return error("Invalid record"); 5408 Inputs.push_back(Op); 5409 } 5410 5411 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5412 continue; 5413 } 5414 5415 case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval] 5416 unsigned OpNum = 0; 5417 Value *Op = nullptr; 5418 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5419 return error("Invalid record"); 5420 if (OpNum != Record.size()) 5421 return error("Invalid record"); 5422 5423 I = new FreezeInst(Op); 5424 InstructionList.push_back(I); 5425 break; 5426 } 5427 } 5428 5429 // Add instruction to end of current BB. If there is no current BB, reject 5430 // this file. 5431 if (!CurBB) { 5432 I->deleteValue(); 5433 return error("Invalid instruction with no BB"); 5434 } 5435 if (!OperandBundles.empty()) { 5436 I->deleteValue(); 5437 return error("Operand bundles found with no consumer"); 5438 } 5439 CurBB->getInstList().push_back(I); 5440 5441 // If this was a terminator instruction, move to the next block. 5442 if (I->isTerminator()) { 5443 ++CurBBNo; 5444 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5445 } 5446 5447 // Non-void values get registered in the value table for future use. 5448 if (!I->getType()->isVoidTy()) 5449 ValueList.assignValue(I, NextValueNo++); 5450 } 5451 5452 OutOfRecordLoop: 5453 5454 if (!OperandBundles.empty()) 5455 return error("Operand bundles found with no consumer"); 5456 5457 // Check the function list for unresolved values. 5458 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5459 if (!A->getParent()) { 5460 // We found at least one unresolved value. Nuke them all to avoid leaks. 5461 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5462 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5463 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5464 delete A; 5465 } 5466 } 5467 return error("Never resolved value found in function"); 5468 } 5469 } 5470 5471 // Unexpected unresolved metadata about to be dropped. 5472 if (MDLoader->hasFwdRefs()) 5473 return error("Invalid function metadata: outgoing forward refs"); 5474 5475 // Trim the value list down to the size it was before we parsed this function. 5476 ValueList.shrinkTo(ModuleValueListSize); 5477 MDLoader->shrinkTo(ModuleMDLoaderSize); 5478 std::vector<BasicBlock*>().swap(FunctionBBs); 5479 return Error::success(); 5480 } 5481 5482 /// Find the function body in the bitcode stream 5483 Error BitcodeReader::findFunctionInStream( 5484 Function *F, 5485 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5486 while (DeferredFunctionInfoIterator->second == 0) { 5487 // This is the fallback handling for the old format bitcode that 5488 // didn't contain the function index in the VST, or when we have 5489 // an anonymous function which would not have a VST entry. 5490 // Assert that we have one of those two cases. 5491 assert(VSTOffset == 0 || !F->hasName()); 5492 // Parse the next body in the stream and set its position in the 5493 // DeferredFunctionInfo map. 5494 if (Error Err = rememberAndSkipFunctionBodies()) 5495 return Err; 5496 } 5497 return Error::success(); 5498 } 5499 5500 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) { 5501 if (Val == SyncScope::SingleThread || Val == SyncScope::System) 5502 return SyncScope::ID(Val); 5503 if (Val >= SSIDs.size()) 5504 return SyncScope::System; // Map unknown synchronization scopes to system. 5505 return SSIDs[Val]; 5506 } 5507 5508 //===----------------------------------------------------------------------===// 5509 // GVMaterializer implementation 5510 //===----------------------------------------------------------------------===// 5511 5512 Error BitcodeReader::materialize(GlobalValue *GV) { 5513 Function *F = dyn_cast<Function>(GV); 5514 // If it's not a function or is already material, ignore the request. 5515 if (!F || !F->isMaterializable()) 5516 return Error::success(); 5517 5518 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5519 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5520 // If its position is recorded as 0, its body is somewhere in the stream 5521 // but we haven't seen it yet. 5522 if (DFII->second == 0) 5523 if (Error Err = findFunctionInStream(F, DFII)) 5524 return Err; 5525 5526 // Materialize metadata before parsing any function bodies. 5527 if (Error Err = materializeMetadata()) 5528 return Err; 5529 5530 // Move the bit stream to the saved position of the deferred function body. 5531 if (Error JumpFailed = Stream.JumpToBit(DFII->second)) 5532 return JumpFailed; 5533 if (Error Err = parseFunctionBody(F)) 5534 return Err; 5535 F->setIsMaterializable(false); 5536 5537 if (StripDebugInfo) 5538 stripDebugInfo(*F); 5539 5540 // Upgrade any old intrinsic calls in the function. 5541 for (auto &I : UpgradedIntrinsics) { 5542 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5543 UI != UE;) { 5544 User *U = *UI; 5545 ++UI; 5546 if (CallInst *CI = dyn_cast<CallInst>(U)) 5547 UpgradeIntrinsicCall(CI, I.second); 5548 } 5549 } 5550 5551 // Update calls to the remangled intrinsics 5552 for (auto &I : RemangledIntrinsics) 5553 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5554 UI != UE;) 5555 // Don't expect any other users than call sites 5556 cast<CallBase>(*UI++)->setCalledFunction(I.second); 5557 5558 // Finish fn->subprogram upgrade for materialized functions. 5559 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F)) 5560 F->setSubprogram(SP); 5561 5562 // Check if the TBAA Metadata are valid, otherwise we will need to strip them. 5563 if (!MDLoader->isStrippingTBAA()) { 5564 for (auto &I : instructions(F)) { 5565 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa); 5566 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA)) 5567 continue; 5568 MDLoader->setStripTBAA(true); 5569 stripTBAA(F->getParent()); 5570 } 5571 } 5572 5573 for (auto &I : instructions(F)) { 5574 // "Upgrade" older incorrect branch weights by dropping them. 5575 if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) { 5576 if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) { 5577 MDString *MDS = cast<MDString>(MD->getOperand(0)); 5578 StringRef ProfName = MDS->getString(); 5579 // Check consistency of !prof branch_weights metadata. 5580 if (!ProfName.equals("branch_weights")) 5581 continue; 5582 unsigned ExpectedNumOperands = 0; 5583 if (BranchInst *BI = dyn_cast<BranchInst>(&I)) 5584 ExpectedNumOperands = BI->getNumSuccessors(); 5585 else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I)) 5586 ExpectedNumOperands = SI->getNumSuccessors(); 5587 else if (isa<CallInst>(&I)) 5588 ExpectedNumOperands = 1; 5589 else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I)) 5590 ExpectedNumOperands = IBI->getNumDestinations(); 5591 else if (isa<SelectInst>(&I)) 5592 ExpectedNumOperands = 2; 5593 else 5594 continue; // ignore and continue. 5595 5596 // If branch weight doesn't match, just strip branch weight. 5597 if (MD->getNumOperands() != 1 + ExpectedNumOperands) 5598 I.setMetadata(LLVMContext::MD_prof, nullptr); 5599 } 5600 } 5601 5602 // Remove incompatible attributes on function calls. 5603 if (auto *CI = dyn_cast<CallBase>(&I)) { 5604 CI->removeRetAttrs(AttributeFuncs::typeIncompatible( 5605 CI->getFunctionType()->getReturnType())); 5606 5607 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo) 5608 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible( 5609 CI->getArgOperand(ArgNo)->getType())); 5610 } 5611 } 5612 5613 // Look for functions that rely on old function attribute behavior. 5614 UpgradeFunctionAttributes(*F); 5615 5616 // Bring in any functions that this function forward-referenced via 5617 // blockaddresses. 5618 return materializeForwardReferencedFunctions(); 5619 } 5620 5621 Error BitcodeReader::materializeModule() { 5622 if (Error Err = materializeMetadata()) 5623 return Err; 5624 5625 // Promise to materialize all forward references. 5626 WillMaterializeAllForwardRefs = true; 5627 5628 // Iterate over the module, deserializing any functions that are still on 5629 // disk. 5630 for (Function &F : *TheModule) { 5631 if (Error Err = materialize(&F)) 5632 return Err; 5633 } 5634 // At this point, if there are any function bodies, parse the rest of 5635 // the bits in the module past the last function block we have recorded 5636 // through either lazy scanning or the VST. 5637 if (LastFunctionBlockBit || NextUnreadBit) 5638 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 5639 ? LastFunctionBlockBit 5640 : NextUnreadBit)) 5641 return Err; 5642 5643 // Check that all block address forward references got resolved (as we 5644 // promised above). 5645 if (!BasicBlockFwdRefs.empty()) 5646 return error("Never resolved function from blockaddress"); 5647 5648 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5649 // delete the old functions to clean up. We can't do this unless the entire 5650 // module is materialized because there could always be another function body 5651 // with calls to the old function. 5652 for (auto &I : UpgradedIntrinsics) { 5653 for (auto *U : I.first->users()) { 5654 if (CallInst *CI = dyn_cast<CallInst>(U)) 5655 UpgradeIntrinsicCall(CI, I.second); 5656 } 5657 if (!I.first->use_empty()) 5658 I.first->replaceAllUsesWith(I.second); 5659 I.first->eraseFromParent(); 5660 } 5661 UpgradedIntrinsics.clear(); 5662 // Do the same for remangled intrinsics 5663 for (auto &I : RemangledIntrinsics) { 5664 I.first->replaceAllUsesWith(I.second); 5665 I.first->eraseFromParent(); 5666 } 5667 RemangledIntrinsics.clear(); 5668 5669 UpgradeDebugInfo(*TheModule); 5670 5671 UpgradeModuleFlags(*TheModule); 5672 5673 UpgradeARCRuntime(*TheModule); 5674 5675 return Error::success(); 5676 } 5677 5678 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5679 return IdentifiedStructTypes; 5680 } 5681 5682 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5683 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex, 5684 StringRef ModulePath, unsigned ModuleId) 5685 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex), 5686 ModulePath(ModulePath), ModuleId(ModuleId) {} 5687 5688 void ModuleSummaryIndexBitcodeReader::addThisModule() { 5689 TheIndex.addModule(ModulePath, ModuleId); 5690 } 5691 5692 ModuleSummaryIndex::ModuleInfo * 5693 ModuleSummaryIndexBitcodeReader::getThisModule() { 5694 return TheIndex.getModule(ModulePath); 5695 } 5696 5697 std::pair<ValueInfo, GlobalValue::GUID> 5698 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) { 5699 auto VGI = ValueIdToValueInfoMap[ValueId]; 5700 assert(VGI.first); 5701 return VGI; 5702 } 5703 5704 void ModuleSummaryIndexBitcodeReader::setValueGUID( 5705 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage, 5706 StringRef SourceFileName) { 5707 std::string GlobalId = 5708 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 5709 auto ValueGUID = GlobalValue::getGUID(GlobalId); 5710 auto OriginalNameID = ValueGUID; 5711 if (GlobalValue::isLocalLinkage(Linkage)) 5712 OriginalNameID = GlobalValue::getGUID(ValueName); 5713 if (PrintSummaryGUIDs) 5714 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 5715 << ValueName << "\n"; 5716 5717 // UseStrtab is false for legacy summary formats and value names are 5718 // created on stack. In that case we save the name in a string saver in 5719 // the index so that the value name can be recorded. 5720 ValueIdToValueInfoMap[ValueID] = std::make_pair( 5721 TheIndex.getOrInsertValueInfo( 5722 ValueGUID, 5723 UseStrtab ? ValueName : TheIndex.saveString(ValueName)), 5724 OriginalNameID); 5725 } 5726 5727 // Specialized value symbol table parser used when reading module index 5728 // blocks where we don't actually create global values. The parsed information 5729 // is saved in the bitcode reader for use when later parsing summaries. 5730 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5731 uint64_t Offset, 5732 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5733 // With a strtab the VST is not required to parse the summary. 5734 if (UseStrtab) 5735 return Error::success(); 5736 5737 assert(Offset > 0 && "Expected non-zero VST offset"); 5738 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream); 5739 if (!MaybeCurrentBit) 5740 return MaybeCurrentBit.takeError(); 5741 uint64_t CurrentBit = MaybeCurrentBit.get(); 5742 5743 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5744 return Err; 5745 5746 SmallVector<uint64_t, 64> Record; 5747 5748 // Read all the records for this value table. 5749 SmallString<128> ValueName; 5750 5751 while (true) { 5752 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 5753 if (!MaybeEntry) 5754 return MaybeEntry.takeError(); 5755 BitstreamEntry Entry = MaybeEntry.get(); 5756 5757 switch (Entry.Kind) { 5758 case BitstreamEntry::SubBlock: // Handled for us already. 5759 case BitstreamEntry::Error: 5760 return error("Malformed block"); 5761 case BitstreamEntry::EndBlock: 5762 // Done parsing VST, jump back to wherever we came from. 5763 if (Error JumpFailed = Stream.JumpToBit(CurrentBit)) 5764 return JumpFailed; 5765 return Error::success(); 5766 case BitstreamEntry::Record: 5767 // The interesting case. 5768 break; 5769 } 5770 5771 // Read a record. 5772 Record.clear(); 5773 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 5774 if (!MaybeRecord) 5775 return MaybeRecord.takeError(); 5776 switch (MaybeRecord.get()) { 5777 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 5778 break; 5779 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 5780 if (convertToString(Record, 1, ValueName)) 5781 return error("Invalid record"); 5782 unsigned ValueID = Record[0]; 5783 assert(!SourceFileName.empty()); 5784 auto VLI = ValueIdToLinkageMap.find(ValueID); 5785 assert(VLI != ValueIdToLinkageMap.end() && 5786 "No linkage found for VST entry?"); 5787 auto Linkage = VLI->second; 5788 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 5789 ValueName.clear(); 5790 break; 5791 } 5792 case bitc::VST_CODE_FNENTRY: { 5793 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 5794 if (convertToString(Record, 2, ValueName)) 5795 return error("Invalid record"); 5796 unsigned ValueID = Record[0]; 5797 assert(!SourceFileName.empty()); 5798 auto VLI = ValueIdToLinkageMap.find(ValueID); 5799 assert(VLI != ValueIdToLinkageMap.end() && 5800 "No linkage found for VST entry?"); 5801 auto Linkage = VLI->second; 5802 setValueGUID(ValueID, ValueName, Linkage, SourceFileName); 5803 ValueName.clear(); 5804 break; 5805 } 5806 case bitc::VST_CODE_COMBINED_ENTRY: { 5807 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 5808 unsigned ValueID = Record[0]; 5809 GlobalValue::GUID RefGUID = Record[1]; 5810 // The "original name", which is the second value of the pair will be 5811 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 5812 ValueIdToValueInfoMap[ValueID] = 5813 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 5814 break; 5815 } 5816 } 5817 } 5818 } 5819 5820 // Parse just the blocks needed for building the index out of the module. 5821 // At the end of this routine the module Index is populated with a map 5822 // from global value id to GlobalValueSummary objects. 5823 Error ModuleSummaryIndexBitcodeReader::parseModule() { 5824 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5825 return Err; 5826 5827 SmallVector<uint64_t, 64> Record; 5828 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 5829 unsigned ValueId = 0; 5830 5831 // Read the index for this module. 5832 while (true) { 5833 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 5834 if (!MaybeEntry) 5835 return MaybeEntry.takeError(); 5836 llvm::BitstreamEntry Entry = MaybeEntry.get(); 5837 5838 switch (Entry.Kind) { 5839 case BitstreamEntry::Error: 5840 return error("Malformed block"); 5841 case BitstreamEntry::EndBlock: 5842 return Error::success(); 5843 5844 case BitstreamEntry::SubBlock: 5845 switch (Entry.ID) { 5846 default: // Skip unknown content. 5847 if (Error Err = Stream.SkipBlock()) 5848 return Err; 5849 break; 5850 case bitc::BLOCKINFO_BLOCK_ID: 5851 // Need to parse these to get abbrev ids (e.g. for VST) 5852 if (readBlockInfo()) 5853 return error("Malformed block"); 5854 break; 5855 case bitc::VALUE_SYMTAB_BLOCK_ID: 5856 // Should have been parsed earlier via VSTOffset, unless there 5857 // is no summary section. 5858 assert(((SeenValueSymbolTable && VSTOffset > 0) || 5859 !SeenGlobalValSummary) && 5860 "Expected early VST parse via VSTOffset record"); 5861 if (Error Err = Stream.SkipBlock()) 5862 return Err; 5863 break; 5864 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 5865 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID: 5866 // Add the module if it is a per-module index (has a source file name). 5867 if (!SourceFileName.empty()) 5868 addThisModule(); 5869 assert(!SeenValueSymbolTable && 5870 "Already read VST when parsing summary block?"); 5871 // We might not have a VST if there were no values in the 5872 // summary. An empty summary block generated when we are 5873 // performing ThinLTO compiles so we don't later invoke 5874 // the regular LTO process on them. 5875 if (VSTOffset > 0) { 5876 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 5877 return Err; 5878 SeenValueSymbolTable = true; 5879 } 5880 SeenGlobalValSummary = true; 5881 if (Error Err = parseEntireSummary(Entry.ID)) 5882 return Err; 5883 break; 5884 case bitc::MODULE_STRTAB_BLOCK_ID: 5885 if (Error Err = parseModuleStringTable()) 5886 return Err; 5887 break; 5888 } 5889 continue; 5890 5891 case BitstreamEntry::Record: { 5892 Record.clear(); 5893 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 5894 if (!MaybeBitCode) 5895 return MaybeBitCode.takeError(); 5896 switch (MaybeBitCode.get()) { 5897 default: 5898 break; // Default behavior, ignore unknown content. 5899 case bitc::MODULE_CODE_VERSION: { 5900 if (Error Err = parseVersionRecord(Record).takeError()) 5901 return Err; 5902 break; 5903 } 5904 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5905 case bitc::MODULE_CODE_SOURCE_FILENAME: { 5906 SmallString<128> ValueName; 5907 if (convertToString(Record, 0, ValueName)) 5908 return error("Invalid record"); 5909 SourceFileName = ValueName.c_str(); 5910 break; 5911 } 5912 /// MODULE_CODE_HASH: [5*i32] 5913 case bitc::MODULE_CODE_HASH: { 5914 if (Record.size() != 5) 5915 return error("Invalid hash length " + Twine(Record.size()).str()); 5916 auto &Hash = getThisModule()->second.second; 5917 int Pos = 0; 5918 for (auto &Val : Record) { 5919 assert(!(Val >> 32) && "Unexpected high bits set"); 5920 Hash[Pos++] = Val; 5921 } 5922 break; 5923 } 5924 /// MODULE_CODE_VSTOFFSET: [offset] 5925 case bitc::MODULE_CODE_VSTOFFSET: 5926 if (Record.empty()) 5927 return error("Invalid record"); 5928 // Note that we subtract 1 here because the offset is relative to one 5929 // word before the start of the identification or module block, which 5930 // was historically always the start of the regular bitcode header. 5931 VSTOffset = Record[0] - 1; 5932 break; 5933 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] 5934 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] 5935 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] 5936 // v2: [strtab offset, strtab size, v1] 5937 case bitc::MODULE_CODE_GLOBALVAR: 5938 case bitc::MODULE_CODE_FUNCTION: 5939 case bitc::MODULE_CODE_ALIAS: { 5940 StringRef Name; 5941 ArrayRef<uint64_t> GVRecord; 5942 std::tie(Name, GVRecord) = readNameFromStrtab(Record); 5943 if (GVRecord.size() <= 3) 5944 return error("Invalid record"); 5945 uint64_t RawLinkage = GVRecord[3]; 5946 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5947 if (!UseStrtab) { 5948 ValueIdToLinkageMap[ValueId++] = Linkage; 5949 break; 5950 } 5951 5952 setValueGUID(ValueId++, Name, Linkage, SourceFileName); 5953 break; 5954 } 5955 } 5956 } 5957 continue; 5958 } 5959 } 5960 } 5961 5962 std::vector<ValueInfo> 5963 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) { 5964 std::vector<ValueInfo> Ret; 5965 Ret.reserve(Record.size()); 5966 for (uint64_t RefValueId : Record) 5967 Ret.push_back(getValueInfoFromValueId(RefValueId).first); 5968 return Ret; 5969 } 5970 5971 std::vector<FunctionSummary::EdgeTy> 5972 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record, 5973 bool IsOldProfileFormat, 5974 bool HasProfile, bool HasRelBF) { 5975 std::vector<FunctionSummary::EdgeTy> Ret; 5976 Ret.reserve(Record.size()); 5977 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 5978 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown; 5979 uint64_t RelBF = 0; 5980 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 5981 if (IsOldProfileFormat) { 5982 I += 1; // Skip old callsitecount field 5983 if (HasProfile) 5984 I += 1; // Skip old profilecount field 5985 } else if (HasProfile) 5986 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 5987 else if (HasRelBF) 5988 RelBF = Record[++I]; 5989 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)}); 5990 } 5991 return Ret; 5992 } 5993 5994 static void 5995 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot, 5996 WholeProgramDevirtResolution &Wpd) { 5997 uint64_t ArgNum = Record[Slot++]; 5998 WholeProgramDevirtResolution::ByArg &B = 5999 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}]; 6000 Slot += ArgNum; 6001 6002 B.TheKind = 6003 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]); 6004 B.Info = Record[Slot++]; 6005 B.Byte = Record[Slot++]; 6006 B.Bit = Record[Slot++]; 6007 } 6008 6009 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record, 6010 StringRef Strtab, size_t &Slot, 6011 TypeIdSummary &TypeId) { 6012 uint64_t Id = Record[Slot++]; 6013 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id]; 6014 6015 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]); 6016 Wpd.SingleImplName = {Strtab.data() + Record[Slot], 6017 static_cast<size_t>(Record[Slot + 1])}; 6018 Slot += 2; 6019 6020 uint64_t ResByArgNum = Record[Slot++]; 6021 for (uint64_t I = 0; I != ResByArgNum; ++I) 6022 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd); 6023 } 6024 6025 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record, 6026 StringRef Strtab, 6027 ModuleSummaryIndex &TheIndex) { 6028 size_t Slot = 0; 6029 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary( 6030 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])}); 6031 Slot += 2; 6032 6033 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]); 6034 TypeId.TTRes.SizeM1BitWidth = Record[Slot++]; 6035 TypeId.TTRes.AlignLog2 = Record[Slot++]; 6036 TypeId.TTRes.SizeM1 = Record[Slot++]; 6037 TypeId.TTRes.BitMask = Record[Slot++]; 6038 TypeId.TTRes.InlineBits = Record[Slot++]; 6039 6040 while (Slot < Record.size()) 6041 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId); 6042 } 6043 6044 std::vector<FunctionSummary::ParamAccess> 6045 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) { 6046 auto ReadRange = [&]() { 6047 APInt Lower(FunctionSummary::ParamAccess::RangeWidth, 6048 BitcodeReader::decodeSignRotatedValue(Record.front())); 6049 Record = Record.drop_front(); 6050 APInt Upper(FunctionSummary::ParamAccess::RangeWidth, 6051 BitcodeReader::decodeSignRotatedValue(Record.front())); 6052 Record = Record.drop_front(); 6053 ConstantRange Range{Lower, Upper}; 6054 assert(!Range.isFullSet()); 6055 assert(!Range.isUpperSignWrapped()); 6056 return Range; 6057 }; 6058 6059 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 6060 while (!Record.empty()) { 6061 PendingParamAccesses.emplace_back(); 6062 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back(); 6063 ParamAccess.ParamNo = Record.front(); 6064 Record = Record.drop_front(); 6065 ParamAccess.Use = ReadRange(); 6066 ParamAccess.Calls.resize(Record.front()); 6067 Record = Record.drop_front(); 6068 for (auto &Call : ParamAccess.Calls) { 6069 Call.ParamNo = Record.front(); 6070 Record = Record.drop_front(); 6071 Call.Callee = getValueInfoFromValueId(Record.front()).first; 6072 Record = Record.drop_front(); 6073 Call.Offsets = ReadRange(); 6074 } 6075 } 6076 return PendingParamAccesses; 6077 } 6078 6079 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo( 6080 ArrayRef<uint64_t> Record, size_t &Slot, 6081 TypeIdCompatibleVtableInfo &TypeId) { 6082 uint64_t Offset = Record[Slot++]; 6083 ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first; 6084 TypeId.push_back({Offset, Callee}); 6085 } 6086 6087 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord( 6088 ArrayRef<uint64_t> Record) { 6089 size_t Slot = 0; 6090 TypeIdCompatibleVtableInfo &TypeId = 6091 TheIndex.getOrInsertTypeIdCompatibleVtableSummary( 6092 {Strtab.data() + Record[Slot], 6093 static_cast<size_t>(Record[Slot + 1])}); 6094 Slot += 2; 6095 6096 while (Slot < Record.size()) 6097 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId); 6098 } 6099 6100 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt, 6101 unsigned WOCnt) { 6102 // Readonly and writeonly refs are in the end of the refs list. 6103 assert(ROCnt + WOCnt <= Refs.size()); 6104 unsigned FirstWORef = Refs.size() - WOCnt; 6105 unsigned RefNo = FirstWORef - ROCnt; 6106 for (; RefNo < FirstWORef; ++RefNo) 6107 Refs[RefNo].setReadOnly(); 6108 for (; RefNo < Refs.size(); ++RefNo) 6109 Refs[RefNo].setWriteOnly(); 6110 } 6111 6112 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 6113 // objects in the index. 6114 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) { 6115 if (Error Err = Stream.EnterSubBlock(ID)) 6116 return Err; 6117 SmallVector<uint64_t, 64> Record; 6118 6119 // Parse version 6120 { 6121 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6122 if (!MaybeEntry) 6123 return MaybeEntry.takeError(); 6124 BitstreamEntry Entry = MaybeEntry.get(); 6125 6126 if (Entry.Kind != BitstreamEntry::Record) 6127 return error("Invalid Summary Block: record for version expected"); 6128 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6129 if (!MaybeRecord) 6130 return MaybeRecord.takeError(); 6131 if (MaybeRecord.get() != bitc::FS_VERSION) 6132 return error("Invalid Summary Block: version expected"); 6133 } 6134 const uint64_t Version = Record[0]; 6135 const bool IsOldProfileFormat = Version == 1; 6136 if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion) 6137 return error("Invalid summary version " + Twine(Version) + 6138 ". Version should be in the range [1-" + 6139 Twine(ModuleSummaryIndex::BitcodeSummaryVersion) + 6140 "]."); 6141 Record.clear(); 6142 6143 // Keep around the last seen summary to be used when we see an optional 6144 // "OriginalName" attachement. 6145 GlobalValueSummary *LastSeenSummary = nullptr; 6146 GlobalValue::GUID LastSeenGUID = 0; 6147 6148 // We can expect to see any number of type ID information records before 6149 // each function summary records; these variables store the information 6150 // collected so far so that it can be used to create the summary object. 6151 std::vector<GlobalValue::GUID> PendingTypeTests; 6152 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls, 6153 PendingTypeCheckedLoadVCalls; 6154 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls, 6155 PendingTypeCheckedLoadConstVCalls; 6156 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses; 6157 6158 while (true) { 6159 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6160 if (!MaybeEntry) 6161 return MaybeEntry.takeError(); 6162 BitstreamEntry Entry = MaybeEntry.get(); 6163 6164 switch (Entry.Kind) { 6165 case BitstreamEntry::SubBlock: // Handled for us already. 6166 case BitstreamEntry::Error: 6167 return error("Malformed block"); 6168 case BitstreamEntry::EndBlock: 6169 return Error::success(); 6170 case BitstreamEntry::Record: 6171 // The interesting case. 6172 break; 6173 } 6174 6175 // Read a record. The record format depends on whether this 6176 // is a per-module index or a combined index file. In the per-module 6177 // case the records contain the associated value's ID for correlation 6178 // with VST entries. In the combined index the correlation is done 6179 // via the bitcode offset of the summary records (which were saved 6180 // in the combined index VST entries). The records also contain 6181 // information used for ThinLTO renaming and importing. 6182 Record.clear(); 6183 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6184 if (!MaybeBitCode) 6185 return MaybeBitCode.takeError(); 6186 switch (unsigned BitCode = MaybeBitCode.get()) { 6187 default: // Default behavior: ignore. 6188 break; 6189 case bitc::FS_FLAGS: { // [flags] 6190 TheIndex.setFlags(Record[0]); 6191 break; 6192 } 6193 case bitc::FS_VALUE_GUID: { // [valueid, refguid] 6194 uint64_t ValueID = Record[0]; 6195 GlobalValue::GUID RefGUID = Record[1]; 6196 ValueIdToValueInfoMap[ValueID] = 6197 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID); 6198 break; 6199 } 6200 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs, 6201 // numrefs x valueid, n x (valueid)] 6202 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs, 6203 // numrefs x valueid, 6204 // n x (valueid, hotness)] 6205 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs, 6206 // numrefs x valueid, 6207 // n x (valueid, relblockfreq)] 6208 case bitc::FS_PERMODULE: 6209 case bitc::FS_PERMODULE_RELBF: 6210 case bitc::FS_PERMODULE_PROFILE: { 6211 unsigned ValueID = Record[0]; 6212 uint64_t RawFlags = Record[1]; 6213 unsigned InstCount = Record[2]; 6214 uint64_t RawFunFlags = 0; 6215 unsigned NumRefs = Record[3]; 6216 unsigned NumRORefs = 0, NumWORefs = 0; 6217 int RefListStartIndex = 4; 6218 if (Version >= 4) { 6219 RawFunFlags = Record[3]; 6220 NumRefs = Record[4]; 6221 RefListStartIndex = 5; 6222 if (Version >= 5) { 6223 NumRORefs = Record[5]; 6224 RefListStartIndex = 6; 6225 if (Version >= 7) { 6226 NumWORefs = Record[6]; 6227 RefListStartIndex = 7; 6228 } 6229 } 6230 } 6231 6232 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6233 // The module path string ref set in the summary must be owned by the 6234 // index's module string table. Since we don't have a module path 6235 // string table section in the per-module index, we create a single 6236 // module path string table entry with an empty (0) ID to take 6237 // ownership. 6238 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6239 assert(Record.size() >= RefListStartIndex + NumRefs && 6240 "Record size inconsistent with number of references"); 6241 std::vector<ValueInfo> Refs = makeRefList( 6242 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6243 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 6244 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF); 6245 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList( 6246 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 6247 IsOldProfileFormat, HasProfile, HasRelBF); 6248 setSpecialRefs(Refs, NumRORefs, NumWORefs); 6249 auto FS = std::make_unique<FunctionSummary>( 6250 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0, 6251 std::move(Refs), std::move(Calls), std::move(PendingTypeTests), 6252 std::move(PendingTypeTestAssumeVCalls), 6253 std::move(PendingTypeCheckedLoadVCalls), 6254 std::move(PendingTypeTestAssumeConstVCalls), 6255 std::move(PendingTypeCheckedLoadConstVCalls), 6256 std::move(PendingParamAccesses)); 6257 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID); 6258 FS->setModulePath(getThisModule()->first()); 6259 FS->setOriginalName(VIAndOriginalGUID.second); 6260 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS)); 6261 break; 6262 } 6263 // FS_ALIAS: [valueid, flags, valueid] 6264 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 6265 // they expect all aliasee summaries to be available. 6266 case bitc::FS_ALIAS: { 6267 unsigned ValueID = Record[0]; 6268 uint64_t RawFlags = Record[1]; 6269 unsigned AliaseeID = Record[2]; 6270 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6271 auto AS = std::make_unique<AliasSummary>(Flags); 6272 // The module path string ref set in the summary must be owned by the 6273 // index's module string table. Since we don't have a module path 6274 // string table section in the per-module index, we create a single 6275 // module path string table entry with an empty (0) ID to take 6276 // ownership. 6277 AS->setModulePath(getThisModule()->first()); 6278 6279 auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; 6280 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); 6281 if (!AliaseeInModule) 6282 return error("Alias expects aliasee summary to be parsed"); 6283 AS->setAliasee(AliaseeVI, AliaseeInModule); 6284 6285 auto GUID = getValueInfoFromValueId(ValueID); 6286 AS->setOriginalName(GUID.second); 6287 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS)); 6288 break; 6289 } 6290 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid] 6291 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 6292 unsigned ValueID = Record[0]; 6293 uint64_t RawFlags = Record[1]; 6294 unsigned RefArrayStart = 2; 6295 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 6296 /* WriteOnly */ false, 6297 /* Constant */ false, 6298 GlobalObject::VCallVisibilityPublic); 6299 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6300 if (Version >= 5) { 6301 GVF = getDecodedGVarFlags(Record[2]); 6302 RefArrayStart = 3; 6303 } 6304 std::vector<ValueInfo> Refs = 6305 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 6306 auto FS = 6307 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6308 FS->setModulePath(getThisModule()->first()); 6309 auto GUID = getValueInfoFromValueId(ValueID); 6310 FS->setOriginalName(GUID.second); 6311 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS)); 6312 break; 6313 } 6314 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, 6315 // numrefs, numrefs x valueid, 6316 // n x (valueid, offset)] 6317 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: { 6318 unsigned ValueID = Record[0]; 6319 uint64_t RawFlags = Record[1]; 6320 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]); 6321 unsigned NumRefs = Record[3]; 6322 unsigned RefListStartIndex = 4; 6323 unsigned VTableListStartIndex = RefListStartIndex + NumRefs; 6324 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6325 std::vector<ValueInfo> Refs = makeRefList( 6326 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6327 VTableFuncList VTableFuncs; 6328 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) { 6329 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first; 6330 uint64_t Offset = Record[++I]; 6331 VTableFuncs.push_back({Callee, Offset}); 6332 } 6333 auto VS = 6334 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6335 VS->setModulePath(getThisModule()->first()); 6336 VS->setVTableFuncs(VTableFuncs); 6337 auto GUID = getValueInfoFromValueId(ValueID); 6338 VS->setOriginalName(GUID.second); 6339 TheIndex.addGlobalValueSummary(GUID.first, std::move(VS)); 6340 break; 6341 } 6342 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs, 6343 // numrefs x valueid, n x (valueid)] 6344 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs, 6345 // numrefs x valueid, n x (valueid, hotness)] 6346 case bitc::FS_COMBINED: 6347 case bitc::FS_COMBINED_PROFILE: { 6348 unsigned ValueID = Record[0]; 6349 uint64_t ModuleId = Record[1]; 6350 uint64_t RawFlags = Record[2]; 6351 unsigned InstCount = Record[3]; 6352 uint64_t RawFunFlags = 0; 6353 uint64_t EntryCount = 0; 6354 unsigned NumRefs = Record[4]; 6355 unsigned NumRORefs = 0, NumWORefs = 0; 6356 int RefListStartIndex = 5; 6357 6358 if (Version >= 4) { 6359 RawFunFlags = Record[4]; 6360 RefListStartIndex = 6; 6361 size_t NumRefsIndex = 5; 6362 if (Version >= 5) { 6363 unsigned NumRORefsOffset = 1; 6364 RefListStartIndex = 7; 6365 if (Version >= 6) { 6366 NumRefsIndex = 6; 6367 EntryCount = Record[5]; 6368 RefListStartIndex = 8; 6369 if (Version >= 7) { 6370 RefListStartIndex = 9; 6371 NumWORefs = Record[8]; 6372 NumRORefsOffset = 2; 6373 } 6374 } 6375 NumRORefs = Record[RefListStartIndex - NumRORefsOffset]; 6376 } 6377 NumRefs = Record[NumRefsIndex]; 6378 } 6379 6380 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6381 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6382 assert(Record.size() >= RefListStartIndex + NumRefs && 6383 "Record size inconsistent with number of references"); 6384 std::vector<ValueInfo> Refs = makeRefList( 6385 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs)); 6386 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 6387 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList( 6388 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex), 6389 IsOldProfileFormat, HasProfile, false); 6390 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6391 setSpecialRefs(Refs, NumRORefs, NumWORefs); 6392 auto FS = std::make_unique<FunctionSummary>( 6393 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount, 6394 std::move(Refs), std::move(Edges), std::move(PendingTypeTests), 6395 std::move(PendingTypeTestAssumeVCalls), 6396 std::move(PendingTypeCheckedLoadVCalls), 6397 std::move(PendingTypeTestAssumeConstVCalls), 6398 std::move(PendingTypeCheckedLoadConstVCalls), 6399 std::move(PendingParamAccesses)); 6400 LastSeenSummary = FS.get(); 6401 LastSeenGUID = VI.getGUID(); 6402 FS->setModulePath(ModuleIdMap[ModuleId]); 6403 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 6404 break; 6405 } 6406 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 6407 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 6408 // they expect all aliasee summaries to be available. 6409 case bitc::FS_COMBINED_ALIAS: { 6410 unsigned ValueID = Record[0]; 6411 uint64_t ModuleId = Record[1]; 6412 uint64_t RawFlags = Record[2]; 6413 unsigned AliaseeValueId = Record[3]; 6414 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6415 auto AS = std::make_unique<AliasSummary>(Flags); 6416 LastSeenSummary = AS.get(); 6417 AS->setModulePath(ModuleIdMap[ModuleId]); 6418 6419 auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; 6420 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); 6421 AS->setAliasee(AliaseeVI, AliaseeInModule); 6422 6423 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6424 LastSeenGUID = VI.getGUID(); 6425 TheIndex.addGlobalValueSummary(VI, std::move(AS)); 6426 break; 6427 } 6428 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 6429 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 6430 unsigned ValueID = Record[0]; 6431 uint64_t ModuleId = Record[1]; 6432 uint64_t RawFlags = Record[2]; 6433 unsigned RefArrayStart = 3; 6434 GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false, 6435 /* WriteOnly */ false, 6436 /* Constant */ false, 6437 GlobalObject::VCallVisibilityPublic); 6438 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6439 if (Version >= 5) { 6440 GVF = getDecodedGVarFlags(Record[3]); 6441 RefArrayStart = 4; 6442 } 6443 std::vector<ValueInfo> Refs = 6444 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart)); 6445 auto FS = 6446 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs)); 6447 LastSeenSummary = FS.get(); 6448 FS->setModulePath(ModuleIdMap[ModuleId]); 6449 ValueInfo VI = getValueInfoFromValueId(ValueID).first; 6450 LastSeenGUID = VI.getGUID(); 6451 TheIndex.addGlobalValueSummary(VI, std::move(FS)); 6452 break; 6453 } 6454 // FS_COMBINED_ORIGINAL_NAME: [original_name] 6455 case bitc::FS_COMBINED_ORIGINAL_NAME: { 6456 uint64_t OriginalName = Record[0]; 6457 if (!LastSeenSummary) 6458 return error("Name attachment that does not follow a combined record"); 6459 LastSeenSummary->setOriginalName(OriginalName); 6460 TheIndex.addOriginalName(LastSeenGUID, OriginalName); 6461 // Reset the LastSeenSummary 6462 LastSeenSummary = nullptr; 6463 LastSeenGUID = 0; 6464 break; 6465 } 6466 case bitc::FS_TYPE_TESTS: 6467 assert(PendingTypeTests.empty()); 6468 llvm::append_range(PendingTypeTests, Record); 6469 break; 6470 6471 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: 6472 assert(PendingTypeTestAssumeVCalls.empty()); 6473 for (unsigned I = 0; I != Record.size(); I += 2) 6474 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); 6475 break; 6476 6477 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: 6478 assert(PendingTypeCheckedLoadVCalls.empty()); 6479 for (unsigned I = 0; I != Record.size(); I += 2) 6480 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); 6481 break; 6482 6483 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: 6484 PendingTypeTestAssumeConstVCalls.push_back( 6485 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 6486 break; 6487 6488 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: 6489 PendingTypeCheckedLoadConstVCalls.push_back( 6490 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}}); 6491 break; 6492 6493 case bitc::FS_CFI_FUNCTION_DEFS: { 6494 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs(); 6495 for (unsigned I = 0; I != Record.size(); I += 2) 6496 CfiFunctionDefs.insert( 6497 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 6498 break; 6499 } 6500 6501 case bitc::FS_CFI_FUNCTION_DECLS: { 6502 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls(); 6503 for (unsigned I = 0; I != Record.size(); I += 2) 6504 CfiFunctionDecls.insert( 6505 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])}); 6506 break; 6507 } 6508 6509 case bitc::FS_TYPE_ID: 6510 parseTypeIdSummaryRecord(Record, Strtab, TheIndex); 6511 break; 6512 6513 case bitc::FS_TYPE_ID_METADATA: 6514 parseTypeIdCompatibleVtableSummaryRecord(Record); 6515 break; 6516 6517 case bitc::FS_BLOCK_COUNT: 6518 TheIndex.addBlockCount(Record[0]); 6519 break; 6520 6521 case bitc::FS_PARAM_ACCESS: { 6522 PendingParamAccesses = parseParamAccesses(Record); 6523 break; 6524 } 6525 } 6526 } 6527 llvm_unreachable("Exit infinite loop"); 6528 } 6529 6530 // Parse the module string table block into the Index. 6531 // This populates the ModulePathStringTable map in the index. 6532 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 6533 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 6534 return Err; 6535 6536 SmallVector<uint64_t, 64> Record; 6537 6538 SmallString<128> ModulePath; 6539 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr; 6540 6541 while (true) { 6542 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6543 if (!MaybeEntry) 6544 return MaybeEntry.takeError(); 6545 BitstreamEntry Entry = MaybeEntry.get(); 6546 6547 switch (Entry.Kind) { 6548 case BitstreamEntry::SubBlock: // Handled for us already. 6549 case BitstreamEntry::Error: 6550 return error("Malformed block"); 6551 case BitstreamEntry::EndBlock: 6552 return Error::success(); 6553 case BitstreamEntry::Record: 6554 // The interesting case. 6555 break; 6556 } 6557 6558 Record.clear(); 6559 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record); 6560 if (!MaybeRecord) 6561 return MaybeRecord.takeError(); 6562 switch (MaybeRecord.get()) { 6563 default: // Default behavior: ignore. 6564 break; 6565 case bitc::MST_CODE_ENTRY: { 6566 // MST_ENTRY: [modid, namechar x N] 6567 uint64_t ModuleId = Record[0]; 6568 6569 if (convertToString(Record, 1, ModulePath)) 6570 return error("Invalid record"); 6571 6572 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId); 6573 ModuleIdMap[ModuleId] = LastSeenModule->first(); 6574 6575 ModulePath.clear(); 6576 break; 6577 } 6578 /// MST_CODE_HASH: [5*i32] 6579 case bitc::MST_CODE_HASH: { 6580 if (Record.size() != 5) 6581 return error("Invalid hash length " + Twine(Record.size()).str()); 6582 if (!LastSeenModule) 6583 return error("Invalid hash that does not follow a module path"); 6584 int Pos = 0; 6585 for (auto &Val : Record) { 6586 assert(!(Val >> 32) && "Unexpected high bits set"); 6587 LastSeenModule->second.second[Pos++] = Val; 6588 } 6589 // Reset LastSeenModule to avoid overriding the hash unexpectedly. 6590 LastSeenModule = nullptr; 6591 break; 6592 } 6593 } 6594 } 6595 llvm_unreachable("Exit infinite loop"); 6596 } 6597 6598 namespace { 6599 6600 // FIXME: This class is only here to support the transition to llvm::Error. It 6601 // will be removed once this transition is complete. Clients should prefer to 6602 // deal with the Error value directly, rather than converting to error_code. 6603 class BitcodeErrorCategoryType : public std::error_category { 6604 const char *name() const noexcept override { 6605 return "llvm.bitcode"; 6606 } 6607 6608 std::string message(int IE) const override { 6609 BitcodeError E = static_cast<BitcodeError>(IE); 6610 switch (E) { 6611 case BitcodeError::CorruptedBitcode: 6612 return "Corrupted bitcode"; 6613 } 6614 llvm_unreachable("Unknown error type!"); 6615 } 6616 }; 6617 6618 } // end anonymous namespace 6619 6620 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6621 6622 const std::error_category &llvm::BitcodeErrorCategory() { 6623 return *ErrorCategory; 6624 } 6625 6626 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream, 6627 unsigned Block, unsigned RecordID) { 6628 if (Error Err = Stream.EnterSubBlock(Block)) 6629 return std::move(Err); 6630 6631 StringRef Strtab; 6632 while (true) { 6633 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6634 if (!MaybeEntry) 6635 return MaybeEntry.takeError(); 6636 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6637 6638 switch (Entry.Kind) { 6639 case BitstreamEntry::EndBlock: 6640 return Strtab; 6641 6642 case BitstreamEntry::Error: 6643 return error("Malformed block"); 6644 6645 case BitstreamEntry::SubBlock: 6646 if (Error Err = Stream.SkipBlock()) 6647 return std::move(Err); 6648 break; 6649 6650 case BitstreamEntry::Record: 6651 StringRef Blob; 6652 SmallVector<uint64_t, 1> Record; 6653 Expected<unsigned> MaybeRecord = 6654 Stream.readRecord(Entry.ID, Record, &Blob); 6655 if (!MaybeRecord) 6656 return MaybeRecord.takeError(); 6657 if (MaybeRecord.get() == RecordID) 6658 Strtab = Blob; 6659 break; 6660 } 6661 } 6662 } 6663 6664 //===----------------------------------------------------------------------===// 6665 // External interface 6666 //===----------------------------------------------------------------------===// 6667 6668 Expected<std::vector<BitcodeModule>> 6669 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) { 6670 auto FOrErr = getBitcodeFileContents(Buffer); 6671 if (!FOrErr) 6672 return FOrErr.takeError(); 6673 return std::move(FOrErr->Mods); 6674 } 6675 6676 Expected<BitcodeFileContents> 6677 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) { 6678 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 6679 if (!StreamOrErr) 6680 return StreamOrErr.takeError(); 6681 BitstreamCursor &Stream = *StreamOrErr; 6682 6683 BitcodeFileContents F; 6684 while (true) { 6685 uint64_t BCBegin = Stream.getCurrentByteNo(); 6686 6687 // We may be consuming bitcode from a client that leaves garbage at the end 6688 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to 6689 // the end that there cannot possibly be another module, stop looking. 6690 if (BCBegin + 8 >= Stream.getBitcodeBytes().size()) 6691 return F; 6692 6693 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6694 if (!MaybeEntry) 6695 return MaybeEntry.takeError(); 6696 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6697 6698 switch (Entry.Kind) { 6699 case BitstreamEntry::EndBlock: 6700 case BitstreamEntry::Error: 6701 return error("Malformed block"); 6702 6703 case BitstreamEntry::SubBlock: { 6704 uint64_t IdentificationBit = -1ull; 6705 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 6706 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8; 6707 if (Error Err = Stream.SkipBlock()) 6708 return std::move(Err); 6709 6710 { 6711 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6712 if (!MaybeEntry) 6713 return MaybeEntry.takeError(); 6714 Entry = MaybeEntry.get(); 6715 } 6716 6717 if (Entry.Kind != BitstreamEntry::SubBlock || 6718 Entry.ID != bitc::MODULE_BLOCK_ID) 6719 return error("Malformed block"); 6720 } 6721 6722 if (Entry.ID == bitc::MODULE_BLOCK_ID) { 6723 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8; 6724 if (Error Err = Stream.SkipBlock()) 6725 return std::move(Err); 6726 6727 F.Mods.push_back({Stream.getBitcodeBytes().slice( 6728 BCBegin, Stream.getCurrentByteNo() - BCBegin), 6729 Buffer.getBufferIdentifier(), IdentificationBit, 6730 ModuleBit}); 6731 continue; 6732 } 6733 6734 if (Entry.ID == bitc::STRTAB_BLOCK_ID) { 6735 Expected<StringRef> Strtab = 6736 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB); 6737 if (!Strtab) 6738 return Strtab.takeError(); 6739 // This string table is used by every preceding bitcode module that does 6740 // not have its own string table. A bitcode file may have multiple 6741 // string tables if it was created by binary concatenation, for example 6742 // with "llvm-cat -b". 6743 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) { 6744 if (!I->Strtab.empty()) 6745 break; 6746 I->Strtab = *Strtab; 6747 } 6748 // Similarly, the string table is used by every preceding symbol table; 6749 // normally there will be just one unless the bitcode file was created 6750 // by binary concatenation. 6751 if (!F.Symtab.empty() && F.StrtabForSymtab.empty()) 6752 F.StrtabForSymtab = *Strtab; 6753 continue; 6754 } 6755 6756 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) { 6757 Expected<StringRef> SymtabOrErr = 6758 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB); 6759 if (!SymtabOrErr) 6760 return SymtabOrErr.takeError(); 6761 6762 // We can expect the bitcode file to have multiple symbol tables if it 6763 // was created by binary concatenation. In that case we silently 6764 // ignore any subsequent symbol tables, which is fine because this is a 6765 // low level function. The client is expected to notice that the number 6766 // of modules in the symbol table does not match the number of modules 6767 // in the input file and regenerate the symbol table. 6768 if (F.Symtab.empty()) 6769 F.Symtab = *SymtabOrErr; 6770 continue; 6771 } 6772 6773 if (Error Err = Stream.SkipBlock()) 6774 return std::move(Err); 6775 continue; 6776 } 6777 case BitstreamEntry::Record: 6778 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 6779 continue; 6780 else 6781 return StreamFailed.takeError(); 6782 } 6783 } 6784 } 6785 6786 /// Get a lazy one-at-time loading module from bitcode. 6787 /// 6788 /// This isn't always used in a lazy context. In particular, it's also used by 6789 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull 6790 /// in forward-referenced functions from block address references. 6791 /// 6792 /// \param[in] MaterializeAll Set to \c true if we should materialize 6793 /// everything. 6794 Expected<std::unique_ptr<Module>> 6795 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll, 6796 bool ShouldLazyLoadMetadata, bool IsImporting, 6797 DataLayoutCallbackTy DataLayoutCallback) { 6798 BitstreamCursor Stream(Buffer); 6799 6800 std::string ProducerIdentification; 6801 if (IdentificationBit != -1ull) { 6802 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit)) 6803 return std::move(JumpFailed); 6804 Expected<std::string> ProducerIdentificationOrErr = 6805 readIdentificationBlock(Stream); 6806 if (!ProducerIdentificationOrErr) 6807 return ProducerIdentificationOrErr.takeError(); 6808 6809 ProducerIdentification = *ProducerIdentificationOrErr; 6810 } 6811 6812 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6813 return std::move(JumpFailed); 6814 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification, 6815 Context); 6816 6817 std::unique_ptr<Module> M = 6818 std::make_unique<Module>(ModuleIdentifier, Context); 6819 M->setMaterializer(R); 6820 6821 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6822 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, 6823 IsImporting, DataLayoutCallback)) 6824 return std::move(Err); 6825 6826 if (MaterializeAll) { 6827 // Read in the entire module, and destroy the BitcodeReader. 6828 if (Error Err = M->materializeAll()) 6829 return std::move(Err); 6830 } else { 6831 // Resolve forward references from blockaddresses. 6832 if (Error Err = R->materializeForwardReferencedFunctions()) 6833 return std::move(Err); 6834 } 6835 return std::move(M); 6836 } 6837 6838 Expected<std::unique_ptr<Module>> 6839 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, 6840 bool IsImporting) { 6841 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting, 6842 [](StringRef) { return None; }); 6843 } 6844 6845 // Parse the specified bitcode buffer and merge the index into CombinedIndex. 6846 // We don't use ModuleIdentifier here because the client may need to control the 6847 // module path used in the combined summary (e.g. when reading summaries for 6848 // regular LTO modules). 6849 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex, 6850 StringRef ModulePath, uint64_t ModuleId) { 6851 BitstreamCursor Stream(Buffer); 6852 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6853 return JumpFailed; 6854 6855 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex, 6856 ModulePath, ModuleId); 6857 return R.parseModule(); 6858 } 6859 6860 // Parse the specified bitcode buffer, returning the function info index. 6861 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() { 6862 BitstreamCursor Stream(Buffer); 6863 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6864 return std::move(JumpFailed); 6865 6866 auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 6867 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index, 6868 ModuleIdentifier, 0); 6869 6870 if (Error Err = R.parseModule()) 6871 return std::move(Err); 6872 6873 return std::move(Index); 6874 } 6875 6876 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream, 6877 unsigned ID) { 6878 if (Error Err = Stream.EnterSubBlock(ID)) 6879 return std::move(Err); 6880 SmallVector<uint64_t, 64> Record; 6881 6882 while (true) { 6883 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks(); 6884 if (!MaybeEntry) 6885 return MaybeEntry.takeError(); 6886 BitstreamEntry Entry = MaybeEntry.get(); 6887 6888 switch (Entry.Kind) { 6889 case BitstreamEntry::SubBlock: // Handled for us already. 6890 case BitstreamEntry::Error: 6891 return error("Malformed block"); 6892 case BitstreamEntry::EndBlock: 6893 // If no flags record found, conservatively return true to mimic 6894 // behavior before this flag was added. 6895 return true; 6896 case BitstreamEntry::Record: 6897 // The interesting case. 6898 break; 6899 } 6900 6901 // Look for the FS_FLAGS record. 6902 Record.clear(); 6903 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record); 6904 if (!MaybeBitCode) 6905 return MaybeBitCode.takeError(); 6906 switch (MaybeBitCode.get()) { 6907 default: // Default behavior: ignore. 6908 break; 6909 case bitc::FS_FLAGS: { // [flags] 6910 uint64_t Flags = Record[0]; 6911 // Scan flags. 6912 assert(Flags <= 0x7f && "Unexpected bits in flag"); 6913 6914 return Flags & 0x8; 6915 } 6916 } 6917 } 6918 llvm_unreachable("Exit infinite loop"); 6919 } 6920 6921 // Check if the given bitcode buffer contains a global value summary block. 6922 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() { 6923 BitstreamCursor Stream(Buffer); 6924 if (Error JumpFailed = Stream.JumpToBit(ModuleBit)) 6925 return std::move(JumpFailed); 6926 6927 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6928 return std::move(Err); 6929 6930 while (true) { 6931 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance(); 6932 if (!MaybeEntry) 6933 return MaybeEntry.takeError(); 6934 llvm::BitstreamEntry Entry = MaybeEntry.get(); 6935 6936 switch (Entry.Kind) { 6937 case BitstreamEntry::Error: 6938 return error("Malformed block"); 6939 case BitstreamEntry::EndBlock: 6940 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false, 6941 /*EnableSplitLTOUnit=*/false}; 6942 6943 case BitstreamEntry::SubBlock: 6944 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 6945 Expected<bool> EnableSplitLTOUnit = 6946 getEnableSplitLTOUnitFlag(Stream, Entry.ID); 6947 if (!EnableSplitLTOUnit) 6948 return EnableSplitLTOUnit.takeError(); 6949 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true, 6950 *EnableSplitLTOUnit}; 6951 } 6952 6953 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) { 6954 Expected<bool> EnableSplitLTOUnit = 6955 getEnableSplitLTOUnitFlag(Stream, Entry.ID); 6956 if (!EnableSplitLTOUnit) 6957 return EnableSplitLTOUnit.takeError(); 6958 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true, 6959 *EnableSplitLTOUnit}; 6960 } 6961 6962 // Ignore other sub-blocks. 6963 if (Error Err = Stream.SkipBlock()) 6964 return std::move(Err); 6965 continue; 6966 6967 case BitstreamEntry::Record: 6968 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID)) 6969 continue; 6970 else 6971 return StreamFailed.takeError(); 6972 } 6973 } 6974 } 6975 6976 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) { 6977 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer); 6978 if (!MsOrErr) 6979 return MsOrErr.takeError(); 6980 6981 if (MsOrErr->size() != 1) 6982 return error("Expected a single module"); 6983 6984 return (*MsOrErr)[0]; 6985 } 6986 6987 Expected<std::unique_ptr<Module>> 6988 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, 6989 bool ShouldLazyLoadMetadata, bool IsImporting) { 6990 Expected<BitcodeModule> BM = getSingleModule(Buffer); 6991 if (!BM) 6992 return BM.takeError(); 6993 6994 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting); 6995 } 6996 6997 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule( 6998 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context, 6999 bool ShouldLazyLoadMetadata, bool IsImporting) { 7000 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata, 7001 IsImporting); 7002 if (MOrErr) 7003 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 7004 return MOrErr; 7005 } 7006 7007 Expected<std::unique_ptr<Module>> 7008 BitcodeModule::parseModule(LLVMContext &Context, 7009 DataLayoutCallbackTy DataLayoutCallback) { 7010 return getModuleImpl(Context, true, false, false, DataLayoutCallback); 7011 // TODO: Restore the use-lists to the in-memory state when the bitcode was 7012 // written. We must defer until the Module has been fully materialized. 7013 } 7014 7015 Expected<std::unique_ptr<Module>> 7016 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 7017 DataLayoutCallbackTy DataLayoutCallback) { 7018 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7019 if (!BM) 7020 return BM.takeError(); 7021 7022 return BM->parseModule(Context, DataLayoutCallback); 7023 } 7024 7025 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) { 7026 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7027 if (!StreamOrErr) 7028 return StreamOrErr.takeError(); 7029 7030 return readTriple(*StreamOrErr); 7031 } 7032 7033 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) { 7034 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7035 if (!StreamOrErr) 7036 return StreamOrErr.takeError(); 7037 7038 return hasObjCCategory(*StreamOrErr); 7039 } 7040 7041 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) { 7042 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer); 7043 if (!StreamOrErr) 7044 return StreamOrErr.takeError(); 7045 7046 return readIdentificationCode(*StreamOrErr); 7047 } 7048 7049 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer, 7050 ModuleSummaryIndex &CombinedIndex, 7051 uint64_t ModuleId) { 7052 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7053 if (!BM) 7054 return BM.takeError(); 7055 7056 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId); 7057 } 7058 7059 Expected<std::unique_ptr<ModuleSummaryIndex>> 7060 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) { 7061 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7062 if (!BM) 7063 return BM.takeError(); 7064 7065 return BM->getSummary(); 7066 } 7067 7068 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) { 7069 Expected<BitcodeModule> BM = getSingleModule(Buffer); 7070 if (!BM) 7071 return BM.takeError(); 7072 7073 return BM->getLTOInfo(); 7074 } 7075 7076 Expected<std::unique_ptr<ModuleSummaryIndex>> 7077 llvm::getModuleSummaryIndexForFile(StringRef Path, 7078 bool IgnoreEmptyThinLTOIndexFile) { 7079 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 7080 MemoryBuffer::getFileOrSTDIN(Path); 7081 if (!FileOrErr) 7082 return errorCodeToError(FileOrErr.getError()); 7083 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize()) 7084 return nullptr; 7085 return getModuleSummaryIndex(**FileOrErr); 7086 } 7087