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