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