This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

C++ PATCH for c++/54021 (__builtin_constant_p and constexpr)


When not optimizing, fold_builtin_1 assumes that __builtin_constant_p isn't going to give any better answer than we can see at first folding. But this isn't true in a constexpr function, for which the parameters can later be replaced by constants. So I've taken Jakub's suggestion of setting optimize across the call to fold in this case.

Tested x86_64-pc-linux-gnu, applying to trunk.
commit 0fe036307f9101c5157a680f816fc816895fe3ea
Author: Jason Merrill <jason@redhat.com>
Date:   Thu Jul 19 09:47:04 2012 -0400

    	PR c++/54021
    	* call.c (build_cxx_call): Set optimize when folding
    	__builtin_constant_p in a constexpr function.

diff --git a/gcc/cp/call.c b/gcc/cp/call.c
index 5b3245f..cf50e88 100644
--- a/gcc/cp/call.c
+++ b/gcc/cp/call.c
@@ -6900,6 +6900,7 @@ tree
 build_cxx_call (tree fn, int nargs, tree *argarray)
 {
   tree fndecl;
+  int optimize_sav;
 
   /* Remember roughly where this call is.  */
   location_t loc = EXPR_LOC_OR_HERE (fn);
@@ -6916,8 +6917,15 @@ build_cxx_call (tree fn, int nargs, tree *argarray)
     return error_mark_node;
 
   /* Some built-in function calls will be evaluated at compile-time in
-     fold ().  */
+     fold ().  Set optimize to 1 when folding __builtin_constant_p inside
+     a constexpr function so that fold_builtin_1 doesn't fold it to 0.  */
+  optimize_sav = optimize;
+  if (!optimize && fndecl && DECL_IS_BUILTIN_CONSTANT_P (fndecl)
+      && current_function_decl
+      && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
+    optimize = 1;
   fn = fold_if_not_in_template (fn);
+  optimize = optimize_sav;
 
   if (VOID_TYPE_P (TREE_TYPE (fn)))
     return fn;
diff --git a/gcc/testsuite/g++.dg/cpp0x/constexpr-builtin2.C b/gcc/testsuite/g++.dg/cpp0x/constexpr-builtin2.C
new file mode 100644
index 0000000..dde38f0
--- /dev/null
+++ b/gcc/testsuite/g++.dg/cpp0x/constexpr-builtin2.C
@@ -0,0 +1,16 @@
+// PR c++/54021
+// { dg-do compile { target c++11 } }
+
+extern int nonconst_func(int);
+constexpr int identity(int x) { return x; }
+constexpr int zero() { return identity(0); }
+constexpr int one() { return identity(1); }
+
+// These are the same.  Only the latter is accepted, though.
+constexpr int rejected_const_4(int x)
+{ return __builtin_constant_p(x) ? 4 : nonconst_func(x); }
+constexpr int accepted_const_4(int x)
+{ return identity(__builtin_constant_p(x)) ? 4 : nonconst_func(x); }
+
+// This is rejected.  I would like it to work.
+constexpr int four = accepted_const_4(1);

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]