[UBSan] Consider zero input to __builtin_clz/ctz to be undefined independent of the...
authorCraig Topper <craig.topper@sifive.com>
Fri, 2 Jun 2023 19:51:42 +0000 (12:51 -0700)
committerCraig Topper <craig.topper@sifive.com>
Fri, 2 Jun 2023 20:01:05 +0000 (13:01 -0700)
Previously we checked isCLZForZeroUndef and only added UBSan checks
if it returned true.

The builtin should be considered undefined for 0 regardless of
the target so that code using it is portable. The isCLZForZeroUndef
was only intended to disable optimizations in the middle end and
backend.

See https://discourse.llvm.org/t/should-ubsan-detect-0-input-to-builtin-clz-ctz-regardless-of-target/71060

Reviewed By: nikic

Differential Revision: https://reviews.llvm.org/D152023

clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/ubsan-builtin-checks.c

index bfa6fd7..c09e5b5 100644 (file)
@@ -1741,7 +1741,7 @@ Value *CodeGenFunction::EmitCheckedArgForBuiltin(const Expr *E,
           && "Unsupported builtin check kind");
 
   Value *ArgValue = EmitScalarExpr(E);
-  if (!SanOpts.has(SanitizerKind::Builtin) || !getTarget().isCLZForZeroUndef())
+  if (!SanOpts.has(SanitizerKind::Builtin))
     return ArgValue;
 
   SanitizerScope SanScope(this);
index eb6ff11..2bc32d8 100644 (file)
@@ -1,7 +1,8 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -w -emit-llvm -o - %s -fsanitize=builtin | FileCheck %s
-// RUN: %clang_cc1 -triple arm64-none-linux-gnu -w -emit-llvm -o - %s -fsanitize=builtin | FileCheck %s --check-prefix=NOT-UB
+// RUN: %clang_cc1 -triple x86_64-apple-darwin10 -w -emit-llvm -o - %s -fsanitize=builtin | FileCheck %s --check-prefixes=CHECK,POISON
+// RUN: %clang_cc1 -triple arm64-none-linux-gnu -w -emit-llvm -o - %s -fsanitize=builtin | FileCheck %s --check-prefixes=CHECK,NOPOISON
 
-// NOT-UB-NOT: __ubsan_handle_invalid_builtin
+// A zero input to __bultin_ctz/clz is considered UB even if the target does not
+// want to optimize based on zero input being undefined.
 
 // CHECK: define{{.*}} void @check_ctz
 void check_ctz(int n) {
@@ -13,7 +14,8 @@ void check_ctz(int n) {
   // CHECK-NEXT: unreachable
   //
   // Continuation block:
-  // CHECK: call i32 @llvm.cttz.i32(i32 [[N]], i1 true)
+  // POISON: call i32 @llvm.cttz.i32(i32 [[N]], i1 true)
+  // NOPOISON: call i32 @llvm.cttz.i32(i32 [[N]], i1 false)
   __builtin_ctz(n);
 
   // CHECK: call void @__ubsan_handle_invalid_builtin
@@ -33,7 +35,8 @@ void check_clz(int n) {
   // CHECK-NEXT: unreachable
   //
   // Continuation block:
-  // CHECK: call i32 @llvm.ctlz.i32(i32 [[N]], i1 true)
+  // POISON: call i32 @llvm.ctlz.i32(i32 [[N]], i1 true)
+  // NOPOISON: call i32 @llvm.ctlz.i32(i32 [[N]], i1 false)
   __builtin_clz(n);
 
   // CHECK: call void @__ubsan_handle_invalid_builtin