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