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