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