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