Skip to content

-ffp-contract difference for runtime / compile-time operations #128545

Open
@jcarreira

Description

@jcarreira

I have a piece of code that computes different floating point results depending on whether the computation happens at compilation time or at runtime (see https://godbolt.org/z/q65q4f7c3 ).

When the values are known at compile time the compiler contracts the operation and computes the result. When they are not known, the expression is computed at runtime without contraction.

#include <iostream>
#include <cmath>
#include <iomanip>

int main() {
  double x = 30.508474576271183309;
  double y = 6.1016949152542370172;

  double r = (x-std::trunc(x/y)*y);

  std::cout << std::setprecision(17);
  std::cout << "compile time (w/ fma): " << r << std::endl;

  volatile double *xx = &x;
  volatile double *yy = &y;

  r = (*xx-std::trunc(*xx/(*yy))*(*yy));
  std::cout << "runtime (w/o fma): " << r << std::endl;

  r = std::fma(std::trunc(*xx/(*yy)),-(*yy),*xx);
  std::cout << "runtime (w/ explicit fma): " << r << std::endl;

  return 0;
}

The output is (with -O3 -ffp-contract=on):

compile time (w/ fma): -1.7763568394002505e-15
runtime (w/o fma): 0
runtime (w/ explicit fma): -1.7763568394002505e-15

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions