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