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