diff --git a/clang/test/CodeGen/builtin-replace-strchr-with-strlen.c b/clang/test/CodeGen/builtin-replace-strchr-with-strlen.c new file mode 100644 --- /dev/null +++ b/clang/test/CodeGen/builtin-replace-strchr-with-strlen.c @@ -0,0 +1,6 @@ +// RUN: %clang_cc1 -triple x86_64-- -S -O1 -fno-builtin-strlen %s -o - | FileCheck %s +char *strchr(const char *, int); +char *b(char *a) { + return strchr(a, '\0'); +// CHECK: jmp strchr +} diff --git a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp --- a/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp +++ b/llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp @@ -363,9 +363,11 @@ // a string literal. If so, we can constant fold. StringRef Str; if (!getConstantStringInfo(SrcStr, Str)) { - if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p) - return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI), - "strchr"); + if (CharC->isZero()) { // strchr(p, 0) -> p + strlen(p) + Value *StrLen = emitStrLen(SrcStr, B, DL, TLI); + return StrLen ? B.CreateGEP(B.getInt8Ty(), SrcStr, StrLen, "strchr") + : nullptr; + } return nullptr; }