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