[llvm] Use StringRef::operator== instead of StringRef::equals (NFC) (#91441)

I'm planning to remove StringRef::equals in favor of
StringRef::operator==.

- StringRef::operator==/!= outnumber StringRef::equals by a factor of
  70 under llvm/ in terms of their usage.

- The elimination of StringRef::equals brings StringRef closer to
  std::string_view, which has operator== but not equals.

- S == "foo" is more readable than S.equals("foo"), especially for
  !Long.Expression.equals("str") vs Long.Expression != "str".
This commit is contained in:
Kazu Hirata 2024-05-08 10:33:53 -07:00 committed by GitHub
parent 46435ac19e
commit bb6df0804b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
34 changed files with 79 additions and 80 deletions

View File

@ -89,7 +89,7 @@ public:
/// Check for string equality. This is more efficient than compare() when
/// the relative ordering of inequal strings isn't needed.
[[nodiscard]] bool equals(StringRef RHS) const { return str().equals(RHS); }
[[nodiscard]] bool equals(StringRef RHS) const { return str() == RHS; }
/// Check for string equality, ignoring case.
[[nodiscard]] bool equals_insensitive(StringRef RHS) const {

View File

@ -6896,7 +6896,7 @@ Error BitcodeReader::materialize(GlobalValue *GV) {
MDString *MDS = cast<MDString>(MD->getOperand(0));
StringRef ProfName = MDS->getString();
// Check consistency of !prof branch_weights metadata.
if (!ProfName.equals("branch_weights"))
if (ProfName != "branch_weights")
continue;
unsigned ExpectedNumOperands = 0;
if (BranchInst *BI = dyn_cast<BranchInst>(&I))

View File

@ -659,7 +659,7 @@ void RuntimeDyldELF::setMipsABI(const ObjectFile &Obj) {
IsMipsO32ABI = AbiVariant & ELF::EF_MIPS_ABI_O32;
IsMipsN32ABI = AbiVariant & ELF::EF_MIPS_ABI2;
}
IsMipsN64ABI = Obj.getFileFormatName().equals("elf64-mips");
IsMipsN64ABI = Obj.getFileFormatName() == "elf64-mips";
}
// Return the .TOC. section and offset.

View File

@ -374,7 +374,7 @@ Expected<NumericVariable *> Pattern::parseNumericVariableDefinition(
Expected<std::unique_ptr<NumericVariableUse>> Pattern::parseNumericVariableUse(
StringRef Name, bool IsPseudo, std::optional<size_t> LineNumber,
FileCheckPatternContext *Context, const SourceMgr &SM) {
if (IsPseudo && !Name.equals("@LINE"))
if (IsPseudo && Name != "@LINE")
return ErrorDiagnostic::get(
SM, Name, "invalid pseudo numeric variable '" + Name + "'");

View File

@ -21,7 +21,7 @@ void llvm::parseFuzzerCLOpts(int ArgC, char *ArgV[]) {
int I = 1;
while (I < ArgC)
if (StringRef(ArgV[I++]).equals("-ignore_remaining_args=1"))
if (StringRef(ArgV[I++]) == "-ignore_remaining_args=1")
break;
while (I < ArgC)
CLArgs.push_back(ArgV[I++]);
@ -39,7 +39,7 @@ void llvm::handleExecNameEncodedBEOpts(StringRef ExecName) {
SmallVector<StringRef, 4> Opts;
NameAndArgs.second.split(Opts, '-');
for (StringRef Opt : Opts) {
if (Opt.equals("gisel")) {
if (Opt == "gisel") {
Args.push_back("-global-isel");
// For now we default GlobalISel to -O0
Args.push_back("-O0");
@ -151,7 +151,7 @@ int llvm::runFuzzerOnInputs(int ArgC, char *ArgV[], FuzzerTestFun TestOne,
for (int I = 1; I < ArgC; ++I) {
StringRef Arg(ArgV[I]);
if (Arg.starts_with("-")) {
if (Arg.equals("-ignore_remaining_args=1"))
if (Arg == "-ignore_remaining_args=1")
break;
continue;
}

View File

@ -694,7 +694,7 @@ bool LTOModule::hasCtorDtor() const {
if (auto *GV = dyn_cast_if_present<GlobalValue *>(Sym)) {
StringRef Name = GV->getName();
if (Name.consume_front("llvm.global_")) {
if (Name.equals("ctors") || Name.equals("dtors"))
if (Name == "ctors" || Name == "dtors")
return true;
}
}

View File

@ -468,7 +468,7 @@ void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) {
void MCAsmStreamer::addExplicitComment(const Twine &T) {
StringRef c = T.getSingleStringRef();
if (c.equals(StringRef(MAI->getSeparatorString())))
if (c == MAI->getSeparatorString())
return;
if (c.starts_with(StringRef("//"))) {
ExplicitCommentToEmit.append("\t");

View File

@ -4543,7 +4543,7 @@ bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
// Emit an error if two (or more) named parameters share the same name
for (const MCAsmMacroParameter& CurrParam : Parameters)
if (CurrParam.Name.equals(Parameter.Name))
if (CurrParam.Name == Parameter.Name)
return TokError("macro '" + Name + "' has multiple parameters"
" named '" + Parameter.Name + "'");

View File

@ -705,7 +705,7 @@ bool DarwinAsmParser::parseDirectiveSection(StringRef, SMLoc) {
.Case("__datacoal_nt", "__data")
.Default(Section);
if (!Section.equals(NonCoalSection)) {
if (Section != NonCoalSection) {
StringRef SectionVal(Loc.getPointer());
size_t B = SectionVal.find(',') + 1, E = SectionVal.find(',', B);
SMLoc BLoc = SMLoc::getFromPointer(SectionVal.data() + B);

View File

@ -13,7 +13,7 @@ using namespace llvm;
MCSectionXCOFF *MCSymbolXCOFF::getRepresentedCsect() const {
assert(RepresentedCsect &&
"Trying to get csect representation of this symbol but none was set.");
assert(getSymbolTableName().equals(RepresentedCsect->getSymbolTableName()) &&
assert(getSymbolTableName() == RepresentedCsect->getSymbolTableName() &&
"SymbolTableNames need to be the same for this symbol and its csect "
"representation.");
return RepresentedCsect;
@ -24,7 +24,7 @@ void MCSymbolXCOFF::setRepresentedCsect(MCSectionXCOFF *C) {
assert((!RepresentedCsect || RepresentedCsect == C) &&
"Trying to set a csect that doesn't match the one that this symbol is "
"already mapped to.");
assert(getSymbolTableName().equals(C->getSymbolTableName()) &&
assert(getSymbolTableName() == C->getSymbolTableName() &&
"SymbolTableNames need to be the same for this symbol and its csect "
"representation.");
RepresentedCsect = C;

View File

@ -269,11 +269,11 @@ Expected<StringRef> ArchiveMemberHeader::getName(uint64_t Size) const {
return Name;
// System libraries from the Windows SDK for Windows 11 contain this symbol.
// It looks like a CFG guard: we just skip it for now.
if (Name.equals("/<XFGHASHMAP>/"))
if (Name == "/<XFGHASHMAP>/")
return Name;
// Some libraries (e.g., arm64rt.lib) from the Windows WDK
// (version 10.0.22000.0) contain this undocumented special member.
if (Name.equals("/<ECSYMBOLS>/"))
if (Name == "/<ECSYMBOLS>/")
return Name;
// It's a long name.
// Get the string table offset.

View File

@ -399,7 +399,7 @@ static Error parseSegmentLoadCommand(
return malformedError("load command " + Twine(LoadCommandIndex) +
" filesize field in " + CmdName +
" greater than vmsize field");
IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
IsPageZeroSegment |= StringRef("__PAGEZERO") == S.segname;
} else
return SegOrErr.takeError();
@ -4364,7 +4364,7 @@ BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
Info.Size = Section.getSize();
Info.SegmentName =
Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
if (!Info.SegmentName.equals(CurSegName)) {
if (Info.SegmentName != CurSegName) {
++CurSegIndex;
CurSegName = Info.SegmentName;
CurSegAddress = Info.Address;

View File

@ -359,7 +359,7 @@ bool object::areTargetsCompatible(const OffloadFile::TargetID &LHS,
return false;
// If the architecture is "all" we assume it is always compatible.
if (LHS.second.equals("generic") || RHS.second.equals("generic"))
if (LHS.second == "generic" || RHS.second == "generic")
return true;
// Only The AMDGPU target requires additional checks.

View File

@ -359,9 +359,9 @@ static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic,
SizeOfInitializedData += S.Header.SizeOfRawData;
if (S.Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
SizeOfUninitializedData += S.Header.SizeOfRawData;
if (S.Name.equals(".text"))
if (S.Name == ".text")
Header->BaseOfCode = S.Header.VirtualAddress; // RVA
else if (S.Name.equals(".data"))
else if (S.Name == ".data")
BaseOfData = S.Header.VirtualAddress; // RVA
if (S.Header.VirtualAddress)
SizeOfImage += alignTo(S.Header.VirtualSize, Header->SectionAlignment);

View File

@ -822,8 +822,7 @@ PrintIRInstrumentation::PassRunDescriptor
PrintIRInstrumentation::popPassRunDescriptor(StringRef PassID) {
assert(!PassRunDescriptorStack.empty() && "empty PassRunDescriptorStack");
PassRunDescriptor Descriptor = PassRunDescriptorStack.pop_back_val();
assert(Descriptor.PassID.equals(PassID) &&
"malformed PassRunDescriptorStack");
assert(Descriptor.PassID == PassID && "malformed PassRunDescriptorStack");
return Descriptor;
}

View File

@ -678,7 +678,7 @@ std::string Context::getCoveragePath(StringRef filename,
return std::string(filename);
std::string CoveragePath;
if (options.LongFileNames && !filename.equals(mainFilename))
if (options.LongFileNames && filename != mainFilename)
CoveragePath =
mangleCoveragePath(mainFilename, options.PreservePaths) + "##";
CoveragePath += mangleCoveragePath(filename, options.PreservePaths);

View File

@ -1283,7 +1283,7 @@ MDNode *mayHaveValueProfileOfKind(const Instruction &Inst,
return nullptr;
MDString *Tag = cast<MDString>(MD->getOperand(0));
if (!Tag || !Tag->getString().equals("VP"))
if (!Tag || Tag->getString() != "VP")
return nullptr;
// Now check kind:

View File

@ -164,9 +164,9 @@ bool isRuntimePath(const StringRef Path) {
const StringRef Filename = llvm::sys::path::filename(Path);
// This list should be updated in case new files with additional interceptors
// are added to the memprof runtime.
return Filename.equals("memprof_malloc_linux.cpp") ||
Filename.equals("memprof_interceptors.cpp") ||
Filename.equals("memprof_new_delete.cpp");
return Filename == "memprof_malloc_linux.cpp" ||
Filename == "memprof_interceptors.cpp" ||
Filename == "memprof_new_delete.cpp";
}
std::string getBuildIdString(const SegmentEntry &Entry) {

View File

@ -1725,7 +1725,7 @@ public:
RedirectingFileSystem::Entry *ParentEntry = nullptr) {
if (!ParentEntry) { // Look for a existent root
for (const auto &Root : FS->Roots) {
if (Name.equals(Root->getName())) {
if (Name == Root->getName()) {
ParentEntry = Root.get();
return ParentEntry;
}
@ -1736,7 +1736,7 @@ public:
llvm::make_range(DE->contents_begin(), DE->contents_end())) {
auto *DirContent =
dyn_cast<RedirectingFileSystem::DirectoryEntry>(Content.get());
if (DirContent && Name.equals(Content->getName()))
if (DirContent && Name == Content->getName())
return DirContent;
}
}

View File

@ -610,7 +610,7 @@ StringRef ARM::getARMCPUForArch(const llvm::Triple &Triple, StringRef MArch) {
return StringRef();
StringRef CPU = llvm::ARM::getDefaultCPU(MArch);
if (!CPU.empty() && !CPU.equals("invalid"))
if (!CPU.empty() && CPU != "invalid")
return CPU;
// If no specific architecture version is requested, return the minimum CPU

View File

@ -373,14 +373,14 @@ StringRef Triple::getObjectFormatTypeName(ObjectFormatType Kind) {
}
static Triple::ArchType parseBPFArch(StringRef ArchName) {
if (ArchName.equals("bpf")) {
if (ArchName == "bpf") {
if (sys::IsLittleEndianHost)
return Triple::bpfel;
else
return Triple::bpfeb;
} else if (ArchName.equals("bpf_be") || ArchName.equals("bpfeb")) {
} else if (ArchName == "bpf_be" || ArchName == "bpfeb") {
return Triple::bpfeb;
} else if (ArchName.equals("bpf_le") || ArchName.equals("bpfel")) {
} else if (ArchName == "bpf_le" || ArchName == "bpfel") {
return Triple::bpfel;
} else {
return Triple::UnknownArch;

View File

@ -705,7 +705,7 @@ bool DwarfLinkerForBinary::linkImpl(
} else {
// Try and emit more helpful warnings by applying some heuristics.
StringRef ObjFile = ContainerName;
bool IsClangModule = sys::path::extension(Path).equals(".pcm");
bool IsClangModule = sys::path::extension(Path) == ".pcm";
bool IsArchive = ObjFile.ends_with(")");
if (IsClangModule) {

View File

@ -229,7 +229,7 @@ static std::string constructDieID(DWARFDie Die,
<< Die.getName(DINameKind::LinkageName);
// Prefix + Name is enough for local variables and parameters.
if (!Prefix.empty() && !Prefix.equals("g"))
if (!Prefix.empty() && Prefix != "g")
return ID.str();
auto DeclFile = Die.findRecursively(dwarf::DW_AT_decl_file);

View File

@ -357,7 +357,7 @@ int main(int argc, char **argv) {
// The function has been materialized, so add its matching basic blocks
// to the block extractor list, or fail if a name is not found.
auto Res = llvm::find_if(*P.first, [&](const BasicBlock &BB) {
return BB.getName().equals(BBName);
return BB.getName() == BBName;
});
if (Res == P.first->end()) {
errs() << argv[0] << ": function " << P.first->getName()

View File

@ -2148,7 +2148,7 @@ static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
else
consumeError(NameOrErr.takeError());
if (SectName.equals("__text")) {
if (SectName == "__text") {
DataRefImpl Ref = Section.getRawDataRefImpl();
StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
DisassembleMachO(FileName, MachOOF, SegName, SectName);

View File

@ -381,14 +381,14 @@ void GraphDiffRenderer::exportGraphAsDOT(raw_ostream &OS, StatType EdgeLabel,
R"(color="{5}" labelfontcolor="{5}" penwidth={6}])"
"\n",
VertexNo[HeadId], VertexNo[TailId],
(HeadId.equals("")) ? static_cast<StringRef>("F0") : HeadId,
HeadId.empty() ? static_cast<StringRef>("F0") : HeadId,
TailId, getLabel(E, EdgeLabel), getColor(E, G, H, EdgeColor),
getLineWidth(E, EdgeColor));
}
for (const auto &V : G.vertices()) {
const auto &VertexId = V.first;
if (VertexId.equals("")) {
if (VertexId.empty()) {
OS << formatv(R"(F{0} [label="F0"])"
"\n",
VertexNo[VertexId]);

View File

@ -18,7 +18,7 @@ inline bool isNumericRegex(llvm::StringRef S) {
static llvm::Regex Float(
"^[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$");
if (S.equals(".nan") || S.equals(".NaN") || S.equals(".NAN"))
if (S == ".nan" || S == ".NaN" || S == ".NAN")
return true;
if (Infinity.match(S))

View File

@ -998,7 +998,7 @@ TEST(StringRefTest, AllocatorCopy) {
// allocator.
StringRef StrEmpty = "";
StringRef StrEmptyc = StrEmpty.copy(Alloc);
EXPECT_TRUE(StrEmpty.equals(StrEmptyc));
EXPECT_TRUE(StrEmpty == StrEmptyc);
EXPECT_EQ(StrEmptyc.data(), nullptr);
EXPECT_EQ(StrEmptyc.size(), 0u);
EXPECT_EQ(Alloc.getTotalMemory(), 0u);
@ -1007,9 +1007,9 @@ TEST(StringRefTest, AllocatorCopy) {
StringRef Str2 = "bye";
StringRef Str1c = Str1.copy(Alloc);
StringRef Str2c = Str2.copy(Alloc);
EXPECT_TRUE(Str1.equals(Str1c));
EXPECT_TRUE(Str1 == Str1c);
EXPECT_NE(Str1.data(), Str1c.data());
EXPECT_TRUE(Str2.equals(Str2c));
EXPECT_TRUE(Str2 == Str2c);
EXPECT_NE(Str2.data(), Str2c.data());
}

View File

@ -173,27 +173,27 @@ TEST(VerifierTest, CrossModuleRef) {
std::string Error;
raw_string_ostream ErrorOS(Error);
EXPECT_TRUE(verifyModule(M2, &ErrorOS));
EXPECT_TRUE(StringRef(ErrorOS.str())
.equals("Global is referenced in a different module!\n"
"ptr @foo2\n"
"; ModuleID = 'M2'\n"
" %call = call i32 @foo2()\n"
"ptr @foo1\n"
"; ModuleID = 'M1'\n"
"Global is used by function in a different module\n"
"ptr @foo2\n"
"; ModuleID = 'M2'\n"
"ptr @foo3\n"
"; ModuleID = 'M3'\n"));
EXPECT_TRUE(StringRef(ErrorOS.str()) ==
"Global is referenced in a different module!\n"
"ptr @foo2\n"
"; ModuleID = 'M2'\n"
" %call = call i32 @foo2()\n"
"ptr @foo1\n"
"; ModuleID = 'M1'\n"
"Global is used by function in a different module\n"
"ptr @foo2\n"
"; ModuleID = 'M2'\n"
"ptr @foo3\n"
"; ModuleID = 'M3'\n");
Error.clear();
EXPECT_TRUE(verifyModule(M1, &ErrorOS));
EXPECT_TRUE(StringRef(ErrorOS.str()).equals(
"Referencing function in another module!\n"
" %call = call i32 @foo2()\n"
"; ModuleID = 'M1'\n"
"ptr @foo2\n"
"; ModuleID = 'M2'\n"));
EXPECT_TRUE(StringRef(ErrorOS.str()) ==
"Referencing function in another module!\n"
" %call = call i32 @foo2()\n"
"; ModuleID = 'M1'\n"
"ptr @foo2\n"
"; ModuleID = 'M2'\n");
Error.clear();
EXPECT_TRUE(verifyModule(M3, &ErrorOS));

View File

@ -317,13 +317,13 @@ TEST_F(MemoryBufferTest, slice) {
EXPECT_EQ(0x4000UL, MB.get()->getBufferSize());
StringRef BufData = MB.get()->getBuffer();
EXPECT_TRUE(BufData.substr(0x0000,8).equals("12345678"));
EXPECT_TRUE(BufData.substr(0x0FF8,8).equals("12345678"));
EXPECT_TRUE(BufData.substr(0x1000,8).equals("abcdefgh"));
EXPECT_TRUE(BufData.substr(0x2FF8,8).equals("abcdefgh"));
EXPECT_TRUE(BufData.substr(0x3000,8).equals("ABCDEFGH"));
EXPECT_TRUE(BufData.substr(0x3FF8,8).equals("ABCDEFGH"));
EXPECT_TRUE(BufData.substr(0x0000, 8) == "12345678");
EXPECT_TRUE(BufData.substr(0x0FF8, 8) == "12345678");
EXPECT_TRUE(BufData.substr(0x1000, 8) == "abcdefgh");
EXPECT_TRUE(BufData.substr(0x2FF8, 8) == "abcdefgh");
EXPECT_TRUE(BufData.substr(0x3000, 8) == "ABCDEFGH");
EXPECT_TRUE(BufData.substr(0x3FF8, 8) == "ABCDEFGH");
// Try non-page aligned.
ErrorOr<OwningBuffer> MB2 = MemoryBuffer::getFileSlice(TestPath.str(),
0x3000, 0x0800);
@ -332,10 +332,10 @@ TEST_F(MemoryBufferTest, slice) {
EXPECT_EQ(0x3000UL, MB2.get()->getBufferSize());
StringRef BufData2 = MB2.get()->getBuffer();
EXPECT_TRUE(BufData2.substr(0x0000,8).equals("12345678"));
EXPECT_TRUE(BufData2.substr(0x17F8,8).equals("12345678"));
EXPECT_TRUE(BufData2.substr(0x1800,8).equals("abcdefgh"));
EXPECT_TRUE(BufData2.substr(0x2FF8,8).equals("abcdefgh"));
EXPECT_TRUE(BufData2.substr(0x0000, 8) == "12345678");
EXPECT_TRUE(BufData2.substr(0x17F8, 8) == "12345678");
EXPECT_TRUE(BufData2.substr(0x1800, 8) == "abcdefgh");
EXPECT_TRUE(BufData2.substr(0x2FF8, 8) == "abcdefgh");
}
TEST_F(MemoryBufferTest, writableSlice) {

View File

@ -1389,10 +1389,10 @@ TEST(YAMLIO, TestReadWriteMyFlowSequence) {
yin >> map2;
EXPECT_FALSE(yin.error());
EXPECT_TRUE(map2.name.equals("hello"));
EXPECT_TRUE(map2.name == "hello");
EXPECT_EQ(map2.strings.size(), 2UL);
EXPECT_TRUE(map2.strings[0].value.equals("one"));
EXPECT_TRUE(map2.strings[1].value.equals("two"));
EXPECT_TRUE(map2.strings[0].value == "one");
EXPECT_TRUE(map2.strings[1].value == "two");
EXPECT_EQ(map2.single.size(), 1UL);
EXPECT_EQ(1, map2.single[0]);
EXPECT_EQ(map2.numbers.size(), 3UL);
@ -1436,7 +1436,7 @@ TEST(YAMLIO, TestReadWriteSequenceOfMyFlowSequence) {
yin >> map2;
EXPECT_FALSE(yin.error());
EXPECT_TRUE(map2.name.equals("hello"));
EXPECT_TRUE(map2.name == "hello");
EXPECT_EQ(map2.sequenceOfNumbers.size(), 3UL);
EXPECT_EQ(map2.sequenceOfNumbers[0].size(), 1UL);
EXPECT_EQ(0, map2.sequenceOfNumbers[0][0]);

View File

@ -1020,7 +1020,7 @@ TEST(TargetParserTest, testInvalidCSKYArch) {
bool testCSKYArch(StringRef Arch, StringRef DefaultCPU) {
CSKY::ArchKind AK = CSKY::parseArch(Arch);
bool Result = (AK != CSKY::ArchKind::INVALID);
Result &= CSKY::getDefaultCPU(Arch).equals(DefaultCPU);
Result &= CSKY::getDefaultCPU(Arch) == DefaultCPU;
return Result;
}

View File

@ -572,8 +572,8 @@ bool testARMArch(StringRef Arch, StringRef DefaultCPU, StringRef SubArch,
unsigned ArchAttr) {
ARM::ArchKind AK = ARM::parseArch(Arch);
bool Result = (AK != ARM::ArchKind::INVALID);
Result &= ARM::getDefaultCPU(Arch).equals(DefaultCPU);
Result &= ARM::getSubArch(AK).equals(SubArch);
Result &= ARM::getDefaultCPU(Arch) == DefaultCPU;
Result &= ARM::getSubArch(AK) == SubArch;
Result &= (ARM::getArchAttr(AK) == ArchAttr);
return Result;
}

View File

@ -3121,7 +3121,7 @@ static void emitMnemonicSpellChecker(raw_ostream &OS, CodeGenTarget &Target,
OS << "\n";
OS << " StringRef T = I->getMnemonic();\n";
OS << " // Avoid recomputing the edit distance for the same string.\n";
OS << " if (T.equals(Prev))\n";
OS << " if (T == Prev)\n";
OS << " continue;\n";
OS << "\n";
OS << " Prev = T;\n";