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