[PATCH] D70143: Check result of emitStrLen before passing it to CreateGEP

Dimitry Andric via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 12 13:34:42 PST 2019


dim created this revision.
dim added reviewers: xbolva00, spatel, jdoerfert, efriedma.
Herald added subscribers: cfe-commits, hiraditya.
Herald added projects: clang, LLVM.

This fixes PR43081, where the transformation of `strchr(p, 0) -> p +
strlen(p)` can cause a segfault, if `-fno-builtin-strlen` is used.  In
that case, `emitStrLen` returns nullptr, which CreateGEP is not designed
to handle.  Also add the minimized code from the PR as a test case.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D70143

Files:
  clang/test/CodeGen/builtin-replace-strchr-with-strlen.c
  llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp


Index: llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
===================================================================
--- llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
+++ 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;
   }
 
Index: clang/test/CodeGen/builtin-replace-strchr-with-strlen.c
===================================================================
--- /dev/null
+++ 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
+}


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D70143.228952.patch
Type: text/x-patch
Size: 1213 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20191112/13860292/attachment.bin>


More information about the llvm-commits mailing list