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