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