[LLVMdev] Integer divide by zero

dag at cray.com dag at cray.com
Tue Apr 16 09:41:14 PDT 2013


Joe Groff <arcata at gmail.com> writes:

> Constant folding undefined expressions is sort of silly, but I
> appreciate that it makes undefined behavior problems in frontends
> immediately apparent with trivial cases before they creep up on you in
> more complicated optimized code. After all, even if the backend makes
> practical concessions to trivial cases, the underlying semantic
> problem is still there and will bite you eventually.

Not necessarily.  It's not uncommon for Fortran programmers to do
something like this (C-tran pseudo code):

if (error) then
  temp = x / 0  ; Force a trap to get into the debugger
end if

The user is relying on trapping behavior to help debug code.  There is
no bad behavior to bite one later.  Optimizing traps away is unfriendly
in cases like this.

> For high-level languages like Julia that want to provide efficiency
> but also give defined behavior to all user-exposed cases, I think
> adding an LLVM intrinsic to represent division that's defined to trap
> on division by zero or overflow would be the best solution. Since the
> trap is a side effect, it would stifle optimization of code that used
> the intrinsic, but the intrinsic could still be lowered to a single
> hardware instruction and avoid the branching and code bloat of manual
> checks on hardware where division by zero natively traps.

What about the case where other optimization exposes a constant divide
by zero later on?  There is no way for a frontend to know to emit the
intrinsic _a_priori_.  We don't want to force all divides to use an
intrinsic because it will kill optimization.

I think to handle the general case we will need a flag to preserve
traps.

                            -David



More information about the llvm-dev mailing list