[Bug sanitizer/115791] division by zero check missing at optimization levels -O2 and -O3

2024-07-04 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115791

--- Comment #3 from Andrew Pinski  ---
So fixed for GCC 11.  Note GCC 10.5.0 was the last release of GCC 10.x series
and there will be no other new 10.x.

[Bug sanitizer/115791] division by zero check missing at optimization levels -O2 and -O3

2024-07-04 Thread xry111 at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115791

Xi Ruoyao  changed:

   What|Removed |Added

   See Also||https://gcc.gnu.org/bugzill
   ||a/show_bug.cgi?id=113190
 Status|UNCONFIRMED |RESOLVED
 Resolution|--- |WONTFIX

--- Comment #2 from Xi Ruoyao  ---
GCC 11.1 works fine, so WONTFIX.

[Bug sanitizer/115791] division by zero check missing at optimization levels -O2 and -O3

2024-07-04 Thread xry111 at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115791

Xi Ruoyao  changed:

   What|Removed |Added

 CC||xry111 at gcc dot gnu.org

--- Comment #1 from Xi Ruoyao  ---
GCC 10.x is no longer supported.

[Bug sanitizer/115791] New: division by zero check missing at optimization levels -O2 and -O3

2024-07-04 Thread bic60176 at gmail dot com via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115791

Bug ID: 115791
   Summary: division by zero check missing at optimization levels
-O2 and -O3
   Product: gcc
   Version: 10.5.0
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: sanitizer
  Assignee: unassigned at gcc dot gnu.org
  Reporter: bic60176 at gmail dot com
CC: dodji at gcc dot gnu.org, dvyukov at gcc dot gnu.org,
jakub at gcc dot gnu.org, kcc at gcc dot gnu.org
  Target Milestone: ---

Created attachment 58592
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=58592=edit
testcase

OS: Ubuntu 22.04.3 LTS
We found a case that UBSAN failed to report division by zero when compiling
with gcc-10.5.0 at optimization levels -O2 and -O3.

$ ../compiler-builds/gcc-10.5.0_build/bin/gcc -fsanitize=undefined
-fsanitize=address -g -lgcc_s -I/home/csmith/include/csmith-2.3.0 -O2
testcase.c -o exec

$ timeout 1s ./exec 2>exec.err
AddressSanitizer:DEADLYSIGNAL
=
==3701326==ERROR: AddressSanitizer: FPE on unknown address 0x0040133d (pc
0x0040133d bp 0x0001 sp 0x7fff7c034130 T0) #0 0x40133d in func_1
testcase.c:20 #1 0x40133d in main testcase.c:29 #2 0x7aaedd229d8f in
__libc_start_call_main ../sysdeps/x86/libc-start.c:58 #3 0x7aaedd229e3f in
__libc_start_main_impl ../sysdeps/nptl/libc_start_call_main.h:392 #4 0x4014d4
in _start (./exec23+0x4014d4) AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: FPE testcase.c:20 in func_1 ==3701326==ABORTING

$ ../compiler-builds/gcc-11.4.0_build/bin/gcc -fsanitize=undefined
-fsanitize=address -g -lgcc_s -I/home/csmith/include/csmith-2.3.0 -O2
testcase.c -o exec

$ timeout 1s ./exec 2>exec.err
testcase.c:20:382: runtime error: division by zero

[Bug middle-end/112771] during GIMPLE pass: bitintlower0 ICE: in build_bitint_type, at tree.cc:7178 with _BitInt(65535) and division by zero

2023-12-01 Thread jakub at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112771

Jakub Jelinek  changed:

   What|Removed |Added

 Resolution|--- |FIXED
 Status|ASSIGNED|RESOLVED

--- Comment #3 from Jakub Jelinek  ---
Fixed.

[Bug middle-end/112771] during GIMPLE pass: bitintlower0 ICE: in build_bitint_type, at tree.cc:7178 with _BitInt(65535) and division by zero

2023-12-01 Thread cvs-commit at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112771

--- Comment #2 from GCC Commits  ---
The master branch has been updated by Jakub Jelinek :

https://gcc.gnu.org/g:9bfebcb1b7ae4e7160644f2104424d6bab4a23f7

commit r14-6050-g9bfebcb1b7ae4e7160644f2104424d6bab4a23f7
Author: Jakub Jelinek 
Date:   Fri Dec 1 10:55:49 2023 +0100

lower-bitint: Fix up handle_operand_addr for 0 constants [PR112771]

handle_operand_addr for INTEGER_CSTs uses wi::min_precision (UNSIGNED
for non-negative constants, SIGNED for negative ones) and from that
computes mp as minimum number of limbs which can represent that value,
and in some cases creates a test BITINT_TYPE with that precision to
categorize it and decide based on that what types to use on the constant
emitted into memory.  For the actual precisions (what will be passed
to libgcc) it actually already uses MAX/MIN to adjust the corner cases:
  *prec = MAX (min_prec, 1);
...
  *prec = MIN ((int) -min_prec, -2);
but for integer_zerop min_prec will be 0,
mp = CEIL (min_prec, limb_prec) * limb_prec;
will be also 0 and we ICE trying to build unsigned BITINT_TYPE with
0 precision.

Fixed thusly by noting even 0 has to be encoded at least as one limb.

2023-12-01  Jakub Jelinek  

PR middle-end/112771
* gimple-lower-bitint.cc (bitint_large_huge::handle_operand_addr):
Use mp = 1 if it is zero.

* gcc.dg/bitint-44.c: New test.

[Bug middle-end/112771] during GIMPLE pass: bitintlower0 ICE: in build_bitint_type, at tree.cc:7178 with _BitInt(65535) and division by zero

2023-11-30 Thread jakub at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112771

Jakub Jelinek  changed:

   What|Removed |Added

 Status|UNCONFIRMED |ASSIGNED
 Ever confirmed|0   |1
   Last reconfirmed||2023-11-30
   Assignee|unassigned at gcc dot gnu.org  |jakub at gcc dot gnu.org

--- Comment #1 from Jakub Jelinek  ---
Created attachment 56733
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=56733=edit
gcc14-pr112771.patch

Untested fix.  Thanks for the report.

[Bug middle-end/112771] New: during GIMPLE pass: bitintlower0 ICE: in build_bitint_type, at tree.cc:7178 with _BitInt(65535) and division by zero

2023-11-29 Thread zsojka at seznam dot cz via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112771

Bug ID: 112771
   Summary: during GIMPLE pass: bitintlower0 ICE: in
build_bitint_type, at tree.cc:7178 with _BitInt(65535)
and division by zero
   Product: gcc
   Version: 14.0
Status: UNCONFIRMED
  Keywords: ice-on-valid-code
  Severity: normal
  Priority: P3
 Component: middle-end
  Assignee: unassigned at gcc dot gnu.org
  Reporter: zsojka at seznam dot cz
  Target Milestone: ---
  Host: x86_64-pc-linux-gnu
Target: x86_64-pc-linux-gnu

Created attachment 56722
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=56722=edit
reduced testcase

$ x86_64-pc-linux-gnu-gcc testcase.c 
testcase.c: In function 'foo':
testcase.c:5:5: warning: division by zero [-Wdiv-by-zero]
5 |   a /= 0;
  | ^~
during GIMPLE pass: bitintlower0
testcase.c:2:1: internal compiler error: in build_bitint_type, at tree.cc:7178
2 | foo (void)
  | ^~~
0x891bea build_bitint_type(unsigned long, int)
/repo/gcc-trunk/gcc/tree.cc:7178
0x2538b8e handle_operand_addr
/repo/gcc-trunk/gcc/gimple-lower-bitint.cc:2185
0x2539407 lower_muldiv_stmt
/repo/gcc-trunk/gcc/gimple-lower-bitint.cc:3339
0x254ca76 gimple_lower_bitint
/repo/gcc-trunk/gcc/gimple-lower-bitint.cc:6349
Please submit a full bug report, with preprocessed source (by using
-freport-bug).
Please include the complete backtrace with any bug report.
See <https://gcc.gnu.org/bugs/> for instructions.

$ x86_64-pc-linux-gnu-gcc -v
Using built-in specs.
COLLECT_GCC=/repo/gcc-trunk/binary-latest-amd64/bin/x86_64-pc-linux-gnu-gcc
COLLECT_LTO_WRAPPER=/repo/gcc-trunk/binary-trunk-r14-5974-20231129191907-g259bb7a45a2-checking-yes-rtl-df-extra-nobootstrap-amd64/bin/../libexec/gcc/x86_64-pc-linux-gnu/14.0.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /repo/gcc-trunk//configure --enable-languages=c,c++
--enable-valgrind-annotations --disable-nls --enable-checking=yes,rtl,df,extra
--disable-bootstrap --with-cloog --with-ppl --with-isl
--build=x86_64-pc-linux-gnu --host=x86_64-pc-linux-gnu
--target=x86_64-pc-linux-gnu --with-ld=/usr/bin/x86_64-pc-linux-gnu-ld
--with-as=/usr/bin/x86_64-pc-linux-gnu-as --disable-libstdcxx-pch
--prefix=/repo/gcc-trunk//binary-trunk-r14-5974-20231129191907-g259bb7a45a2-checking-yes-rtl-df-extra-nobootstrap-amd64
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 14.0.0 20231129 (experimental) (GCC)

[Bug middle-end/111711] [14 Regression] ICE: in maybe_legitimize_operand, at optabs.cc:8046 at -O1 with division by zero

2023-10-06 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111711

Andrew Pinski  changed:

   What|Removed |Added

 Resolution|--- |DUPLICATE
 Status|NEW |RESOLVED

--- Comment #3 from Andrew Pinski  ---
So I looked further into this and it was actually a dup when I said it was not.

Anyways just marking it as a dup of bug 111260 in the end.

*** This bug has been marked as a duplicate of bug 111260 ***

[Bug middle-end/111711] [14 Regression] ICE: in maybe_legitimize_operand, at optabs.cc:8046 at -O1 with division by zero

2023-10-06 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111711

--- Comment #2 from Andrew Pinski  ---
(In reply to Andrew Pinski from comment #1)
> It was introduced by r14-2667-gceae1400cf24f329393e96dd9720 .
> 
> We have:
>   long int x;
>   int _3;
>   _Bool _5;
>   _3 = 0 / 0;
>   _5 = _3 == 822920;
>   x_7 = _5 ? 822920 : 0;
> 
> If I disable the added checks on dealing with rtx_equal_p, the ICE goes away.

I mean if I disable the added code trying to reuse the constants, the ICE goes
away.

> The problem is the mode for the result does not match the mode for the
> comparison (DImode for the result of the conditional and SImode for the
> comparison).

[Bug middle-end/111711] [14 Regression] ICE: in maybe_legitimize_operand, at optabs.cc:8046 at -O1 with division by zero

2023-10-06 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111711

Andrew Pinski  changed:

   What|Removed |Added

 Ever confirmed|0   |1
   Keywords|needs-bisection |
   Last reconfirmed||2023-10-06
 Status|UNCONFIRMED |NEW

--- Comment #1 from Andrew Pinski  ---
It was introduced by r14-2667-gceae1400cf24f329393e96dd9720 .

We have:
  long int x;
  int _3;
  _Bool _5;
  _3 = 0 / 0;
  _5 = _3 == 822920;
  x_7 = _5 ? 822920 : 0;

If I disable the added checks on dealing with rtx_equal_p, the ICE goes away.
The problem is the mode for the result does not match the mode for the
comparison (DImode for the result of the conditional and SImode for the
comparison).

[Bug rtl-optimization/111711] [14 Regression] ICE: in maybe_legitimize_operand, at optabs.cc:8046 at -O1 with division by zero

2023-10-06 Thread rguenth at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111711

Richard Biener  changed:

   What|Removed |Added

   Target Milestone|--- |14.0
   Keywords||needs-bisection

[Bug rtl-optimization/111711] New: [14 Regression] ICE: in maybe_legitimize_operand, at optabs.cc:8046 at -O1 with division by zero

2023-10-05 Thread zsojka at seznam dot cz via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111711

Bug ID: 111711
   Summary: [14 Regression] ICE: in maybe_legitimize_operand, at
optabs.cc:8046 at -O1 with division by zero
   Product: gcc
   Version: 14.0
Status: UNCONFIRMED
  Keywords: ice-on-valid-code
  Severity: normal
  Priority: P3
 Component: rtl-optimization
  Assignee: unassigned at gcc dot gnu.org
  Reporter: zsojka at seznam dot cz
  Target Milestone: ---
  Host: x86_64-pc-linux-gnu
Target: aarch64-unknown-linux-gnu

Created attachment 56064
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=56064=edit
reduced testcase

Compiler output:
$ aarch64-unknown-linux-gnu-gcc -O testcase.c
testcase.c: In function 'bar':
testcase.c:4:15: warning: division by zero [-Wdiv-by-zero]
4 |   x *= x == 0 / 0;
  |   ^
during RTL pass: expand
testcase.c: In function 'foo':
testcase.c:11:10: internal compiler error: in maybe_legitimize_operand, at
optabs.cc:8046
   11 |   return bar (822920);
  |  ^~~~
0x7ff794 maybe_legitimize_operand
/repo/gcc-trunk/gcc/optabs.cc:8046
0x7ff794 maybe_legitimize_operands(insn_code, unsigned int, unsigned int,
expand_operand*)
/repo/gcc-trunk/gcc/optabs.cc:8194
0x1104c69 maybe_gen_insn(insn_code, unsigned int, expand_operand*)
/repo/gcc-trunk/gcc/optabs.cc:8213
0x1106789 maybe_expand_insn(insn_code, unsigned int, expand_operand*)
/repo/gcc-trunk/gcc/optabs.cc:8268
0x1106789 emit_conditional_move_1
/repo/gcc-trunk/gcc/optabs.cc:5242
0x1106b5c emit_conditional_move(rtx_def*, rtx_comparison, rtx_def*, rtx_def*,
machine_mode, int)
/repo/gcc-trunk/gcc/optabs.cc:5155
0xe646e3 expand_cond_expr_using_cmove
/repo/gcc-trunk/gcc/expr.cc:9099
0xe50ebd expand_expr_real_2(separate_ops*, rtx_def*, machine_mode,
expand_modifier)
/repo/gcc-trunk/gcc/expr.cc:10520
0xe5713f expand_expr_real_1(tree_node*, rtx_def*, machine_mode,
expand_modifier, rtx_def**, bool)
/repo/gcc-trunk/gcc/expr.cc:10821
0xd190c4 expand_expr(tree_node*, rtx_def*, machine_mode, expand_modifier)
/repo/gcc-trunk/gcc/expr.h:310
0xd190c4 expand_return
/repo/gcc-trunk/gcc/cfgexpand.cc:3809
0xd190c4 expand_gimple_stmt_1
/repo/gcc-trunk/gcc/cfgexpand.cc:3918
0xd190c4 expand_gimple_stmt
/repo/gcc-trunk/gcc/cfgexpand.cc:4044
0xd1f4fe expand_gimple_basic_block
/repo/gcc-trunk/gcc/cfgexpand.cc:6100
0xd20fb6 execute
/repo/gcc-trunk/gcc/cfgexpand.cc:6835
Please submit a full bug report, with preprocessed source (by using
-freport-bug).
Please include the complete backtrace with any bug report.
See <https://gcc.gnu.org/bugs/> for instructions.

aarch64-unknown-linux-gnu-gcc -v
Using built-in specs.
COLLECT_GCC=/repo/gcc-trunk/binary-latest-aarch64/bin/aarch64-unknown-linux-gnu-gcc
COLLECT_LTO_WRAPPER=/repo/gcc-trunk/binary-trunk-20231006111028-gf05b68b8f00-checking-yes-rtl-df-extra-aarch64/bin/../libexec/gcc/aarch64-unknown-linux-gnu/14.0.0/lto-wrapper
Target: aarch64-unknown-linux-gnu
Configured with: /repo/gcc-trunk//configure --enable-languages=c,c++
--enable-valgrind-annotations --disable-nls --enable-checking=yes,rtl,df,extra
--with-cloog --with-ppl --with-isl
--with-sysroot=/usr/aarch64-unknown-linux-gnu --build=x86_64-pc-linux-gnu
--host=x86_64-pc-linux-gnu --target=aarch64-unknown-linux-gnu
--with-ld=/usr/bin/aarch64-unknown-linux-gnu-ld
--with-as=/usr/bin/aarch64-unknown-linux-gnu-as --disable-libstdcxx-pch
--prefix=/repo/gcc-trunk//binary-trunk-20231006111028-gf05b68b8f00-checking-yes-rtl-df-extra-aarch64
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 14.0.0 20231006 (experimental) (GCC)

Avoid division by zero in fold_loop_internal_call

2023-08-14 Thread Jan Hubicka via Gcc-patches
Hi,
My patch to fix profile after folding internal call is missing check for the
case profile was already zero before if-conversion.

Bootstrapped/regtested x86_64-linux, comitted.

gcc/ChangeLog:

PR gcov-profile/110988
* tree-cfg.cc (fold_loop_internal_call): Avoid division by zero.

diff --git a/gcc/tree-cfg.cc b/gcc/tree-cfg.cc
index ab1f8067c54..105f4b1c953 100644
--- a/gcc/tree-cfg.cc
+++ b/gcc/tree-cfg.cc
@@ -7734,11 +7734,14 @@ fold_loop_internal_call (gimple *g, tree value)
 test.  This should not happen as the guarded code should
 start with pre-header.  */
  gcc_assert (single_pred_edge (taken_edge->dest));
- taken_edge->dest->count
-   = taken_edge->dest->count.apply_scale (new_count,
-  old_count);
- scale_strictly_dominated_blocks (taken_edge->dest,
-  new_count, old_count);
+ if (old_count.nonzero_p ())
+   {
+ taken_edge->dest->count
+   = taken_edge->dest->count.apply_scale (new_count,
+  old_count);
+ scale_strictly_dominated_blocks (taken_edge->dest,
+  new_count, old_count);
+   }
}
}
 }


Fix division by zero in tree-ssa-loop-split

2023-08-10 Thread Jan Hubicka via Gcc-patches
Hi,
Profile update I added to tree-ssa-loop-split can divide by zero in
situation that the conditional is predicted with 0 probability which
is triggered by jump threading update in the testcase.

gcc/ChangeLog:

PR middle-end/110923
* tree-ssa-loop-split.cc (split_loop): Watch for division by zero.

gcc/testsuite/ChangeLog:

PR middle-end/110923
* gcc.dg/tree-ssa/pr110923.c: New test.

diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr110923.c 
b/gcc/testsuite/gcc.dg/tree-ssa/pr110923.c
new file mode 100644
index 000..8f5720a5e9e
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/pr110923.c
@@ -0,0 +1,14 @@
+/* { dg-do compile } */ 
+/* { dg-options "-O3 -fdump-tree-lsplit-details-blocks" } */
+int a, b, c, d;
+int main() {
+  for (a = 0; a < 2; a++) {
+if (b > 2)
+  c = 0;
+if (b > a)
+  d = 0;
+  }
+  return 0;
+}
+/* { dg-final { scan-tree-dump-times "loop split" 1 "lsplit" } } */
+/* { dg-final { scan-tree-dump-not "Invalid sum" "lsplit" } } */
diff --git a/gcc/tree-ssa-loop-split.cc b/gcc/tree-ssa-loop-split.cc
index 2f7918c6e65..64464802c1e 100644
--- a/gcc/tree-ssa-loop-split.cc
+++ b/gcc/tree-ssa-loop-split.cc
@@ -703,7 +703,7 @@ split_loop (class loop *loop1)
   split between of the two new loops.  Keep orignal estimate since
   it is likely better then completely dropping it.
 
-  TODO: If we know that onle of the new loops has constant
+  TODO: If we know that one of the new loops has constant
   number of iterations, we can do better.  We could also update
   upper bounds.  */
if (loop1->any_estimate
@@ -713,11 +713,15 @@ split_loop (class loop *loop1)
  ? true_edge->probability.to_sreal () : (sreal)1;
sreal scale2 = false_edge->probability.reliable_p ()
  ? false_edge->probability.to_sreal () : (sreal)1;
+   sreal div1 = loop1_prob.to_sreal ();
/* +1 to get header interations rather than latch iterations and 
then
   -1 to convert back.  */
-   loop1->nb_iterations_estimate
- = MAX sreal)loop1->nb_iterations_estimate.to_shwi () + 1) * 
scale
-/ loop1_prob.to_sreal ()).to_nearest_int () - 1, 0);
+   if (div1 != 0)
+ loop1->nb_iterations_estimate
+   = MAX sreal)loop1->nb_iterations_estimate.to_shwi () + 1)
+  * scale / div1).to_nearest_int () - 1, 0);
+   else
+ loop1->any_estimate = false;
loop2->nb_iterations_estimate
  = MAX sreal)loop2->nb_iterations_estimate.to_shwi () + 1) * 
scale2
 / profile_probability::very_likely ().to_sreal ())


[Bug middle-end/109578] fail to remove dead code due to division by zero

2023-04-20 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109578

--- Comment #5 from Andrew Pinski  ---
(In reply to Andrew Pinski from comment #3)
> Anyways maybe the issue with PR 29968 was a scheduling issue which was fixed
> later on that GCC didn't realize divide could trap.

I was right on that, it was a dup of bug 41239 which was fixed in GCC 4.5.0.
The problem was exactly what I thought it was, a trapping instruction being
scheduled before the call. And yes it has been fixed for a long time, 13 years
in fact.

[Bug middle-end/109578] fail to remove dead code due to division by zero

2023-04-20 Thread vincent-gcc at vinc17 dot net via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109578

--- Comment #4 from Vincent Lefèvre  ---
(In reply to Andrew Pinski from comment #3)
> Anyways maybe the issue with PR 29968 was a scheduling issue which was fixed
> later on that GCC didn't realize divide could trap.

OK, thanks, I can see your update marking PR 29968 as a duplicate of PR 41239
(fixed).

[Bug rtl-optimization/41239] Scheduler reorders division by zero before a call that might not return

2023-04-20 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=41239

Andrew Pinski  changed:

   What|Removed |Added

 CC||tiamat at komi dot mts.ru

--- Comment #7 from Andrew Pinski  ---
*** Bug 29968 has been marked as a duplicate of this bug. ***

[Bug c/29968] integer division by zero with optimization

2023-04-20 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=29968

Andrew Pinski  changed:

   What|Removed |Added

 Resolution|INVALID |DUPLICATE

--- Comment #6 from Andrew Pinski  ---
Dup of bug 41239 in the end which was fixed in GCC 4.5.0.

*** This bug has been marked as a duplicate of bug 41239 ***

[Bug c/29968] integer division by zero with optimization

2023-04-20 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=29968

--- Comment #5 from Andrew Pinski  ---
(In reply to Vincent Lefèvre from comment #4)
> (In reply to Andreas Schwab from comment #2)
> > Your program is invoking undefined behaviour.  You should not perform the
> > division if the divisor is zero.
> 
> But PR109578 Comment 1 says that side effects should be visible before
> undefined behavior occurs. Thus this bug should be reopened.

Except it can no longer reproduce it so the issue has been fixed a long time
ago.

[Bug middle-end/109578] fail to remove dead code due to division by zero

2023-04-20 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109578

--- Comment #3 from Andrew Pinski  ---
(In reply to Vincent Lefèvre from comment #2)
> (In reply to Andrew Pinski from comment #1)
> > We don't removing code before undefined behavior ...
> > That is GCC does not know that printf  does not have side effects.
> 
> Then GCC is incorrect in bug 29968, because it does the division *before*
> the printf.

Or was a bug which has since been fixed.

For sparc GCC 12.2.0 we get:
sethi   %hi(.LC0), %o0
callputs, 0
 or %o0, %lo(.LC0), %o0
ta  5

Anyways maybe the issue with PR 29968 was a scheduling issue which was fixed
later on that GCC didn't realize divide could trap.

[Bug c/29968] integer division by zero with optimization

2023-04-20 Thread vincent-gcc at vinc17 dot net via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=29968

Vincent Lefèvre  changed:

   What|Removed |Added

 CC||vincent-gcc at vinc17 dot net

--- Comment #4 from Vincent Lefèvre  ---
(In reply to Andreas Schwab from comment #2)
> Your program is invoking undefined behaviour.  You should not perform the
> division if the divisor is zero.

But PR109578 Comment 1 says that side effects should be visible before
undefined behavior occurs. Thus this bug should be reopened.

[Bug middle-end/109578] fail to remove dead code due to division by zero

2023-04-20 Thread vincent-gcc at vinc17 dot net via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109578

--- Comment #2 from Vincent Lefèvre  ---
(In reply to Andrew Pinski from comment #1)
> We don't removing code before undefined behavior ...
> That is GCC does not know that printf  does not have side effects.

Then GCC is incorrect in bug 29968, because it does the division *before* the
printf.

[Bug middle-end/109578] fail to remove dead code due to division by zero

2023-04-20 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109578

Andrew Pinski  changed:

   What|Removed |Added

 Resolution|--- |WONTFIX
 Status|UNCONFIRMED |RESOLVED

--- Comment #1 from Andrew Pinski  ---
We don't removing code before undefined behavior ...
That is GCC does not know that printf  does not have side effects.

[Bug middle-end/109578] New: fail to remove dead code due to division by zero

2023-04-20 Thread vincent-gcc at vinc17 dot net via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109578

Bug ID: 109578
   Summary: fail to remove dead code due to division by zero
   Product: gcc
   Version: 12.2.1
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: middle-end
  Assignee: unassigned at gcc dot gnu.org
  Reporter: vincent-gcc at vinc17 dot net
  Target Milestone: ---

This is about the opposite of the invalid bug 29968:

#include 

int f (int i, int k)
{
  if (k == 0)
printf ("k = 0\n");
  return i/k;
}

int main (void)
{
  return f (1, 0);
}

With gcc-12 (Debian 12.2.0-14) 12.2.0 and -O3 optimization, I get:

k = 0
zsh: illegal hardware instruction (core dumped)  ./tst

But since the case k == 0 corresponds to an undefined behavior (which is the
justification behind that GCC is correct in bug 29968), the code

  if (k == 0)
printf ("k = 0\n");

should have been removed as an optimization.

[Bug analyzer/99669] RFE: detect division by zero in analyzer

2023-03-20 Thread dmalcolm at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99669

David Malcolm  changed:

   What|Removed |Added

 CC||geoffreydgr at icloud dot com

--- Comment #3 from David Malcolm  ---
*** Bug 109201 has been marked as a duplicate of this bug. ***

Re: Division by zero on A53 which does not raise an exception

2022-11-29 Thread Szabolcs Nagy via Gcc
The 11/28/2022 21:37, Stephen Smith via Binutils wrote:
> I am working on a project which is using an A53 core.   The core does not 
> raise an exception if there is a division by zero (for either integer or 
> floating point division).

floating-point division by zero signals the FE_DIVBYZERO exception.
you can test this via fetestexcept(FE_DIVBYZERO).

integer operations must not affect fenv status flags so integer
division by zero does not do that.

if you want to *trap* division by zero, there is no reliable way
to do that in c (this is not related to particular cpus though).


Re: Division by zero on A53 which does not raise an exception

2022-11-29 Thread Richard Biener via Gcc
On Tue, Nov 29, 2022 at 5:39 AM Stephen Smith via Gcc  wrote:
>
> I am working on a project which is using an A53 core.   The core does not
> raise an exception if there is a division by zero (for either integer or
> floating point division).
>
> The designers chose to set status bits for the floating point case but not
> raise an exception.With the integer division no status bits are set.
>
> Does the GCC  compilers or Binutils assembler and linker have a way to deal
> with this issue on the ARM A53 processor?
>
> For Linux, was special support added in the kernel to help Glibc with this
> issue?  If so, I will comb the linux source tree.
>
> My project is using GCC 7.3.0

I'm second-guessing that you want to have an exception raised for
integer division by zero?  Since the C standard defines this as
invoking undefined behavior and GCC generally takes advantage
of this reliably getting an exception is difficult.  There's
-fsanitize=integer-divide-by-zero -fsanitize-undefined-trap-on-error
which you could use.

There are targets with options like -mcheck-zero-division but
arm is not amongst those.

Richard.

>
>


Division by zero on A53 which does not raise an exception

2022-11-28 Thread Stephen Smith via Gcc
I am working on a project which is using an A53 core.   The core does not 
raise an exception if there is a division by zero (for either integer or 
floating point division).

The designers chose to set status bits for the floating point case but not 
raise an exception.With the integer division no status bits are set.

Does the GCC  compilers or Binutils assembler and linker have a way to deal 
with this issue on the ARM A53 processor?  

For Linux, was special support added in the kernel to help Glibc with this 
issue?  If so, I will comb the linux source tree.

My project is using GCC 7.3.0




[PATCH] tree-optimization/106189 - avoid division by zero exception

2022-07-26 Thread Richard Biener via Gcc-patches
The diagnostic code can end up with zero sized array elements
with T[][0] and the wide-int code nicely avoids exceptions when
dividing by zero in one codepath but not in another.  The following
fixes the exception by using wide-int in both paths.

Bootstrapped and tested on x86_64-unknown-linux-gnu, pushed.

PR tree-optimization/106189
* gimple-array-bounds.cc (array_bounds_checker::check_mem_ref):
Divide using offset_ints.

* gcc.dg/pr106189.c: New testcase.
---
 gcc/gimple-array-bounds.cc  | 2 +-
 gcc/testsuite/gcc.dg/pr106189.c | 5 +
 2 files changed, 6 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/gcc.dg/pr106189.c

diff --git a/gcc/gimple-array-bounds.cc b/gcc/gimple-array-bounds.cc
index 0b48bdb0ae5..e190b93aa85 100644
--- a/gcc/gimple-array-bounds.cc
+++ b/gcc/gimple-array-bounds.cc
@@ -534,7 +534,7 @@ array_bounds_checker::check_mem_ref (location_t location, 
tree ref,
   int i = 0;
   if (aref.offmax[i] < -aref.sizrng[1] || aref.offmax[i = 1] > ubound)
 {
-  HOST_WIDE_INT tmpidx = aref.offmax[i].to_shwi () / eltsize.to_shwi ();
+  HOST_WIDE_INT tmpidx = (aref.offmax[i] / eltsize).to_shwi ();
 
   if (warning_at (location, OPT_Warray_bounds,
  "intermediate array offset %wi is outside array bounds "
diff --git a/gcc/testsuite/gcc.dg/pr106189.c b/gcc/testsuite/gcc.dg/pr106189.c
new file mode 100644
index 000..0eca8343c56
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pr106189.c
@@ -0,0 +1,5 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -Warray-bounds=2 -w" } */
+
+int a_n_0_0_a[][0];
+void a_n_0_0() { T(((char *)a_n_0_0_a)[1]); }
-- 
2.35.3


[Bug analyzer/99669] RFE: detect division by zero in analyzer

2022-06-08 Thread dmalcolm at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99669

David Malcolm  changed:

   What|Removed |Added

 Blocks||105887

--- Comment #2 from David Malcolm  ---
See also:
  https://clang.llvm.org/docs/analyzer/checkers.html#core-dividezero-c-c-objc


Referenced Bugs:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105887
[Bug 105887] RFE: clang analyzer warnings that GCC's -fanalyzer could implement

[Ada] Move messages on division by zero to the right operand

2022-01-06 Thread Pierre-Marie de Rodat via Gcc-patches
All compile-time messages about division by zero are now located at the
right operand. Previously some of them were located at the division
operator, which was inconsistent.

Tested on x86_64-pc-linux-gnu, committed on trunk

gcc/ada/

* sem_eval.adb (Eval_Arithmetic_Op): Add Loc parameter to all
calls to Apply_Compile_Time_Constraint_Error related to division
by zero.diff --git a/gcc/ada/sem_eval.adb b/gcc/ada/sem_eval.adb
--- a/gcc/ada/sem_eval.adb
+++ b/gcc/ada/sem_eval.adb
@@ -2117,6 +2117,7 @@ package body Sem_Eval is
 
  Apply_Compile_Time_Constraint_Error
(N, "division by zero", CE_Divide_By_Zero,
+Loc  => Sloc (Right),
 Warn => not Stat or SPARK_Mode = On);
  return;
 
@@ -2139,6 +2140,7 @@ package body Sem_Eval is
 
  Apply_Compile_Time_Constraint_Error
(N, "mod with zero divisor", CE_Divide_By_Zero,
+Loc  => Sloc (Right),
 Warn => not Stat or SPARK_Mode = On);
  return;
 
@@ -2159,6 +2161,7 @@ package body Sem_Eval is
 
  Apply_Compile_Time_Constraint_Error
(N, "rem with zero divisor", CE_Divide_By_Zero,
+Loc  => Sloc (Right),
 Warn => not Stat or SPARK_Mode = On);
  return;
 
@@ -2218,7 +2221,8 @@ package body Sem_Eval is
 else pragma Assert (Nkind (N) = N_Op_Divide);
if UR_Is_Zero (Right_Real) then
   Apply_Compile_Time_Constraint_Error
-(N, "division by zero", CE_Divide_By_Zero);
+(N, "division by zero", CE_Divide_By_Zero,
+ Loc => Sloc (Right));
   return;
end if;
 




[Bug analyzer/99669] RFE: detect division by zero in analyzer

2021-11-16 Thread dmalcolm at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99669

--- Comment #1 from David Malcolm  ---
I implemented a version of this (-Wanalyzer-tainted-divisor) for GCC 12 in:
  https://gcc.gnu.org/pipermail/gcc-patches/2021-November/584356.html

[Bug c/21438] Warning about division by zero depends on lexical form

2021-09-28 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=21438

Andrew Pinski  changed:

   What|Removed |Added

 Status|NEW |ASSIGNED
   Assignee|unassigned at gcc dot gnu.org  |pinskia at gcc dot 
gnu.org
   Last reconfirmed|2005-12-18 01:45:12 |2021-9-28
  Known to fail||

--- Comment #7 from Andrew Pinski  ---
(In reply to Manuel López-Ibáñez from comment #5)
> Subject: Bug 21438

The only thing this patch did was uniformed the code between the front-ends.

I am going to look into fix this once and for all.
GCC is the only compiler which warns for this case even.

[Bug tree-optimization/46352] ICE: division by zero with -fdump-tree-tracer

2021-08-08 Thread pinskia at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=46352

Andrew Pinski  changed:

   What|Removed |Added

 Status|UNCONFIRMED |RESOLVED
  Known to work||4.7.0
 Resolution|--- |FIXED
   Target Milestone|--- |4.7.0

--- Comment #3 from Andrew Pinski  ---
This condition will never happen in 4.7.0+.
Because we will not have the case where we have one BB there:
  if (n_basic_blocks_for_fn (fun) <= NUM_FIXED_BLOCKS + 1)
return 0;

[Bug analyzer/99669] New: RFE: detect division by zero in analyzer

2021-03-19 Thread dmalcolm at gcc dot gnu.org via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99669

Bug ID: 99669
   Summary: RFE: detect division by zero in analyzer
   Product: gcc
   Version: 11.0
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: analyzer
  Assignee: dmalcolm at gcc dot gnu.org
  Reporter: dmalcolm at gcc dot gnu.org
  Target Milestone: ---

-fanalyzer could probably warn about division by zero:

Consider this easy case (from
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89863#c7):

extern void g();

void f()
{
unsigned int vsync_rate_hz = 0;
unsigned int frame_time_microsec = 100 / vsync_rate_hz;

g();
}

See also bug 80744 (same idea but for C++)

PVS-Studio complains about this:
  https://www.viva64.com/en/w/v609/
  https://www.viva64.com/en/examples/v609/
which has interprocedural examples, and an example of a loop where we could
"know" that the iterator could be zero.

CWE-369: Divide By Zero:
  https://cwe.mitre.org/data/definitions/369.html

Re: [PATCH] libstdc++: Fix division by zero in std::sample

2020-10-20 Thread Patrick Palka via Gcc-patches
On Tue, 20 Oct 2020, Jonathan Wakely wrote:

> On 21/09/20 16:01 +0100, Jonathan Wakely wrote:
> > On 18/09/20 21:08 -0400, Patrick Palka via Libstdc++ wrote:
> > > This fixes a division by zero in the selection-sampling std::__search
> > > overload when the input range is empty (and hence __unsampled_sz is 0).
> > > 
> > > Tested on x86_64-pc-linux-gnu.
> > > 
> > > libstdc++-v3/ChangeLog:
> > > 
> > >   * include/bits/stl_algo.h (__sample): Exit early when the
> > >   input range is empty.
> > >   * testsuite/25_algorithms/sample/3.cc: New test.
> > > ---
> > > libstdc++-v3/include/bits/stl_algo.h  |  3 ++
> > > .../testsuite/25_algorithms/sample/3.cc   | 50 +++
> > > 2 files changed, 53 insertions(+)
> > > create mode 100644 libstdc++-v3/testsuite/25_algorithms/sample/3.cc
> > 
> > OK, thanks.
> 
> Could you please backport this to all branches too.

Ah yes, sorry about losing track of this patch.  I should be able to get
the backports done by end of today.



Re: [PATCH] libstdc++: Fix division by zero in std::sample

2020-10-20 Thread Jonathan Wakely via Gcc-patches

On 21/09/20 16:01 +0100, Jonathan Wakely wrote:

On 18/09/20 21:08 -0400, Patrick Palka via Libstdc++ wrote:

This fixes a division by zero in the selection-sampling std::__search
overload when the input range is empty (and hence __unsampled_sz is 0).

Tested on x86_64-pc-linux-gnu.

libstdc++-v3/ChangeLog:

* include/bits/stl_algo.h (__sample): Exit early when the
input range is empty.
* testsuite/25_algorithms/sample/3.cc: New test.
---
libstdc++-v3/include/bits/stl_algo.h  |  3 ++
.../testsuite/25_algorithms/sample/3.cc   | 50 +++
2 files changed, 53 insertions(+)
create mode 100644 libstdc++-v3/testsuite/25_algorithms/sample/3.cc


OK, thanks.


Could you please backport this to all branches too.




Re: [PATCH] libstdc++: Fix division by zero in std::sample

2020-09-21 Thread Jonathan Wakely via Gcc-patches

On 18/09/20 21:08 -0400, Patrick Palka via Libstdc++ wrote:

This fixes a division by zero in the selection-sampling std::__search
overload when the input range is empty (and hence __unsampled_sz is 0).

Tested on x86_64-pc-linux-gnu.

libstdc++-v3/ChangeLog:

* include/bits/stl_algo.h (__sample): Exit early when the
input range is empty.
* testsuite/25_algorithms/sample/3.cc: New test.
---
libstdc++-v3/include/bits/stl_algo.h  |  3 ++
.../testsuite/25_algorithms/sample/3.cc   | 50 +++
2 files changed, 53 insertions(+)
create mode 100644 libstdc++-v3/testsuite/25_algorithms/sample/3.cc


OK, thanks.




Re: [PATCH] libstdc++: Fix division by zero in std::sample

2020-09-21 Thread Patrick Palka via Gcc-patches
On Fri, 18 Sep 2020, Patrick Palka wrote:

> This fixes a division by zero in the selection-sampling std::__search

Whoops, this line say std::__sample, not std::__search.

> overload when the input range is empty (and hence __unsampled_sz is 0).
> 
> Tested on x86_64-pc-linux-gnu.
> 
> libstdc++-v3/ChangeLog:
> 
>   * include/bits/stl_algo.h (__sample): Exit early when the
>   input range is empty.
>   * testsuite/25_algorithms/sample/3.cc: New test.
> ---
>  libstdc++-v3/include/bits/stl_algo.h  |  3 ++
>  .../testsuite/25_algorithms/sample/3.cc   | 50 +++
>  2 files changed, 53 insertions(+)
>  create mode 100644 libstdc++-v3/testsuite/25_algorithms/sample/3.cc
> 
> diff --git a/libstdc++-v3/include/bits/stl_algo.h 
> b/libstdc++-v3/include/bits/stl_algo.h
> index a0b96c61798..2478b5857c1 100644
> --- a/libstdc++-v3/include/bits/stl_algo.h
> +++ b/libstdc++-v3/include/bits/stl_algo.h
> @@ -5775,6 +5775,9 @@ _GLIBCXX_BEGIN_NAMESPACE_ALGO
>using _Gen = remove_reference_t<_UniformRandomBitGenerator>;
>using __uc_type = common_type_t;
>  
> +  if (__first == __last)
> + return __out;
> +
>__distrib_type __d{};
>_Size __unsampled_sz = std::distance(__first, __last);
>__n = std::min(__n, __unsampled_sz);
> diff --git a/libstdc++-v3/testsuite/25_algorithms/sample/3.cc 
> b/libstdc++-v3/testsuite/25_algorithms/sample/3.cc
> new file mode 100644
> index 000..e89c40e27ee
> --- /dev/null
> +++ b/libstdc++-v3/testsuite/25_algorithms/sample/3.cc
> @@ -0,0 +1,50 @@
> +// Copyright (C) 2020 Free Software Foundation, Inc.
> +//
> +// This file is part of the GNU ISO C++ Library.  This library is free
> +// software; you can redistribute it and/or modify it under the
> +// terms of the GNU General Public License as published by the
> +// Free Software Foundation; either version 3, or (at your option)
> +// any later version.
> +
> +// This library is distributed in the hope that it will be useful,
> +// but WITHOUT ANY WARRANTY; without even the implied warranty of
> +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
> +// GNU General Public License for more details.
> +
> +// You should have received a copy of the GNU General Public License along
> +// with this library; see the file COPYING3.  If not see
> +// <http://www.gnu.org/licenses/>.
> +
> +// { dg-options "-std=gnu++17" }
> +// { dg-do run { target c++17 } }
> +// { dg-require-cstdint "" }
> +
> +#include 
> +#include 
> +#include 
> +#include 
> +
> +std::mt19937 rng;
> +
> +using std::sample;
> +using __gnu_test::test_container;
> +using __gnu_test::output_iterator_wrapper;
> +using __gnu_test::forward_iterator_wrapper;
> +
> +void
> +test01()
> +{
> +  const int in = 0;
> +  test_container pop(, );
> +  int out;
> +  test_container samp(,  + 1);
> +
> +  auto it = sample(pop.begin(), pop.end(), samp.begin(), 1, rng);
> +  VERIFY( it.ptr ==  );
> +}
> +
> +int
> +main()
> +{
> +  test01();
> +}
> -- 
> 2.28.0.497.g54e85e7af1
> 
> 



[PATCH] libstdc++: Fix division by zero in std::sample

2020-09-18 Thread Patrick Palka via Gcc-patches
This fixes a division by zero in the selection-sampling std::__search
overload when the input range is empty (and hence __unsampled_sz is 0).

Tested on x86_64-pc-linux-gnu.

libstdc++-v3/ChangeLog:

* include/bits/stl_algo.h (__sample): Exit early when the
input range is empty.
* testsuite/25_algorithms/sample/3.cc: New test.
---
 libstdc++-v3/include/bits/stl_algo.h  |  3 ++
 .../testsuite/25_algorithms/sample/3.cc   | 50 +++
 2 files changed, 53 insertions(+)
 create mode 100644 libstdc++-v3/testsuite/25_algorithms/sample/3.cc

diff --git a/libstdc++-v3/include/bits/stl_algo.h 
b/libstdc++-v3/include/bits/stl_algo.h
index a0b96c61798..2478b5857c1 100644
--- a/libstdc++-v3/include/bits/stl_algo.h
+++ b/libstdc++-v3/include/bits/stl_algo.h
@@ -5775,6 +5775,9 @@ _GLIBCXX_BEGIN_NAMESPACE_ALGO
   using _Gen = remove_reference_t<_UniformRandomBitGenerator>;
   using __uc_type = common_type_t;
 
+  if (__first == __last)
+   return __out;
+
   __distrib_type __d{};
   _Size __unsampled_sz = std::distance(__first, __last);
   __n = std::min(__n, __unsampled_sz);
diff --git a/libstdc++-v3/testsuite/25_algorithms/sample/3.cc 
b/libstdc++-v3/testsuite/25_algorithms/sample/3.cc
new file mode 100644
index 000..e89c40e27ee
--- /dev/null
+++ b/libstdc++-v3/testsuite/25_algorithms/sample/3.cc
@@ -0,0 +1,50 @@
+// Copyright (C) 2020 Free Software Foundation, Inc.
+//
+// This file is part of the GNU ISO C++ Library.  This library is free
+// software; you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the
+// Free Software Foundation; either version 3, or (at your option)
+// any later version.
+
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License along
+// with this library; see the file COPYING3.  If not see
+// <http://www.gnu.org/licenses/>.
+
+// { dg-options "-std=gnu++17" }
+// { dg-do run { target c++17 } }
+// { dg-require-cstdint "" }
+
+#include 
+#include 
+#include 
+#include 
+
+std::mt19937 rng;
+
+using std::sample;
+using __gnu_test::test_container;
+using __gnu_test::output_iterator_wrapper;
+using __gnu_test::forward_iterator_wrapper;
+
+void
+test01()
+{
+  const int in = 0;
+  test_container pop(, );
+  int out;
+  test_container samp(,  + 1);
+
+  auto it = sample(pop.begin(), pop.end(), samp.begin(), 1, rng);
+  VERIFY( it.ptr ==  );
+}
+
+int
+main()
+{
+  test01();
+}
-- 
2.28.0.497.g54e85e7af1



[Bug tree-optimization/96807] Division by zero produces zero with gcc -O2

2020-08-30 Thread pinskia at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96807

Andrew Pinski  changed:

   What|Removed |Added

 Status|UNCONFIRMED |RESOLVED
 Resolution|--- |INVALID

--- Comment #2 from Andrew Pinski  ---
>Instead of giving division by zero or infinity, it gives zero.

Is that even defined in Fortran, I think the answer is NO. so closing as
invalid.

[Bug tree-optimization/96807] Division by zero produces zero with gcc -O2

2020-08-27 Thread rguenth at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96807

--- Comment #1 from Richard Biener  ---
Division by zero is undefined behavior so we simplify 1/x to 0 if x is known
to be not one [unless there's literal 1/0 which is sometimes used to generate
traps].

[Bug tree-optimization/96807] New: Division by zero produces zero with gcc -O2

2020-08-26 Thread fazedo at gmail dot com
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96807

Bug ID: 96807
   Summary: Division by zero produces zero with gcc -O2
   Product: gcc
   Version: unknown
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: tree-optimization
  Assignee: unassigned at gcc dot gnu.org
  Reporter: fazedo at gmail dot com
  Target Milestone: ---

Hello,

The following code produces 1/0 = 0 with gcc -O2: 



#include 
#include 

int main(int argn, char** argc){
  unsigned base = argn>1 ? atoi(argc[1]) : 0;
  if (base!=1) printf("%d\n", 1/base); // produces 0 for base=0 with -O2
  return 0; 
}


The same behavior occurs with clang but not with icc.  If 1/base is not guarded
by if or if base is a signed integer, it produces a floating point exception
even with -O2. 

As a result, Fortran's intrinsic power operator (**) applied to integers is
producing wrong results when the base is zero and the exponent is negative.
Instead of giving division by zero or infinity, it gives zero.

The code given below shows that base**(-1) yields 0 when base=0. 

It is my understanding that gfortran calls functions pow_iX_iY from
libgfortran/generated. These functions are correctly coded but they produce
0**n=0 for n<0 due to optimizations when libgfortran is compiled. 


program power
  implicit none
  integer (kind = 4) :: base = 0

  print *, base**(-1)   ! produces 0
  print *, real(base, 4)**(-1)  ! produces infinity
end program



By the way, is there any advantage to using the pow_XX_YY.c functions on
libgfortran/generated instead of __powiXX2 (and its integer version) defined
for __builtin_powi on libgcc2.c?

It seems to me that libgcc2's version reads much better and should be a little
faster because it saves the first multiplication (by pow=1).

The only difference in behaviour I see is that when the exponent is negative
and the base if a floating point type, libgcc2 calculates 1/(x**(-n)) while
libgfortran calculates (1/x)**(-n). The first version being more accurate.

I am using gcc 9.3.0 on x86-64.

Best regards,
Fabio Azevedo

Re: [PATCH] Fortran : ICE for division by zero in declaration PR95882

2020-08-26 Thread Thomas Koenig via Gcc-patches

Hi Mark,


OK to commit and backport?


OK.  Thanks for the patch!

Best regards

Thomas


[PATCH] Fortran : ICE for division by zero in declaration PR95882

2020-08-25 Thread Mark Eggleston

Second attempt, this time with the correct attachment.

OK to commit and backport?

[PATCH] Fortran  : ICE for division by zero in declaration PR95882

A length expression containing a divide by zero in a character
declaration will result in an ICE if the constant is anymore
complicated that a contant divided by a constant.

The cause was that char_len_param_value can return MATCH_YES
even if a divide by zero was seen.  Prior to returning check
whether a divide by zero was seen and if so set it to MATCH_ERROR.

2020-08-24  Mark Eggleston 

gcc/fortran

    PR fortran/95882
    * decl.c (char_len_param_value): Check gfc_seen_div0 and
    it is set return MATCH_ERROR.

2020-08-24  Mark Eggleston 

gcc/testsuite/

    PR fortran/95882
    * gfortran.dg/pr95882_1.f90: New test.
    * gfortran.dg/pr95882_2.f90: New test.
    * gfortran.dg/pr95882_3.f90: New test.
    * gfortran.dg/pr95882_4.f90: New test.
    * gfortran.dg/pr95882_5.f90: New test.

--
https://www.codethink.co.uk/privacy.html

>From e97963ec8edc58217d2ff225c58256ebd61c8e7c Mon Sep 17 00:00:00 2001
From: Mark Eggleston 
Date: Fri, 21 Aug 2020 06:39:30 +0100
Subject: [PATCH] Fortran  : ICE for division by zero in declaration PR95882

A length expression containing a divide by zero in a character
declaration will result in an ICE if the constant is anymore
complicated that a contant divided by a constant.

The cause was that char_len_param_value can return MATCH_YES
even if a divide by zero was seen.  Prior to returning check
whether a divide by zero was seen and if so set it to MATCH_ERROR.

2020-08-24  Mark Eggleston  

gcc/fortran

	PR fortran/95882
	* decl.c (char_len_param_value): Check gfc_seen_div0 and
	it is set return MATCH_ERROR.

2020-08-24  Mark Eggleston  

gcc/testsuite/

	PR fortran/95882
	* gfortran.dg/pr95882_1.f90: New test.
	* gfortran.dg/pr95882_2.f90: New test.
	* gfortran.dg/pr95882_3.f90: New test.
	* gfortran.dg/pr95882_4.f90: New test.
	* gfortran.dg/pr95882_5.f90: New test.
---
 gcc/fortran/decl.c  | 3 +++
 gcc/testsuite/gfortran.dg/pr95882_1.f90 | 8 
 gcc/testsuite/gfortran.dg/pr95882_2.f90 | 6 ++
 gcc/testsuite/gfortran.dg/pr95882_3.f90 | 6 ++
 gcc/testsuite/gfortran.dg/pr95882_4.f90 | 7 +++
 gcc/testsuite/gfortran.dg/pr95882_5.f90 | 6 ++
 6 files changed, 36 insertions(+)
 create mode 100644 gcc/testsuite/gfortran.dg/pr95882_1.f90
 create mode 100644 gcc/testsuite/gfortran.dg/pr95882_2.f90
 create mode 100644 gcc/testsuite/gfortran.dg/pr95882_3.f90
 create mode 100644 gcc/testsuite/gfortran.dg/pr95882_4.f90
 create mode 100644 gcc/testsuite/gfortran.dg/pr95882_5.f90

diff --git a/gcc/fortran/decl.c b/gcc/fortran/decl.c
index d854b2a0307..c612b492f3e 100644
--- a/gcc/fortran/decl.c
+++ b/gcc/fortran/decl.c
@@ -1146,6 +1146,9 @@ char_len_param_value (gfc_expr **expr, bool *deferred)
   gfc_free_expr (e);
 }
 
+  if (gfc_seen_div0)
+m = MATCH_ERROR;
+
   return m;
 
 syntax:
diff --git a/gcc/testsuite/gfortran.dg/pr95882_1.f90 b/gcc/testsuite/gfortran.dg/pr95882_1.f90
new file mode 100644
index 000..c254bddf494
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr95882_1.f90
@@ -0,0 +1,8 @@
+! { dg-do compile }
+
+module m
+   type t
+  character(((0)/0)) :: c  ! { dg-error "Division by zero" }
+   end type
+end
+
diff --git a/gcc/testsuite/gfortran.dg/pr95882_2.f90 b/gcc/testsuite/gfortran.dg/pr95882_2.f90
new file mode 100644
index 000..d308f0c3181
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr95882_2.f90
@@ -0,0 +1,6 @@
+! { dg-do compile }
+
+module m
+   character(0/(0)) :: c = '123456789'  ! { dg-error "Division by zero" }
+end
+
diff --git a/gcc/testsuite/gfortran.dg/pr95882_3.f90 b/gcc/testsuite/gfortran.dg/pr95882_3.f90
new file mode 100644
index 000..bd849135480
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr95882_3.f90
@@ -0,0 +1,6 @@
+! { dg-do compile }
+
+subroutine s(c)
+   character(((0)/0)) :: c  ! { dg-error "Division by zero" }
+end
+
diff --git a/gcc/testsuite/gfortran.dg/pr95882_4.f90 b/gcc/testsuite/gfortran.dg/pr95882_4.f90
new file mode 100644
index 000..52892d32b8b
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr95882_4.f90
@@ -0,0 +1,7 @@
+! { dg-do compile }
+
+program p
+   character(((0)/0)) :: c  ! { dg-error "Division by zero" }
+   common /x/ c
+end
+
diff --git a/gcc/testsuite/gfortran.dg/pr95882_5.f90 b/gcc/testsuite/gfortran.dg/pr95882_5.f90
new file mode 100644
index 000..dcdf5304052
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr95882_5.f90
@@ -0,0 +1,6 @@
+! { dg-do compile }
+
+program p
+   character(0/(0)) :: c = '123456789'  ! { dg-error "Division by zero" }
+   common c
+end
-- 
2.11.0



Re: [PATCH] Fortran : ICE for division by zero in declaration PR95882

2020-08-25 Thread Mark Eggleston



On 25/08/2020 07:13, Mark Eggleston wrote:


On 24/08/2020 17:42, Thomas Koenig wrote:

Hi Mark,


OK to commit and backport?


The test cases mentioned in the ChangeLog are not in the
patch, instead there is the test case for PR 96624.

Could you correct that?

Whoops, yes I'll fix that.

It is actually the wrong attachment, I'll try again.


Best regards

Thomas


--
https://www.codethink.co.uk/privacy.html



Re: [PATCH] Fortran : ICE for division by zero in declaration PR95882

2020-08-25 Thread Mark Eggleston



On 24/08/2020 17:42, Thomas Koenig wrote:

Hi Mark,


OK to commit and backport?


The test cases mentioned in the ChangeLog are not in the
patch, instead there is the test case for PR 96624.

Could you correct that?

Whoops, yes I'll fix that.


Best regards

Thomas


--
https://www.codethink.co.uk/privacy.html



Re: [PATCH] Fortran : ICE for division by zero in declaration PR95882

2020-08-24 Thread Thomas Koenig via Gcc-patches

Hi Mark,


OK to commit and backport?


The test cases mentioned in the ChangeLog are not in the
patch, instead there is the test case for PR 96624.

Could you correct that?

Best regards

Thomas


[PATCH] Fortran : ICE for division by zero in declaration PR95882

2020-08-24 Thread Mark Eggleston

Please find attached a fix for PR95882.

Tested on x86_64 with bootstrap.

OK to commit and backport?

Fortran  : ICE for division by zero in declaration PR95882

A length expression containing a divide by zero in a character
declaration will result in an ICE if the constant is anymore
complicated that a contant divided by a constant.

The cause was that char_len_param_value can return MATCH_YES
even if a divide by zero was seen.  Prior to returning check
whether a divide by zero was seen and if so set it to MATCH_ERROR.

2020-08-24  Mark Eggleston 

gcc/fortran

    PR fortran/95882
    * decl.c (char_len_param_value): Check gfc_seen_div0 and
    if it is set return MATCH_ERROR.

2020-08-24  Mark Eggleston 

gcc/testsuite/

    PR fortran/95882
    * gfortran.dg/pr95882_1.f90: New test.
    * gfortran.dg/pr95882_2.f90: New test.
    * gfortran.dg/pr95882_3.f90: New test.
    * gfortran.dg/pr95882_4.f90: New test.
    * gfortran.dg/pr95882_5.f90: New test.

--
https://www.codethink.co.uk/privacy.html

>From ab94bb744a7d64751f6b93cc56ad3ed5fe5cfc81 Mon Sep 17 00:00:00 2001
From: Mark Eggleston 
Date: Mon, 17 Aug 2020 13:50:28 +0100
Subject: [PATCH] Fortran  : Runtime error, reshape constant array assignment
 PR96624

When assigning a reshaped constant array of shape [2,0] to a
variable fails with an invalid memory access.  If a varibale
with the parameter attribute is initialised with the same reshape
there is no runtime error.

2020-08-20  Steven G. Kargl  

gcc/fortran/

	PR fortran/96624
	* simplify.c (gfc_simplifiy_reshape): Add new variable "zerosize".
	Set zerosize if any of the result shape ranks are zero.  After
	setting the result shapes, if zerosize is set jump to new label
	"sizezero".  Add label "sizezero" just before clearing index and
	returning result.

2020-08-20  Mark Eggleston  

gcc/testsuite/

	PR fortran/96624
	*gfortran/pr96624.f90: New test.
---
 gcc/fortran/simplify.c| 11 ++-
 gcc/testsuite/gfortran.dg/pr96624.f90 | 10 ++
 2 files changed, 20 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/gfortran.dg/pr96624.f90

diff --git a/gcc/fortran/simplify.c b/gcc/fortran/simplify.c
index eb8b2afeb29..0d77d289651 100644
--- a/gcc/fortran/simplify.c
+++ b/gcc/fortran/simplify.c
@@ -6721,6 +6721,7 @@ gfc_simplify_reshape (gfc_expr *source, gfc_expr *shape_exp,
   unsigned long j;
   size_t nsource;
   gfc_expr *e, *result;
+  bool zerosize = false;
 
   /* Check that argument expression types are OK.  */
   if (!is_constant_array_expr (source)
@@ -6843,7 +6844,14 @@ gfc_simplify_reshape (gfc_expr *source, gfc_expr *shape_exp,
   result->rank = rank;
   result->shape = gfc_get_shape (rank);
   for (i = 0; i < rank; i++)
-mpz_init_set_ui (result->shape[i], shape[i]);
+{
+  mpz_init_set_ui (result->shape[i], shape[i]);
+  if (shape[i] == 0)
+	zerosize = true;
+}
+ 
+  if (zerosize)
+goto sizezero;
 
   while (nsource > 0 || npad > 0)
 {
@@ -6893,6 +6901,7 @@ inc:
   break;
 }
 
+sizezero:
   mpz_clear (index);
 
   return result;
diff --git a/gcc/testsuite/gfortran.dg/pr96624.f90 b/gcc/testsuite/gfortran.dg/pr96624.f90
new file mode 100644
index 000..a4cfe5c3279
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr96624.f90
@@ -0,0 +1,10 @@
+! { dg-do run }
+
+program test
+  integer :: a(2,0)
+  character(4) :: buffer
+  a = reshape([1,2,3,4], [2,0])
+  write(buffer,"(2a1)") ">", "<"
+  if (trim(buffer).ne."><") stop 1
+end
+
-- 
2.11.0



Re: [PATCH] RISC-V: align RISC-V software division with hardware specification in case of division by zero

2020-06-02 Thread Jim Wilson
On Fri, May 29, 2020 at 1:53 AM MOSER Virginie via Gcc-patches
 wrote:
> The assembly code in libgcc/config/riscv/div.S does not handle the division 
> by zero as specified in the riscv-spec v2.2 chapter 6.2 in case of signed 
> division:

This looks OK.  There are some administrative comments to make here.

FSF policy requires copyright assignments.  I don't see one for you or
your employer.  If you are serious about contributing to GNU projects.
you need to get a copyright assignment.  This patch is small enough
that I can accept it, but I may not be able to accept the next one.
If you don't get a copyright assignment, you might consider filing bug
reports instead and let someone with an assignment write the patch.

The patch is mime encoded which is inconvenient.  The patch also got
corrupted somehow.  I had to edit it before I could get it to apply.
Or maybe the patch was for an older gcc version?  git format-patch and
git send-email is a good way to create and send a patch.  Or you can
file a bug report and add the patch as an attachment there.

ChangeLog entries should describe what change was made.  Not why it
was made.  The why should go into the git commit or comments in the
code.  I rewrote the ChangeLog entry.

We prefer lines that are less than 80 characters.  I moved the comment
to a separate line and also fixed some other nearby lines.  Comments
end with a period and two spaces.

I fixed up the patch, tested it, and committed it.  I will send the
patch I committed.

Jim


[PATCH] RISC-V: align RISC-V software division with hardware specification in case of division by zero

2020-05-29 Thread MOSER Virginie via Gcc-patches
The assembly code in libgcc/config/riscv/div.S does not handle the division by 
zero as specified in the riscv-spec v2.2 chapter 6.2 in case of signed division:

"The quotient of division by zero has all bits set, i.e. 2XLEN−1 for unsigned 
division or−1 for signed division."

When a negative number is divided by zero in the __divdi3 function, the result 
is 1 instead of -1.

As soon as there exists a specific implementation for the software division for 
the RISC-V and although that the C language allows unspecified result in case 
of division by zero, it would be worth aligning the software RISC-V division 
with the hardware implementation so that the compliance tests could pass 
whatever the -mno-div or -mdiv flag value.
Especially in the case where the patch is simple, does not add additional code 
size nor execution time.

The patch proposes that when the dividend is negative, a zero divisor is 
considered as negative so that the result of the unsigned division will not be 
inverted. This consists of exchanging a "branch greater or equal zero (bgez)" 
with a "branch greater than zero (bgtz)".

Virginie

---

ChangeLog

*libgcc/config/riscv/div.S: Change handling of signed division by zero in case 
of negative dividend to align with RISC-V specification for hardware division.



diff --git a/libgcc/config/riscv/div.S b/libgcc/config/riscv/div.S
index 922a4338042..57f5856e11d 100644
--- a/libgcc/config/riscv/div.S
+++ b/libgcc/config/riscv/div.S
@@ -107,7 +107,8 @@ FUNC_END (__umoddi3)
   /* Handle negative arguments to __divdi3.  */
.L10:
   neg   a0, a0
-  bgez  a1, .L12  /* Compute __udivdi3(-a0, a1), then negate the result.  
*/
+  bgtz  a1, .L12  /* Compute __udivdi3(-a0, a1), then negate the result.  
*/
+  /* Zero is handled as a negative so that the result will 
not be inverted */
   neg   a1, a1
   j __udivdi3 /* Compute __udivdi3(-a0, -a1).  */


Re: PR fortran/95053 - division by zero constants

2020-05-17 Thread Thomas Koenig via Gcc-patches

Am 15.05.20 um 22:33 schrieb Harald Anlauf:

Here's a new attempt to finally fix this PR and any known fallout.

In order to handle division by zero in declarations, but still accept the
code snippet adapted from 521.wrf_r (from spec2017), I removed the hunk
that was added to fix PR94399, and deferred the handling to a later stage.

One case regarding array shapes is handled in variable_decl in decl.c, the
other one regarding PDTs is handled in gfc_get_pdt_instance in the same
file.  While at it, I improved the error message to notify the user if an
expression that should be of INTEGER type isn't.

Regtests with no new failures on x86_64-pc-linux-gnu, after adjusting
error messages for test dec_structure_23.f90.

OK for trunk?


I think this is a good approach (and a better error message, too).

So, OK, and thanks for the patch!

Regards

Thomas


PR fortran/95053 - division by zero constants

2020-05-15 Thread Harald Anlauf
Here's a new attempt to finally fix this PR and any known fallout.

In order to handle division by zero in declarations, but still accept the
code snippet adapted from 521.wrf_r (from spec2017), I removed the hunk
that was added to fix PR94399, and deferred the handling to a later stage.

One case regarding array shapes is handled in variable_decl in decl.c, the
other one regarding PDTs is handled in gfc_get_pdt_instance in the same
file.  While at it, I improved the error message to notify the user if an
expression that should be of INTEGER type isn't.

Regtests with no new failures on x86_64-pc-linux-gnu, after adjusting
error messages for test dec_structure_23.f90.

OK for trunk?

Thanks,
Harald


PR fortran/95053 - division by zero constants

Partially revert the fix for PR93499.  Replace by checks for valid
expressions in the declaration of array shape and PDT KIND and LEN
expressions at a later stage.

gcc/fortran/

2020-05-15  Harald Anlauf  

PR fortran/95053
* arith.c (gfc_divide): Revert hunk introduced by patch for
PR93499.
* decl.c (variable_decl): Generate error for array shape not being
an INTEGER constant.
(gfc_get_pdt_instance): Generate error if KIND or LEN expressions
in declaration of a PDT instance do not simplify to INTEGER
constants.

gcc/testsuite/

2020-05-15  Harald Anlauf  

PR fortran/95053
* gfortran.dg/dec_structure_23.f90: Adjust to new error messages.
* gfortran.dg/pr95053_2.f90: New test.
* gfortran.dg/pr95053_3.f90: New test.

diff --git a/gcc/fortran/arith.c b/gcc/fortran/arith.c
index dd72f44d377..c770569eb81 100644
--- a/gcc/fortran/arith.c
+++ b/gcc/fortran/arith.c
@@ -1806,38 +1806,6 @@ gfc_multiply (gfc_expr *op1, gfc_expr *op2)
 gfc_expr *
 gfc_divide (gfc_expr *op1, gfc_expr *op2)
 {
-  if (op2 && op2->expr_type == EXPR_CONSTANT)
-{
-  arith rc = ARITH_OK;
-  switch (op2->ts.type)
-	{
-	case BT_INTEGER:
-	  /* non-integer divided by integer 0 is handled elsewhere.  */
-	  if (mpz_sgn (op2->value.integer) == 0
-	  && op1->ts.type == BT_INTEGER)
-	rc = ARITH_DIV0;
-	  break;
-	case BT_REAL:
-	  if (mpfr_sgn (op2->value.real) == 0
-	  && flag_range_check == 1)
-	rc = ARITH_DIV0;
-	  break;
-	case BT_COMPLEX:
-	  if (mpc_cmp_si_si (op2->value.complex, 0, 0) == 0
-	  && flag_range_check == 1)
-	rc = ARITH_DIV0;
-	  break;
-	default:
-	  /* basic type is non-numeric, handle this elsewhere.  */
-	  break;
-	}
-  if (rc == ARITH_DIV0)
-	{
-	  gfc_seen_div0 = true;
-	  gfc_error ("Division by zero at %L", >where);
-	  return NULL;
-	}
-}
   return eval_intrinsic_f3 (INTRINSIC_DIVIDE, gfc_arith_divide, op1, op2);
 }

diff --git a/gcc/fortran/decl.c b/gcc/fortran/decl.c
index 9cc81361f43..3ad5559c3ec 100644
--- a/gcc/fortran/decl.c
+++ b/gcc/fortran/decl.c
@@ -2607,6 +2607,14 @@ variable_decl (int elem)
 	  gfc_free_expr (e);
 	}

+	  if (not_constant && e->ts.type != BT_INTEGER)
+	{
+	  gfc_error ("Explicit array shape at %C must be constant of "
+			 "INTEGER type and not %s type",
+			 gfc_basic_typename (e->ts.type));
+	  m = MATCH_ERROR;
+	  goto cleanup;
+	}
 	  if (not_constant)
 	{
 	  gfc_error ("Explicit shaped array with nonconstant bounds at %C");
@@ -3741,8 +3749,9 @@ gfc_get_pdt_instance (gfc_actual_arglist *param_list, gfc_symbol **sym,
   if (kind_expr)
 	{
 	  /* Try simplification even for LEN expressions.  */
+	  bool ok;
 	  gfc_resolve_expr (kind_expr);
-	  gfc_simplify_expr (kind_expr, 1);
+	  ok = gfc_simplify_expr (kind_expr, 1);
 	  /* Variable expressions seem to default to BT_PROCEDURE.
 	 TODO find out why this is and fix it.  */
 	  if (kind_expr->ts.type != BT_INTEGER
@@ -3753,6 +3762,12 @@ gfc_get_pdt_instance (gfc_actual_arglist *param_list, gfc_symbol **sym,
 			 gfc_basic_typename (kind_expr->ts.type));
 	  goto error_return;
 	}
+	  if (kind_expr->ts.type == BT_INTEGER && !ok)
+	{
+	  gfc_error ("The parameter expression at %C does not "
+			 "simplify to an INTEGER constant");
+	  goto error_return;
+	}

 	  tail->expr = gfc_copy_expr (kind_expr);
 	}
diff --git a/gcc/testsuite/gfortran.dg/dec_structure_23.f90 b/gcc/testsuite/gfortran.dg/dec_structure_23.f90
index 78db344e0fc..39e5369c056 100644
--- a/gcc/testsuite/gfortran.dg/dec_structure_23.f90
+++ b/gcc/testsuite/gfortran.dg/dec_structure_23.f90
@@ -13,8 +13,8 @@ program p
   integer :: nn
   real :: rr
   structure /s/
-integer x(n)/1/   ! { dg-error "array with nonconstant bounds" }
+integer x(n)/1/   ! { dg-error "must be constant of INTEGER type" }
 integer xx(nn)  /1/   ! { dg-error "array with nonconstant bounds" }
-integer xxx(rr) /1.0/ ! { dg-error &quo

Re: [Patch] PR fortran/93499 - ICE on division by zero in declaration statements

2020-05-10 Thread Thomas Koenig via Gcc-patches

Hi Harald,


the attached should be mostly self-explaining.  Division by zero handling
appeared to be incomplete.  It was not dealt with properly when occurring
in declaration statements.  We now try to handle this.

OK for mainline?


OK.

Thanks for the patch!

Regards

Thomas


[Patch] PR fortran/93499 - ICE on division by zero in declaration statements

2020-05-09 Thread Harald Anlauf
Hi,

the attached should be mostly self-explaining.  Division by zero handling
appeared to be incomplete.  It was not dealt with properly when occurring
in declaration statements.  We now try to handle this.

OK for mainline?

Thanks,
Harald



PR fortran/93499 - ICE on division by zero in declaration statements

Division by zero in declaration statements could sometimes
generate NULL pointers being passed around that lead to ICEs.

gcc/fortran/ChangeLog:

2020-05-09  Harald Anlauf  

PR fortran/93499
* arith.c (gfc_divide): Catch division by zero.
(eval_intrinsic_f3): Safeguard for NULL operands.

gcc/testsuite/ChangeLog:

2020-05-09  Harald Anlauf  

PR fortran/93499
* gfortran.dg/pr93499.f90: New test.

diff --git a/gcc/fortran/arith.c b/gcc/fortran/arith.c
index 422ef40c431..1cd0867a941 100644
--- a/gcc/fortran/arith.c
+++ b/gcc/fortran/arith.c
@@ -1746,6 +1746,9 @@ eval_intrinsic_f3 (gfc_intrinsic_op op,
   gfc_expr *result;
   eval_f f;

+  if (!op1 && !op2)
+return NULL;
+
   result = reduce_binary0 (op1, op2);
   if (result != NULL)
 return eval_type_intrinsic0(op, result);
@@ -1803,6 +1806,37 @@ gfc_multiply (gfc_expr *op1, gfc_expr *op2)
 gfc_expr *
 gfc_divide (gfc_expr *op1, gfc_expr *op2)
 {
+  if (op2 && op2->expr_type == EXPR_CONSTANT)
+{
+  arith rc = ARITH_OK;
+  switch (op2->ts.type)
+	{
+	case BT_INTEGER:
+	  /* non-integer divided by integer 0 is handled elsewhere.  */
+	  if (mpz_sgn (op2->value.integer) == 0
+	  && op1->ts.type == BT_INTEGER)
+	rc = ARITH_DIV0;
+	  break;
+	case BT_REAL:
+	  if (mpfr_sgn (op2->value.real) == 0
+	  && flag_range_check == 1)
+	rc = ARITH_DIV0;
+	  break;
+	case BT_COMPLEX:
+	  if (mpc_cmp_si_si (op2->value.complex, 0, 0) == 0
+	  && flag_range_check == 1)
+	rc = ARITH_DIV0;
+	  break;
+	default:
+	  gfc_internal_error ("gfc_divide(): Bad basic type");
+	}
+  if (rc == ARITH_DIV0)
+	{
+	  gfc_seen_div0 = true;
+	  gfc_error ("Division by zero at %L", >where);
+	  return NULL;
+	}
+}
   return eval_intrinsic_f3 (INTRINSIC_DIVIDE, gfc_arith_divide, op1, op2);
 }

diff --git a/gcc/testsuite/gfortran.dg/pr93499.f90 b/gcc/testsuite/gfortran.dg/pr93499.f90
new file mode 100644
index 000..7a414bb6016
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr93499.f90
@@ -0,0 +1,10 @@
+! { dg-do compile }
+! PR 93499 - this used to ICE. Original test case by Gerhard Steinmetz.
+
+program p
+  integer :: a((0.)/0)  ! { dg-error "Division by zero" }
+  type t(n)
+ integer, len :: n
+  end type t
+  type(t((0)/0))  :: x  ! { dg-error "Division by zero" }
+end


Fix ICE with cast of division by zero (PR c/93348)

2020-01-21 Thread Joseph Myers
Bug 93348 reports an ICE on certain cases of casts of expressions that
may appear only in unevaluated parts of integer constant expressions,
arising from the generation of nested C_MAYBE_CONST_EXPRs.  This patch
fixes it by adding a call to remove_c_maybe_const_expr in the
integer-operands case, as is done in other similar cases.

Bootstrapped with no regressions for x86_64-pc-linux-gnu.  Applied to 
mainline.  Will also backport to GCC 9 and 8 branches.

gcc/c:
2020-01-22  Joseph Myers  

PR c/93348
* c-typeck.c (build_c_cast): Call remove_c_maybe_const_expr on
argument with integer operands.

gcc/testsuite:
2020-01-22  Joseph Myers  

PR c/93348
* gcc.c-torture/compile/pr93348-1.c: New test.

diff --git a/gcc/c/c-typeck.c b/gcc/c/c-typeck.c
index 9866c83faf2..8df0849bd8b 100644
--- a/gcc/c/c-typeck.c
+++ b/gcc/c/c-typeck.c
@@ -5715,6 +5715,8 @@ build_c_cast (location_t loc, tree type, tree expr)
 expr = TREE_OPERAND (expr, 0);
 
   value = expr;
+  if (int_operands)
+value = remove_c_maybe_const_expr (value);
 
   if (type == error_mark_node || expr == error_mark_node)
 return error_mark_node;
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr93348-1.c 
b/gcc/testsuite/gcc.c-torture/compile/pr93348-1.c
new file mode 100644
index 000..d2edec565ee
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr93348-1.c
@@ -0,0 +1,5 @@
+int
+ya (void)
+{
+  return (long int) (1 / 0);
+}

-- 
Joseph S. Myers
jos...@codesourcery.com


Re: [patch, fortran] Updated fix PR 92961, ICE on division by zero error in array bounds

2019-12-29 Thread Jerry

This one looks OK Thomas

Cheers,

Jerry

On 12/22/19 7:28 AM, Thomas Koenig wrote:

Hello world,

here is an update for the fix for PR 92961, which also takes care
of the second test case in the PR (included in the first one).

The patch itself should be clear enough - make sure that there
is a MATCH_ERROR on matching an array spec which contains 0/(0).
Rather than pass around information several calls deep, I chose
to use a global variable.

Regression-tested. OK for trunk?

(Only a few bugs to fix to be at least below 900 bugs at the end
of the year, by the way - we are at 389 submitted bugs vs. 461 closed,
which is not bad).

Regards

 Thomas

2019-12-22  Thomas Koenig  

 PR fortran/92961
 * gfortran.h (gfc_seen_div0): Add declaration.
 * arith.h (gfc_seen_div0): Add definition.
 (eval_intrinsic): For integer division by zero, set gfc_seen_div0.
 * decl.c (variable_decl):  If resolution resp. simplification
 fails for array spec and a division of zero error has been
 seen, return MATCH_ERROR.

2019-12-22  Thomas Koenig  

 PR fortran/92961
 * gfortran.dg/arith_divide_2.f90: New test.




*ping* [patch, fortran] Updated fix PR 92961, ICE on division by zero error in array bounds

2019-12-29 Thread Thomas Koenig

Am 22.12.19 um 16:28 schrieb Thomas Koenig:


here is an update for the fix for PR 92961, which also takes care
of the second test case in the PR (included in the first one).

The patch itself should be clear enough - make sure that there
is a MATCH_ERROR on matching an array spec which contains 0/(0).
Rather than pass around information several calls deep, I chose
to use a global variable.

Regression-tested. OK for trunk?


Ping?

I'd like to get the bug count at least go to 902 in the old year
(if 900 cannot be achieved :-)

Regards

Thomas


[patch, fortran] Updated fix PR 92961, ICE on division by zero error in array bounds

2019-12-22 Thread Thomas Koenig

Hello world,

here is an update for the fix for PR 92961, which also takes care
of the second test case in the PR (included in the first one).

The patch itself should be clear enough - make sure that there
is a MATCH_ERROR on matching an array spec which contains 0/(0).
Rather than pass around information several calls deep, I chose
to use a global variable.

Regression-tested. OK for trunk?

(Only a few bugs to fix to be at least below 900 bugs at the end
of the year, by the way - we are at 389 submitted bugs vs. 461 closed,
which is not bad).

Regards

Thomas

2019-12-22  Thomas Koenig  

PR fortran/92961
* gfortran.h (gfc_seen_div0): Add declaration.
* arith.h (gfc_seen_div0): Add definition.
(eval_intrinsic): For integer division by zero, set gfc_seen_div0.
* decl.c (variable_decl):  If resolution resp. simplification
fails for array spec and a division of zero error has been
seen, return MATCH_ERROR.

2019-12-22  Thomas Koenig  

PR fortran/92961
* gfortran.dg/arith_divide_2.f90: New test.
Index: gfortran.h
===
--- gfortran.h	(Revision 279639)
+++ gfortran.h	(Arbeitskopie)
@@ -2995,6 +2995,8 @@ void gfc_arith_done_1 (void);
 arith gfc_check_integer_range (mpz_t p, int kind);
 bool gfc_check_character_range (gfc_char_t, int);
 
+extern bool gfc_seen_div0;
+
 /* trans-types.c */
 bool gfc_check_any_c_kind (gfc_typespec *);
 int gfc_validate_kind (bt, int, bool);
Index: arith.c
===
--- arith.c	(Revision 279639)
+++ arith.c	(Arbeitskopie)
@@ -32,6 +32,8 @@ along with GCC; see the file COPYING3.  If not see
 #include "target-memory.h"
 #include "constructor.h"
 
+bool gfc_seen_div0;
+
 /* MPFR does not have a direct replacement for mpz_set_f() from GMP.
It's easily implemented with a few calls though.  */
 
@@ -1620,6 +1622,10 @@ eval_intrinsic (gfc_intrinsic_op op,
   gfc_error (gfc_arith_error (rc), >where);
   if (rc == ARITH_OVERFLOW)
 	goto done;
+
+  if (rc == ARITH_DIV0 && op2->ts.type == BT_INTEGER)
+	gfc_seen_div0 = true;
+
   return NULL;
 }
 
Index: decl.c
===
--- decl.c	(Revision 279639)
+++ decl.c	(Arbeitskopie)
@@ -2551,7 +2551,12 @@ variable_decl (int elem)
 	  for (int i = 0; i < as->rank; i++)
 	{
 	  e = gfc_copy_expr (as->lower[i]);
-	  gfc_resolve_expr (e);
+	  if (!gfc_resolve_expr (e) && gfc_seen_div0)
+		{
+		  m = MATCH_ERROR;
+		  goto cleanup;
+		}
+
 	  gfc_simplify_expr (e, 0);
 	  if (e && (e->expr_type != EXPR_CONSTANT))
 		{
@@ -2561,7 +2566,12 @@ variable_decl (int elem)
 	  gfc_free_expr (e);
 
 	  e = gfc_copy_expr (as->upper[i]);
-	  gfc_resolve_expr (e);
+	  if (!gfc_resolve_expr (e)  && gfc_seen_div0)
+		{
+		  m = MATCH_ERROR;
+		  goto cleanup;
+		}
+
 	  gfc_simplify_expr (e, 0);
 	  if (e && (e->expr_type != EXPR_CONSTANT))
 		{
@@ -2587,7 +2597,12 @@ variable_decl (int elem)
 	  if (e->expr_type != EXPR_CONSTANT)
 		{
 		  n = gfc_copy_expr (e);
-		  gfc_simplify_expr (n, 1);
+		  if (!gfc_simplify_expr (n, 1)  && gfc_seen_div0) 
+		{
+		  m = MATCH_ERROR;
+		  goto cleanup;
+		}
+
 		  if (n->expr_type == EXPR_CONSTANT)
 		gfc_replace_expr (e, n);
 		  else
@@ -2597,7 +2612,12 @@ variable_decl (int elem)
 	  if (e->expr_type != EXPR_CONSTANT)
 		{
 		  n = gfc_copy_expr (e);
-		  gfc_simplify_expr (n, 1);
+		  if (!gfc_simplify_expr (n, 1)  && gfc_seen_div0) 
+		{
+		  m = MATCH_ERROR;
+		  goto cleanup;
+		}
+		  
 		  if (n->expr_type == EXPR_CONSTANT)
 		gfc_replace_expr (e, n);
 		  else
@@ -2934,6 +2954,7 @@ variable_decl (int elem)
 
 cleanup:
   /* Free stuff up and return.  */
+  gfc_seen_div0 = false;
   gfc_free_expr (initializer);
   gfc_free_array_spec (as);
 
! { dg-do compile }
! This used to ICE. Original test case by Gerhard Steinmetz.
program p
   integer :: a((0)/0)! { dg-error "Division by zero" }
   integer :: b(0/(0))! { dg-error "Division by zero" }
   integer :: c((0)/(0))  ! { dg-error "Division by zero" }
   integer :: d(0/0)  ! { dg-error "Division by zero" }
   integer :: x = ubound(a,1) ! { dg-error "must be an array" }
end


Re: [pach, fortran] Fix PR 92961, ICE on division by zero error in array bounds

2019-12-20 Thread Thomas Koenig




the attached patch fixes an ICE in an array declaration where the
specified size came from 0/0. This is an 8/9/10 regression.


Actually, it does not fix all testcases in the PR, so some more
tweaking is still needed.

Regards

Thomas


[pach, fortran] Fix PR 92961, ICE on division by zero error in array bounds

2019-12-20 Thread Thomas Koenig

Hello world,

the attached patch fixes an ICE in an array declaration where the
specified size came from 0/0. This is an 8/9/10 regression.

The actual ICE fix was the NULL check in simplify_intrinsic_op, which in
turn led to strange error messages, which are then corrected by
the rest of the patch. Rather than try to transport state across I
do not know how many levels of calls, I chose a global variable.

Regression-tested. OK for all affected branches?

Regards

Thomas

2019-12-20  Thomas Koenig  

PR fortran/92961
* gfortran.h (gfc_seen_div0): Add declaration.
* arith.h (gfc_seen_div0): Add definition.
(eval_intrinsic): For integer division by zero, issue
gfc_error_now and set gfc_seen_div0.
* decl.c (variable_decl): If a division by zero error has been
seen previously, do not issue an addtional error.
* expr.c (simplify_intrinsic_op): Return NULL if op1 is NULL.

2019-12-20  Thomas Koenig  

PR fortran/92961
* gfortran.dg/arith_divide_2.f90: New test.
Index: gfortran.h
===
--- gfortran.h	(Revision 279639)
+++ gfortran.h	(Arbeitskopie)
@@ -2995,6 +2995,8 @@ void gfc_arith_done_1 (void);
 arith gfc_check_integer_range (mpz_t p, int kind);
 bool gfc_check_character_range (gfc_char_t, int);
 
+extern bool gfc_seen_div0;
+
 /* trans-types.c */
 bool gfc_check_any_c_kind (gfc_typespec *);
 int gfc_validate_kind (bt, int, bool);
Index: arith.c
===
--- arith.c	(Revision 279639)
+++ arith.c	(Arbeitskopie)
@@ -32,6 +32,8 @@ along with GCC; see the file COPYING3.  If not see
 #include "target-memory.h"
 #include "constructor.h"
 
+bool gfc_seen_div0;
+
 /* MPFR does not have a direct replacement for mpz_set_f() from GMP.
It's easily implemented with a few calls though.  */
 
@@ -1617,7 +1619,15 @@ eval_intrinsic (gfc_intrinsic_op op,
 
   if (rc != ARITH_OK)
 {
-  gfc_error (gfc_arith_error (rc), >where);
+  if (rc == ARITH_DIV0 && op2->ts.type == BT_INTEGER)
+	{
+	  gfc_error_now (gfc_arith_error (rc), >where);
+	  gfc_seen_div0 = true;
+	  return NULL;
+	}
+  else
+	gfc_error (gfc_arith_error (rc), >where);
+
   if (rc == ARITH_OVERFLOW)
 	goto done;
   return NULL;
Index: decl.c
===
--- decl.c	(Revision 279639)
+++ decl.c	(Arbeitskopie)
@@ -2535,6 +2535,10 @@ variable_decl (int elem)
 	  goto cleanup;
 	}
 
+  /* eval_intrinsic may signal a division by zero.  */
+
+  gfc_seen_div0 = false;
+
   /* F2018:C830 (R816) An explicit-shape-spec whose bounds are not
 	 constant expressions shall appear only in a subprogram, derived
 	 type definition, BLOCK construct, or interface body.  */
@@ -2573,7 +2577,15 @@ variable_decl (int elem)
 
 	  if (not_constant)
 	{
-	  gfc_error ("Explicit shaped array with nonconstant bounds at %C");
+	  /* If there is a division by zero error, it will have been reported
+		 previously using gfc_error_now in eval_intrinsic.  */
+
+	  if (!gfc_seen_div0)
+		gfc_error ("Explicit shaped array with nonconstant bounds at "
+			   "%C");
+
+	  gfc_seen_div0 = false;
+
 	  m = MATCH_ERROR;
 	  goto cleanup;
 	}
Index: expr.c
===
--- expr.c	(Revision 279639)
+++ expr.c	(Arbeitskopie)
@@ -1153,6 +1153,9 @@ simplify_intrinsic_op (gfc_expr *p, int type)
   op2 = p->value.op.op2;
   op  = p->value.op.op;
 
+  if (op1 == NULL)
+return false;
+
   if (!gfc_simplify_expr (op1, type))
 return false;
   if (!gfc_simplify_expr (op2, type))
! { dg-do compile }
! This used to ICE. Original test case by Gerhard Steinmetz.
program p
   integer :: a((0)/0)    ! { dg-error "Division by zero" }
   integer :: b(0/(0))! { dg-error "Division by zero" }
   integer :: c((0)/(0))  ! { dg-error "Division by zero" }
   integer :: d(0/0)  ! { dg-error "Division by zero" }
end


[Bug other/88499] Check for less than zero removed before floating point division causes division by zero (fast-math mode)

2018-12-14 Thread pinskia at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88499

Andrew Pinski  changed:

   What|Removed |Added

 Status|UNCONFIRMED |RESOLVED
 Resolution|--- |INVALID

--- Comment #4 from Andrew Pinski  ---
You need to turn back on trapping math, -ftrapping-math for this to work
correctly.  -ftrapping-math is turned off with -ffast-math.

[Bug other/88499] Check for less than zero removed before floating point division causes division by zero (fast-math mode)

2018-12-14 Thread fuscated at gmail dot com
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88499

--- Comment #3 from Teodor Petrov  ---
@Marc Glisse: Would it be possible to give an explanation why this is not a
good idea? Link to some kind of a documentation which explains that this
behaviour is expected?

[Bug other/88499] Check for less than zero removed before floating point division causes division by zero (fast-math mode)

2018-12-14 Thread glisse at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88499

--- Comment #2 from Marc Glisse  ---
I don't think using fenv.h with -ffast-math makes much sense.

[Bug other/88499] Check for less than zero removed before floating point division causes division by zero (fast-math mode)

2018-12-14 Thread fuscated at gmail dot com
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88499

--- Comment #1 from Teodor Petrov  ---
Here are the commands used to reproduce the bug:
$ g++ -g -fPIC -Ofast  -msse4.2 -std=c++11 -ffunction-sections -fdata-sections
-ffast-math -fvisibility=hidden -fexceptions -Wno-c++11-extensions
gcc_division.cpp 
$ ./a.out 
p=0.000; i=0
Floating point exception (core dumped)

If I move the if-else which sets the y0 outside of the loop just after the
printf call it works as expected and there is no SIGFPE.

[Bug other/88499] New: Check for less than zero removed before floating point division causes division by zero (fast-math mode)

2018-12-14 Thread fuscated at gmail dot com
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=88499

Bug ID: 88499
   Summary: Check for less than zero removed before floating point
division causes division by zero (fast-math mode)
   Product: gcc
   Version: 8.2.0
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: other
  Assignee: unassigned at gcc dot gnu.org
  Reporter: fuscated at gmail dot com
  Target Milestone: ---

Created attachment 45237
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=45237=edit
minimal source to reproduce the problem

See the attached file.
I've tried 4.8.2 and 8.2.0. on x86-64 Linux. Both failed with SIGFPE.

[Bug c++/80744] Detect Possible Division By Zero and give a warning in C/C++ [-Wmaybe-div-by-zero]

2018-11-01 Thread egallager at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80744

Eric Gallager  changed:

   What|Removed |Added

 Blocks||87403
Summary|Detect Divide By Zero and   |Detect Possible Division By
   |give a warning in  C/C++|Zero and give a warning in
   ||C/C++ [-Wmaybe-div-by-zero]

--- Comment #6 from Eric Gallager  ---
(In reply to Martin Sebor from comment #3)
> I agree that diagnosing (A) or (C) under -Wdiv-by-zero would not be
> appropriate because the option controls compile-time division by zero and
> there is none here.
> 
> Extending -Wdiv-by-zero to diagnose possible division by zero would
> undoubtedly make the option exceedingly noisy.  Introducing a new option
> such as -Wmaybe-div-by-zero analogous to -Wmaybe-uninitialized would be fine
> but the option wouldn't diagnose ether (A) or (C) because there is no
> evidence of overflow.  -Wmaybe-uninitialized triggers under very restrictive
> conditions, when there is some evidence that an uninitialized variable is
> used.  To avoid excessive noise from -Wmaybe-div-by-zero some similar
> approach would need to used.  Such as:
> 
>   int f (int i)
>   {
> int j;
> 
> if (i == 0) // because of this test
>   j = 7;
> else
>   j = 13;
> 
> return j / i;   // i may be assumed to be zero here
>   }

Changing title then to specify -Wmaybe-div-by-zero would be a different
warning, which lets it block the new-warning meta-bug


Referenced Bugs:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87403
[Bug 87403] [Meta-bug] Issues that suggest a new warning

[Bug libstdc++/67011] division by zero in std::exponential_distribution

2018-05-14 Thread redi at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67011

Jonathan Wakely  changed:

   What|Removed |Added

 Status|UNCONFIRMED |NEW
   Last reconfirmed||2018-05-14
 Ever confirmed|0   |1

--- Comment #4 from Jonathan Wakely  ---
(In reply to Matthias Kretz from comment #3)
> The problem is that (result_type(1) - __aurng()) must never be zero (because
> std::log might raise FE_DIVBYZERO for std::log(0)). If __aurng() is a
> distribution guaranteed to exclude result_type(1) then this works fine.
> AFAIK std::generate_canoncial sometimes generates a 1 (cf.
> https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176).

PR 63176 is fixed now.

> Also, I'm wondering whether the 1 - rng wouldn't reduce the randomness.
> Consider:
> std::log(numeric_limits::min()) -> -87.3365478515625
> std::log(1.f - nextafter(1.f, 0.f))-> -16.635532379150390625
> IIUC, the effect of log(1 - rng) is that the distance between random values
> from std::exponential_distribution is considerable larger than for log(rng).

Hmm, let's confirm the bug for that, instead of the division-by-zero that
should be fixed.

[Bug c/82349] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread sch...@linux-m68k.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82349

--- Comment #5 from Andreas Schwab  ---
Undefined means anything can happen, not even consistently.

[Bug c/82349] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread marc.pres at gmx dot net
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82349

--- Comment #4 from Marcello Presulli  ---
Thats clear, but why are the 2 terms different each.
If so, they should output the same, because what would be the difference
between 1.0/denom and 1.0/0 in case of fast-math ?

[Bug c/82351] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread sch...@linux-m68k.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82351

Andreas Schwab  changed:

   What|Removed |Added

 Status|UNCONFIRMED |RESOLVED
 Resolution|--- |DUPLICATE

--- Comment #1 from Andreas Schwab  ---
dup

*** This bug has been marked as a duplicate of bug 82349 ***

[Bug c/82349] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread sch...@linux-m68k.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82349

--- Comment #3 from Andreas Schwab  ---
*** Bug 82351 has been marked as a duplicate of this bug. ***

[Bug c/82350] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread pinskia at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82350

Andrew Pinski  changed:

   What|Removed |Added

 Status|UNCONFIRMED |RESOLVED
 Resolution|--- |DUPLICATE

--- Comment #1 from Andrew Pinski  ---
.

*** This bug has been marked as a duplicate of bug 82349 ***

[Bug c/82349] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread pinskia at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82349

--- Comment #2 from Andrew Pinski  ---
*** Bug 82350 has been marked as a duplicate of this bug. ***

[Bug c/82349] float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread pinskia at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82349

Andrew Pinski  changed:

   What|Removed |Added

 Status|UNCONFIRMED |RESOLVED
 Resolution|--- |INVALID

--- Comment #1 from Andrew Pinski  ---
Two issues here that makes this undefined.
1) out of range conversion is undefined.  That is inf converted to an int does
not have a specified value.
2) inf is not a valid value for float when -ffast-math is specified  (fast math
implies finite math only).

[Bug c/82351] New: float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread marc.pres at gmx dot net
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82351

Bug ID: 82351
   Summary: float INFINITY issue with division by zero in
regression with compiler option '-ffast-math'
   Product: gcc
   Version: unknown
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: c
  Assignee: unassigned at gcc dot gnu.org
  Reporter: marc.pres at gmx dot net
  Target Milestone: ---

Given this code snippet:

#include 
#include 

int main(void) {

int denom=0;
printf("%d %d %d\n", (int)(1.0/denom), (int)(1.0/0), (int)INFINITY);

return 0;
}

bash> gcc infinity.c

bash> -2147483648 -2147483648 2147483647

bash> gcc infinity.c -ffast-math

bash> -2147483648 2147483647 2147483647

What is unclear regarding the IEEE standard and the supplement documentation of
option "-ffast-math", is why is 1. first and 2. term are different in sign AND
why are the 2 outputs generally different.

In my opionion all the terms above should be positive like 2147483647.


Dr. Marcello Presulli

[Bug c/82350] New: float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread marc.pres at gmx dot net
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82350

Bug ID: 82350
   Summary: float INFINITY issue with division by zero in
regression with compiler option '-ffast-math'
   Product: gcc
   Version: unknown
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: c
  Assignee: unassigned at gcc dot gnu.org
  Reporter: marc.pres at gmx dot net
  Target Milestone: ---

Given this code snippet:

#include 
#include 

int main(void) {

int denom=0;
printf("%d %d %d\n", (int)(1.0/denom), (int)(1.0/0), (int)INFINITY);

return 0;
}

bash> gcc infinity.c

bash> -2147483648 -2147483648 2147483647

bash> gcc infinity.c -ffast-math

bash> -2147483648 2147483647 2147483647

What is unclear regarding the IEEE standard and the supplement documentation of
option "-ffast-math", is why is 1. first and 2. term are different in sign AND
why are the 2 outputs generally different.

In my opionion all the terms above should be positive like 2147483647.


Dr. Marcello Presulli

[Bug c/82349] New: float INFINITY issue with division by zero in regression with compiler option '-ffast-math'

2017-09-28 Thread marc.pres at gmx dot net
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82349

Bug ID: 82349
   Summary: float INFINITY issue with division by zero in
regression with compiler option '-ffast-math'
   Product: gcc
   Version: unknown
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: c
  Assignee: unassigned at gcc dot gnu.org
  Reporter: marc.pres at gmx dot net
  Target Milestone: ---

Given this code snippet:

#include 
#include 

int main(void) {

int denom=0;
printf("%d %d %d\n", (int)(1.0/denom), (int)(1.0/0), (int)INFINITY);

return 0;
}

bash> gcc infinity.c

bash> -2147483648 -2147483648 2147483647

bash> gcc infinity.c -ffast-math

bash> -2147483648 2147483647 2147483647

What is unclear regarding the IEEE standard and the supplement documentation of
option "-ffast-math", is why is 1. first and 2. term in are different in sign
AND why are the 2 outputs generally different.

In my opionion all the terms above should be positive like 2147483647.


Dr. Marcello Presulli

[Ada] Issue check instead of error in static division by zero

2016-04-18 Thread Arnaud Charlet
In some cases of generic instantiations, or code configuration, some code
may be deactivated and contain static divisions by zero. Instead of
issuing an error in SPARK code, generate a suitable check.

Tested on x86_64-pc-linux-gnu, committed on trunk

2016-04-18  Yannick Moy  <m...@adacore.com>

* sem_eval.adb (Eval_Arithmetic_Op): Do not issue error on static
    division by zero, instead possibly issue a warning.
* sem_res.adb (Resolve_Arithmetic_Op): Do not issue error on
static division by zero, instead add check flag on original
expression.
* sem_util.adb, sem_util.ads (Compile_Time_Constraint_Error):
Only issue error when both SPARK_Mode is On and Warn is False.

Index: sem_util.adb
===
--- sem_util.adb(revision 235122)
+++ sem_util.adb(working copy)
@@ -4574,9 +4574,16 @@
 
begin
   --  If this is a warning, convert it into an error if we are in code
-  --  subject to SPARK_Mode being set ON.
+  --  subject to SPARK_Mode being set On, unless Warn is True to force a
+  --  warning. The rationale is that a compile-time constraint error should
+  --  lead to an error instead of a warning when SPARK_Mode is On, but in
+  --  a few cases we prefer to issue a warning and generate both a suitable
+  --  run-time error in GNAT and a suitable check message in GNATprove.
+  --  Those cases are those that likely correspond to deactivated SPARK
+  --  code, so that this kind of code can be compiled and analyzed instead
+  --  of being rejected.
 
-  Error_Msg_Warn := SPARK_Mode /= On;
+  Error_Msg_Warn := Warn or SPARK_Mode /= On;
 
   --  A static constraint error in an instance body is not a fatal error.
   --  we choose to inhibit the message altogether, because there is no
@@ -4648,8 +4655,6 @@
  --  evaluated.
 
  if not Is_Statically_Unevaluated (N) then
-Error_Msg_Warn := SPARK_Mode /= On;
-
 if Present (Ent) then
Error_Msg_NEL (Msgc (1 .. Msgl), N, Ent, Eloc);
 else
Index: sem_util.ads
===
--- sem_util.ads(revision 235122)
+++ sem_util.ads(working copy)
@@ -135,7 +135,9 @@
--  is present, this is used instead. Warn is normally False. If it is
--  True then the message is treated as a warning even though it does
--  not end with a ? (this is used when the caller wants to parameterize
-   --  whether an error or warning is given).
+   --  whether an error or warning is given), or when the message should be
+   --  treated as a warning even when SPARK_Mode is On (which otherwise would
+   --  force an error).
 
function Async_Readers_Enabled (Id : Entity_Id) return Boolean;
--  Given the entity of an abstract state or a variable, determine whether
Index: sem_res.adb
===
--- sem_res.adb (revision 235116)
+++ sem_res.adb (working copy)
@@ -5440,7 +5440,9 @@
  and then Expr_Value_R (Rop) = Ureal_0))
 then
--  Specialize the warning message according to the operation.
-   --  The following warnings are for the case
+   --  When SPARK_Mode is On, force a warning instead of an error
+   --  in that case, as this likely corresponds to deactivated
+   --  code. The following warnings are for the case
 
case Nkind (N) is
   when N_Op_Divide =>
@@ -5459,23 +5461,26 @@
   ("float division by zero, may generate "
& "'+'/'- infinity??", Right_Opnd (N));
 
---  For all other cases, we get a Constraint_Error
+ --  For all other cases, we get a Constraint_Error
 
  else
 Apply_Compile_Time_Constraint_Error
   (N, "division by zero??", CE_Divide_By_Zero,
-   Loc => Sloc (Right_Opnd (N)));
+   Loc  => Sloc (Right_Opnd (N)),
+   Warn => SPARK_Mode = On);
  end if;
 
   when N_Op_Rem =>
  Apply_Compile_Time_Constraint_Error
(N, "rem with zero divisor??", CE_Divide_By_Zero,
-Loc => Sloc (Right_Opnd (N)));
+Loc  => Sloc (Right_Opnd (N)),
+Warn => SPARK_Mode = On);
 
   when N_Op_Mod =>
  Apply_Compile_Time_Constraint_Error
(N, "mod with zero divisor??", CE_Divide_By_Zero,
-Loc => Sloc (Right_Opnd (N)));
+

[PATCH 2/2] [graphite] check for ISL generated code that leads to division by zero

2015-11-30 Thread Sebastian Pop
we used to generate modulo and division by zero because ISL uses big numbers
which translate to zero in modulo arithmetic.  The patch also improves error 
handling
and bails out early in case of wrong code gen.
---
 gcc/graphite-isl-ast-to-gimple.c | 85 +++-
 1 file changed, 83 insertions(+), 2 deletions(-)

diff --git a/gcc/graphite-isl-ast-to-gimple.c b/gcc/graphite-isl-ast-to-gimple.c
index 16cb5fa..bfce316 100644
--- a/gcc/graphite-isl-ast-to-gimple.c
+++ b/gcc/graphite-isl-ast-to-gimple.c
@@ -502,7 +502,7 @@ private:
 tree
 translate_isl_ast_to_gimple::
 gcc_expression_from_isl_ast_expr_id (tree type,
-__isl_keep isl_ast_expr *expr_id,
+__isl_take isl_ast_expr *expr_id,
 ivs_params )
 {
   gcc_assert (isl_ast_expr_get_type (expr_id) == isl_ast_expr_id);
@@ -550,8 +550,13 @@ binary_op_to_tree (tree type, __isl_take isl_ast_expr 
*expr, ivs_params )
   tree tree_lhs_expr = gcc_expression_from_isl_expression (type, arg_expr, ip);
   arg_expr = isl_ast_expr_get_op_arg (expr, 1);
   tree tree_rhs_expr = gcc_expression_from_isl_expression (type, arg_expr, ip);
+
   enum isl_ast_op_type expr_type = isl_ast_expr_get_op_type (expr);
   isl_ast_expr_free (expr);
+
+  if (codegen_error)
+return NULL_TREE;
+
   switch (expr_type)
 {
 case isl_ast_op_add:
@@ -564,15 +569,43 @@ binary_op_to_tree (tree type, __isl_take isl_ast_expr 
*expr, ivs_params )
   return fold_build2 (MULT_EXPR, type, tree_lhs_expr, tree_rhs_expr);
 
 case isl_ast_op_div:
+  /* As ISL operates on arbitrary precision numbers, we may end up with
+division by 2^64 that is folded to 0.  */
+  if (integer_zerop (tree_rhs_expr))
+   {
+ codegen_error = true;
+ return NULL_TREE;
+   }
   return fold_build2 (EXACT_DIV_EXPR, type, tree_lhs_expr, tree_rhs_expr);
 
 case isl_ast_op_pdiv_q:
+  /* As ISL operates on arbitrary precision numbers, we may end up with
+division by 2^64 that is folded to 0.  */
+  if (integer_zerop (tree_rhs_expr))
+   {
+ codegen_error = true;
+ return NULL_TREE;
+   }
   return fold_build2 (TRUNC_DIV_EXPR, type, tree_lhs_expr, tree_rhs_expr);
 
 case isl_ast_op_pdiv_r:
+  /* As ISL operates on arbitrary precision numbers, we may end up with
+division by 2^64 that is folded to 0.  */
+  if (integer_zerop (tree_rhs_expr))
+   {
+ codegen_error = true;
+ return NULL_TREE;
+   }
   return fold_build2 (TRUNC_MOD_EXPR, type, tree_lhs_expr, tree_rhs_expr);
 
 case isl_ast_op_fdiv_q:
+  /* As ISL operates on arbitrary precision numbers, we may end up with
+division by 2^64 that is folded to 0.  */
+  if (integer_zerop (tree_rhs_expr))
+   {
+ codegen_error = true;
+ return NULL_TREE;
+   }
   return fold_build2 (FLOOR_DIV_EXPR, type, tree_lhs_expr, tree_rhs_expr);
 
 case isl_ast_op_and:
@@ -620,6 +653,9 @@ ternary_op_to_tree (tree type, __isl_take isl_ast_expr 
*expr, ivs_params )
   tree tree_third_expr
 = gcc_expression_from_isl_expression (type, arg_expr, ip);
   isl_ast_expr_free (expr);
+
+  if (codegen_error)
+return NULL_TREE;
   return fold_build3 (COND_EXPR, type, tree_first_expr,
  tree_second_expr, tree_third_expr);
 }
@@ -635,7 +671,7 @@ unary_op_to_tree (tree type, __isl_take isl_ast_expr *expr, 
ivs_params )
   isl_ast_expr *arg_expr = isl_ast_expr_get_op_arg (expr, 0);
   tree tree_expr = gcc_expression_from_isl_expression (type, arg_expr, ip);
   isl_ast_expr_free (expr);
-  return fold_build1 (NEGATE_EXPR, type, tree_expr);
+  return codegen_error ? NULL_TREE : fold_build1 (NEGATE_EXPR, type, 
tree_expr);
 }
 
 /* Converts an isl_ast_expr_op expression E with unknown number of arguments
@@ -661,11 +697,25 @@ nary_op_to_tree (tree type, __isl_take isl_ast_expr 
*expr, ivs_params )
 }
   isl_ast_expr *arg_expr = isl_ast_expr_get_op_arg (expr, 0);
   tree res = gcc_expression_from_isl_expression (type, arg_expr, ip);
+
+  if (codegen_error)
+{
+  isl_ast_expr_free (expr);
+  return NULL_TREE;
+}
+
   int i;
   for (i = 1; i < isl_ast_expr_get_op_n_arg (expr); i++)
 {
   arg_expr = isl_ast_expr_get_op_arg (expr, i);
   tree t = gcc_expression_from_isl_expression (type, arg_expr, ip);
+
+  if (codegen_error)
+   {
+ isl_ast_expr_free (expr);
+ return NULL_TREE;
+   }
+
   res = fold_build2 (op_code, type, res, t);
 }
   isl_ast_expr_free (expr);
@@ -680,6 +730,12 @@ translate_isl_ast_to_gimple::
 gcc_expression_from_isl_expr_op (tree type, __isl_take isl_ast_expr *expr,
 ivs_params )
 {
+  if (codegen_error)
+{
+  isl_ast_expr_free (expr);
+  return NULL_TREE;
+}
+
   gcc_assert (isl_ast_expr_get_type (expr) == isl_ast_expr

[Bug libstdc++/67011] division by zero in std::exponential_distribution

2015-07-27 Thread kretz at kde dot org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67011

Matthias Kretz kretz at kde dot org changed:

   What|Removed |Added

 CC||kretz at kde dot org

--- Comment #3 from Matthias Kretz kretz at kde dot org ---
The problem is that (result_type(1) - __aurng()) must never be zero (because
std::log might raise FE_DIVBYZERO for std::log(0)). If __aurng() is a
distribution guaranteed to exclude result_type(1) then this works fine. AFAIK
std::generate_canoncialfloat sometimes generates a 1 (cf.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63176).

Also, I'm wondering whether the 1 - rng wouldn't reduce the randomness.
Consider:
std::log(numeric_limitsfloat::min()) - -87.3365478515625
std::log(1.f - nextafter(1.f, 0.f))- -16.635532379150390625
IIUC, the effect of log(1 - rng) is that the distance between random values
from std::exponential_distribution is considerable larger than for log(rng).


[Bug libstdc++/67011] division by zero in std::exponential_distribution

2015-07-26 Thread redi at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67011

--- Comment #1 from Jonathan Wakely redi at gcc dot gnu.org ---
One is for std::exponential_distribution and one is for
std::tr1:exponential_distribution. The former is already fixed and the latter
is moribund and we don't really care about it any more.


[Bug libstdc++/67011] division by zero in std::exponential_distribution

2015-07-26 Thread redi at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67011

--- Comment #2 from Jonathan Wakely redi at gcc dot gnu.org ---
Although if you're still seeing a problem with std::exponential_distribution
then I guess it's not the same bug.

(Please ignore tr1/random.h unless you're actually using
std::tr1::exponential_distribution ... and if you are using that, you should
consider not using it :-)


[Bug libstdc++/67011] New: division by zero in std::exponential_distribution

2015-07-25 Thread janus at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67011

Bug ID: 67011
   Summary: division by zero in std::exponential_distribution
   Product: gcc
   Version: 4.8.4
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: libstdc++
  Assignee: unassigned at gcc dot gnu.org
  Reporter: janus at gcc dot gnu.org
  Target Milestone: ---

After seeing a division-by-zero problem in a C++11 code (compiled with GCC
4.8.4), I traced it down and found that it seems to come from a call to
std::exponential_distribution.

Looking into the GCC trunk sources, I found two implementations of
std::exponential_distribution, in these two files:

libstdc++-v3/include/bits/random.h
libstdc++-v3/include/tr1/random.h


In the first one, operator() is implemented like this:

  return -std::log(result_type(1) - __aurng()) / __p.lambda();

In the second one like this:

  return -std::log(__urng()) / _M_lambda;


Looking through bugzilla I found PR 55047, which seems to describe exactly the
problem I observed (resulting from a log(0) call), but the fix has only been
applied to bits/random.h, not to tr1/random.h. I don't actually understand the
relationship between those two files (and which implementation is used under
which circumstances), but I guess the fix from PR 55047 should also be applied
to tr1/random.h?


Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Steve Ellcey
On Thu, 2015-05-14 at 09:42 -0700, Steve Ellcey wrote:
 Marek,
 
 This may be unrelated to your patches for PR 66127 and 66066 but I am
 having a new failure when building the latest glibc with the latest GCC.
 
 I haven't yet tracked down exactly which patch caused the problem.  Included
 is a cutdown test case from libio/memstream.c in glibc that results in a
 strict-aliasing error.  Is this is something you already know about or have
 seen?
 
 In the mean time I will try to figure out exactly which patch caused this 
 error
 to trigger.
 
 Steve Ellcey
 sell...@imgtec.com

Sorry for the noise, it looks like this failure is not related to any
recent changes in GCC.  I still get the error in older GCC's so I think
something must have changed in glibc.  I will start digging there.

Steve Ellcey
sell...@imgtec.com



Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Marek Polacek
On Thu, May 14, 2015 at 10:07:56AM -0700, Steve Ellcey wrote:
 Sorry for the noise, it looks like this failure is not related to any
 recent changes in GCC.  I still get the error in older GCC's so I think
 something must have changed in glibc.  I will start digging there.

Yeah -- strict aliasing should be unrelated to the changes I've recently done
in the C FE.

Marek


Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Steve Ellcey
Marek,

This may be unrelated to your patches for PR 66127 and 66066 but I am
having a new failure when building the latest glibc with the latest GCC.

I haven't yet tracked down exactly which patch caused the problem.  Included
is a cutdown test case from libio/memstream.c in glibc that results in a
strict-aliasing error.  Is this is something you already know about or have
seen?

In the mean time I will try to figure out exactly which patch caused this error
to trigger.

Steve Ellcey
sell...@imgtec.com


typedef unsigned int size_t;
extern void *malloc (size_t __size) __attribute__ ((__nothrow__ )) __attribute__
 ((__malloc__)) ;

struct _IO_FILE_plus { void *vtable; };
void *_IO_mem_jumps;

struct _IO_streambuf { };

typedef struct _IO_strfile_
{
  struct _IO_streambuf _sbf;
} _IO_strfile;

struct _IO_FILE_memstream
{
  _IO_strfile _sf;
};

void open_memstream (int bufloc, int sizeloc)
{
  struct locked_FILE
  {
struct _IO_FILE_memstream fp;
  } *new_f;
  new_f = (struct locked_FILE *) malloc (sizeof (struct locked_FILE));
  ((struct _IO_FILE_plus *) new_f-fp._sf._sbf)-vtable = _IO_mem_jumps;
}


x.c: In function 'open_memstream':
x.c:28:12: error: dereferencing type-punned pointer will break strict-aliasing 
rules [-Werror=strict-aliasing]
   ((struct _IO_FILE_plus *) new_f-fp._sf._sbf)-vtable = _IO_mem_jumps;
^
cc1: all warnings being treated as errors




Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Steve Ellcey
On Thu, 2015-05-14 at 19:22 +0200, Marek Polacek wrote:
 On Thu, May 14, 2015 at 10:07:56AM -0700, Steve Ellcey wrote:
  Sorry for the noise, it looks like this failure is not related to any
  recent changes in GCC.  I still get the error in older GCC's so I think
  something must have changed in glibc.  I will start digging there.
 
 Yeah -- strict aliasing should be unrelated to the changes I've recently done
 in the C FE.
 
   Marek

FYI: I finally found the change that caused this failure, it is a GCC
patch after all.  It starts with Richard's fix to PR middle-end/66110.
I sent some email to glibc but I am not sure (again) if we want to
change GCC or glibc.

https://sourceware.org/ml/libc-alpha/2015-05/msg00258.html

Steve Ellcey
sell...@imgtec.com



[Bug c/66127] Division by zero gets folded away

2015-05-14 Thread mpolacek at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66127

--- Comment #10 from Marek Polacek mpolacek at gcc dot gnu.org ---
Author: mpolacek
Date: Thu May 14 11:42:53 2015
New Revision: 223193

URL: https://gcc.gnu.org/viewcvs?rev=223193root=gccview=rev
Log:
PR c/66066
PR c/66127
* c-common.c (c_fully_fold): Pass false down to c_fully_fold_internal.
(c_fully_fold_internal): Fold C_MAYBE_CONST_EXPRs with
C_MAYBE_CONST_EXPR_INT_OPERANDS set.  Add FOR_INT_CONST argument and
use it.  If FOR_INT_CONST, require that all evaluated operands be
INTEGER_CSTs.

* c-typeck.c (digest_init): Call pedwarn_init with OPT_Wpedantic
rather than with 0.

* gcc.dg/pr14649-1.c: Add -Wpedantic.
* gcc.dg/pr19984.c: Likewise.
* gcc.dg/pr66066-1.c: New test.
* gcc.dg/pr66066-2.c: New test.
* gcc.dg/pr66066-3.c: New test.

Added:
trunk/gcc/testsuite/gcc.dg/pr66066-1.c
trunk/gcc/testsuite/gcc.dg/pr66066-2.c
trunk/gcc/testsuite/gcc.dg/pr66066-3.c
Modified:
trunk/gcc/c-family/ChangeLog
trunk/gcc/c-family/c-common.c
trunk/gcc/c/ChangeLog
trunk/gcc/c/c-typeck.c
trunk/gcc/testsuite/ChangeLog
trunk/gcc/testsuite/gcc.dg/pr14649-1.c
trunk/gcc/testsuite/gcc.dg/pr19984.c


[Bug c/66127] Division by zero gets folded away

2015-05-14 Thread mpolacek at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66127

Marek Polacek mpolacek at gcc dot gnu.org changed:

   What|Removed |Added

 Status|ASSIGNED|RESOLVED
 Resolution|--- |FIXED

--- Comment #11 from Marek Polacek mpolacek at gcc dot gnu.org ---
Ought to be fixed.


Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Richard Biener
On May 14, 2015 12:46:06 AM GMT+02:00, Joseph Myers jos...@codesourcery.com 
wrote:
On Wed, 13 May 2015, Marek Polacek wrote:

  Rather, how about having an extra argument to c_fully_fold_internal
(e.g. 
  for_int_const) indicating that the folding is of an expression with

  integer constant operands (so this argument would be true in the
new case 
  of folding the contents of a C_MAYBE_CONST_EXPR with 
  C_MAYBE_CONST_EXPR_INT_OPERANDS set)?  In that special case, 
  c_fully_fold_internal would only fold the expression itself if all 
  evaluated operands folded to INTEGER_CSTs (so if something that
doesn't 
  get folded, such as division by 0, is encountered, then all
evaluated 
  expressions containing it also don't get folded).
 
 Did you mean something like the following?  It is on top of the
previous
 c_fully_fold_internal patch; if it makes any sense, I'll squash these
 into one.

Yes.  The two patches are OK together, though I think it would be
better 
to add for_int_const checks also in the cases of unary operations, ,
|| 
and ?: (the last three being cases where it's only the evaluated
operands 
that need to fold to INTEGER_CSTs, not any unevaluated operands).  It
may 
well be the case that no folding at present can fold any of those cases
to 
an INTEGER_CST when it shouldn't be one, but I don't think we should
rely 
on that.

 This still doesn't reject enum { A = 0 * (unsigned) (1 / 0) };, but
note
 that we don't reject such an enum at present.

It's rejected with -pedantic-errors, but it should indeed be rejected 
unconditionally like the other cases.

Casts can do some optimization prematurely, but I don't know if that
has 
anything to do with the non-rejection here.

Do the patches allow us to remove the restrictions from the folding patterns?

Richard.




Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Marek Polacek
On Thu, May 14, 2015 at 09:59:49AM +0200, Richard Biener wrote:
 Do the patches allow us to remove the restrictions from the folding patterns?

With the c_fully_fold_internal patches there's no need to tweak any match.pd
patterns.  So PR66127 + PR66066 are to be solved solely in the C FE.  Is that
what you're asking about?

Marek


[Bug c/66127] Division by zero gets folded away

2015-05-14 Thread mpolacek at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66127

Marek Polacek mpolacek at gcc dot gnu.org changed:

   What|Removed |Added

  Component|middle-end  |c

--- Comment #9 from Marek Polacek mpolacek at gcc dot gnu.org ---
This is going to be solved in c_fully_fold_internal so changing the component.


Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Marek Polacek
On Wed, May 13, 2015 at 10:46:06PM +, Joseph Myers wrote:
 Yes.  The two patches are OK together, though I think it would be better 

Thanks.

 to add for_int_const checks also in the cases of unary operations, , || 
 and ?: (the last three being cases where it's only the evaluated operands 
 that need to fold to INTEGER_CSTs, not any unevaluated operands).  It may 
 well be the case that no folding at present can fold any of those cases to 
 an INTEGER_CST when it shouldn't be one, but I don't think we should rely 
 on that.

Yeah, I couldn't find a case where it would trigger, but I added for_int_const
checks for the other cases all the same.

I'm attaching the patch here for archival purposes.

Bootstrapped/regtested on x86_64-linux, applying to trunk.

2015-05-14  Marek Polacek  pola...@redhat.com

PR c/66066
PR c/66127
* c-common.c (c_fully_fold): Pass false down to c_fully_fold_internal.
(c_fully_fold_internal): Fold C_MAYBE_CONST_EXPRs with
C_MAYBE_CONST_EXPR_INT_OPERANDS set.  Add FOR_INT_CONST argument and
use it.  If FOR_INT_CONST, require that all evaluated operands be
INTEGER_CSTs.

* c-typeck.c (digest_init): Call pedwarn_init with OPT_Wpedantic
rather than with 0.

* gcc.dg/pr14649-1.c: Add -Wpedantic.
* gcc.dg/pr19984.c: Likewise.
* gcc.dg/pr66066-1.c: New test.
* gcc.dg/pr66066-2.c: New test.
* gcc.dg/pr66066-3.c: New test.

diff --git gcc/c-family/c-common.c gcc/c-family/c-common.c
index 7e5ac72..31c4c0d 100644
--- gcc/c-family/c-common.c
+++ gcc/c-family/c-common.c
@@ -315,7 +315,7 @@ const struct fname_var_t fname_vars[] =
 /* Global visibility options.  */
 struct visibility_flags visibility_options;
 
-static tree c_fully_fold_internal (tree expr, bool, bool *, bool *);
+static tree c_fully_fold_internal (tree expr, bool, bool *, bool *, bool);
 static tree check_case_value (location_t, tree);
 static bool check_case_bounds (location_t, tree, tree, tree *, tree *);
 
@@ -1148,7 +1148,7 @@ c_fully_fold (tree expr, bool in_init, bool *maybe_const)
   expr = TREE_OPERAND (expr, 0);
 }
   ret = c_fully_fold_internal (expr, in_init, maybe_const,
-  maybe_const_itself);
+  maybe_const_itself, false);
   if (eptype)
 ret = fold_convert_loc (loc, eptype, ret);
   *maybe_const = maybe_const_itself;
@@ -1161,11 +1161,13 @@ c_fully_fold (tree expr, bool in_init, bool 
*maybe_const)
arithmetic overflow (for C90, *MAYBE_CONST_OPERANDS is carried from
both evaluated and unevaluated subexpressions while
*MAYBE_CONST_ITSELF is carried from only evaluated
-   subexpressions).  */
+   subexpressions).  FOR_INT_CONST indicates if EXPR is an expression
+   with integer constant operands, and if any of the operands doesn't
+   get folded to an integer constant, don't fold the expression itself.  */
 
 static tree
 c_fully_fold_internal (tree expr, bool in_init, bool *maybe_const_operands,
-  bool *maybe_const_itself)
+  bool *maybe_const_itself, bool for_int_const)
 {
   tree ret = expr;
   enum tree_code code = TREE_CODE (expr);
@@ -1209,7 +1211,11 @@ c_fully_fold_internal (tree expr, bool in_init, bool 
*maybe_const_operands,
   if (C_MAYBE_CONST_EXPR_NON_CONST (expr))
*maybe_const_operands = false;
   if (C_MAYBE_CONST_EXPR_INT_OPERANDS (expr))
-   *maybe_const_itself = false;
+   {
+ *maybe_const_itself = false;
+ inner = c_fully_fold_internal (inner, in_init, maybe_const_operands,
+maybe_const_itself, true);
+   }
   if (pre  !in_init)
ret = build2 (COMPOUND_EXPR, TREE_TYPE (expr), pre, inner);
   else
@@ -1259,7 +1265,7 @@ c_fully_fold_internal (tree expr, bool in_init, bool 
*maybe_const_operands,
   op1 = TREE_OPERAND (expr, 1);
   op2 = TREE_OPERAND (expr, 2);
   op0 = c_fully_fold_internal (op0, in_init, maybe_const_operands,
-  maybe_const_itself);
+  maybe_const_itself, for_int_const);
   STRIP_TYPE_NOPS (op0);
   if (op0 != orig_op0)
ret = build3 (COMPONENT_REF, TREE_TYPE (expr), op0, op1, op2);
@@ -1276,10 +1282,10 @@ c_fully_fold_internal (tree expr, bool in_init, bool 
*maybe_const_operands,
   op2 = TREE_OPERAND (expr, 2);
   op3 = TREE_OPERAND (expr, 3);
   op0 = c_fully_fold_internal (op0, in_init, maybe_const_operands,
-  maybe_const_itself);
+  maybe_const_itself, for_int_const);
   STRIP_TYPE_NOPS (op0);
   op1 = c_fully_fold_internal (op1, in_init, maybe_const_operands,
-  maybe_const_itself);
+  maybe_const_itself, for_int_const);
   STRIP_TYPE_NOPS (op1);
   op1 = decl_constant_value_for_optimization (op1);
 

Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Jakub Jelinek
On Thu, May 14, 2015 at 11:48:55AM +0200, Richard Biener wrote:
 On May 14, 2015 10:10:35 AM GMT+02:00, Marek Polacek pola...@redhat.com 
 wrote:
 On Thu, May 14, 2015 at 09:59:49AM +0200, Richard Biener wrote:
  Do the patches allow us to remove the restrictions from the folding
 patterns?
 
 With the c_fully_fold_internal patches there's no need to tweak any
 match.pd
 patterns.  So PR66127 + PR66066 are to be solved solely in the C FE. 
 Is that
 what you're asking about?
 
 No, I'm asking whether we can remove the existing guards in match.pd.

There is also the C++ FE...

Jakub


Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Marek Polacek
On Thu, May 14, 2015 at 11:48:55AM +0200, Richard Biener wrote:
 On May 14, 2015 10:10:35 AM GMT+02:00, Marek Polacek pola...@redhat.com 
 wrote:
 On Thu, May 14, 2015 at 09:59:49AM +0200, Richard Biener wrote:
  Do the patches allow us to remove the restrictions from the folding
 patterns?
 
 With the c_fully_fold_internal patches there's no need to tweak any
 match.pd
 patterns.  So PR66127 + PR66066 are to be solved solely in the C FE. 
 Is that
 what you're asking about?
 
 No, I'm asking whether we can remove the existing guards in match.pd.

Sorry, I don't know which guards exactly you mean (side effects?) so can't
verify, but as Jakub points out, I doubt we can remove anything at this point
because of C++ FE.  (c_fully_fold{,_internal} are never used in the C++ FE.)

Marek


Re: [PATCH] Don't fold away division by zero (PR middle-end/66127)

2015-05-14 Thread Richard Biener
On May 14, 2015 10:10:35 AM GMT+02:00, Marek Polacek pola...@redhat.com wrote:
On Thu, May 14, 2015 at 09:59:49AM +0200, Richard Biener wrote:
 Do the patches allow us to remove the restrictions from the folding
patterns?

With the c_fully_fold_internal patches there's no need to tweak any
match.pd
patterns.  So PR66127 + PR66066 are to be solved solely in the C FE. 
Is that
what you're asking about?

No, I'm asking whether we can remove the existing guards in match.pd.

Richard.

   Marek




[Bug middle-end/66127] Division by zero gets folded away

2015-05-13 Thread rguenth at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66127

--- Comment #4 from Richard Biener rguenth at gcc dot gnu.org ---
Note that the inconsistent handling of */% 0 has been 1:1 translated from
fold-const.c (also the comments).


[Bug middle-end/66127] Division by zero gets folded away

2015-05-13 Thread mpolacek at gcc dot gnu.org
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66127

Marek Polacek mpolacek at gcc dot gnu.org changed:

   What|Removed |Added

 Status|UNCONFIRMED |ASSIGNED
   Last reconfirmed||2015-05-13
   Assignee|unassigned at gcc dot gnu.org  |mpolacek at gcc dot 
gnu.org
   Target Milestone|--- |6.0
 Ever confirmed|0   |1

--- Comment #5 from Marek Polacek mpolacek at gcc dot gnu.org ---
I have some patch...


  1   2   3   4   >