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