]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
ranger: Handle nonnull_if_nonzero attribute [PR117023]
authorJakub Jelinek <jakub@redhat.com>
Thu, 28 Nov 2024 10:50:49 +0000 (11:50 +0100)
committerJakub Jelinek <jakub@gcc.gnu.org>
Thu, 28 Nov 2024 10:50:49 +0000 (11:50 +0100)
On top of the
https://gcc.gnu.org/pipermail/gcc-patches/2024-November/668554.html
patch which introduces the nonnull_if_nonzero attribute (because
C2Y is allowing NULL arguments on various calls like memcpy, memset,
strncpy etc. as long as the count is 0) the following patch adds just
limited handling of the attribute in the ranger, in particular infers
nonnull for the pointer argument referenced in first argument of the
attribute if the second argument is a non-zero INTEGER_CST
(integer_nonzerop).

Ideally (as the FIXME says) I'd like to query arg2 range and check if
it doesn't contain zero, but am not sure such queries are possible from
gimple_infer_range (and if it is possible whether one can just query
the currently recorded range for it or if one can call something that
will try to compute the range by walking the def stmts etc.).

Could you handle as a follow-up the range querying if it is possible?

As for useful testcase, with the patch I'm going to post next
e.g. gcc.dg/tree-ssa/pr78154.c if the calls use d as destination (not dn)
and count that will have a range which doesn't include 0 and isn't constant.

2024-11-28  Jakub Jelinek  <jakub@redhat.com>

PR c/117023
* gimple-range-infer.cc (gimple_infer_range::gimple_infer_range):
Handle also nonnull_if_nonzero attributes.

gcc/gimple-range-infer.cc

index 98642e2438fc6aeab09088ca5f70f5fe45793f69..b5621f0b22aa6647d6848878009e21cbc2d8e50c 100644 (file)
@@ -183,6 +183,30 @@ gimple_infer_range::gimple_infer_range (gimple *s, bool use_rangeops)
            }
          BITMAP_FREE (nonnullargs);
        }
+      if (fntype)
+       for (tree attrs = TYPE_ATTRIBUTES (fntype);
+            (attrs = lookup_attribute ("nonnull_if_nonzero", attrs));
+            attrs = TREE_CHAIN (attrs))
+         {
+           tree args = TREE_VALUE (attrs);
+           unsigned int idx = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
+           unsigned int idx2
+             = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1;
+           if (idx < gimple_call_num_args (s)
+               && idx2 < gimple_call_num_args (s))
+             {
+               tree arg = gimple_call_arg (s, idx);
+               tree arg2 = gimple_call_arg (s, idx2);
+               if (!POINTER_TYPE_P (TREE_TYPE (arg))
+                   || !INTEGRAL_TYPE_P (TREE_TYPE (arg2))
+                   || integer_zerop (arg2))
+                 continue;
+               if (integer_nonzerop (arg2))
+                 add_nonzero (arg);
+               // FIXME: Can one query here whether arg2 has
+               // nonzero range if it is a SSA_NAME?
+             }
+         }
       // Fallthru and walk load/store ops now.
     }