Skip to content

Commit

Permalink
[llvm] Use StringRef::operator== instead of StringRef::equals (NFC) (#…
Browse files Browse the repository at this point in the history
…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".
  • Loading branch information
kazutakahirata authored May 8, 2024
1 parent 46435ac commit bb6df08
Show file tree
Hide file tree
Showing 34 changed files with 79 additions and 80 deletions.
2 changes: 1 addition & 1 deletion llvm/include/llvm/ADT/SmallString.h
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class SmallString : public SmallVector<char, InternalLen> {

/// 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 {
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Bitcode/Reader/BitcodeReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/FileCheck/FileCheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "'");

Expand Down
6 changes: 3 additions & 3 deletions llvm/lib/FuzzMutate/FuzzerCLI.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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++]);
Expand All @@ -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");
Expand Down Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/LTO/LTOModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/MC/MCAsmStreamer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/MC/MCParser/AsmParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "'");

Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/MC/MCParser/DarwinAsmParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/MC/MCSymbolXCOFF.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/Object/Archive.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/Object/MachOObjectFile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Object/OffloadBinary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/ObjectYAML/COFFEmitter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions llvm/lib/Passes/StandardInstrumentations.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/ProfileData/GCOV.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/ProfileData/InstrProf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions llvm/lib/ProfileData/MemProfReader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions llvm/lib/Support/VirtualFileSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1725,7 +1725,7 @@ class llvm::vfs::RedirectingFileSystemParser {
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;
}
Expand All @@ -1736,7 +1736,7 @@ class llvm::vfs::RedirectingFileSystemParser {
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;
}
}
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/TargetParser/ARMTargetParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions llvm/lib/TargetParser/Triple.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion llvm/tools/dsymutil/DwarfLinkerForBinary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion llvm/tools/llvm-dwarfdump/Statistics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion llvm/tools/llvm-extract/llvm-extract.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion llvm/tools/llvm-objdump/MachODump.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions llvm/tools/llvm-xray/xray-graph-diff.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
6 changes: 3 additions & 3 deletions llvm/unittests/ADT/StringRefTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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());
}

Expand Down
36 changes: 18 additions & 18 deletions llvm/unittests/IR/VerifierTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
Loading

0 comments on commit bb6df08

Please sign in to comment.