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