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