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