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