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