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