diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr107394.c b/gcc/testsuite/gcc.dg/tree-ssa/pr107394.c
new file mode 100644
index 0000000000000000000000000000000000000000..0e1e5ac40cea42b5d6d9c52ee90c974088c181d3
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/pr107394.c
@@ -0,0 +1,22 @@
+// { dg-do compile }
+// { dg-options "-O2" }
+
+static double
+quux (double x)
+{
+  return __builtin_fabs (x);
+}
+
+__attribute__ ((flatten, optimize ("-ffinite-math-only"))) static int
+bar (int *p)
+{
+  *p = quux (0.0);
+
+  return 0;
+}
+
+void
+foo (int *p)
+{
+  (void) bar (p);
+}
diff --git a/gcc/value-range-storage.cc b/gcc/value-range-storage.cc
index 6e05462283012d8ea8b1fab8f0bc8a7f301dbcf1..462447ba250a4d140c0f068000cbfb090bd7b08b 100644
--- a/gcc/value-range-storage.cc
+++ b/gcc/value-range-storage.cc
@@ -261,17 +261,28 @@ frange_storage_slot::get_frange (frange &r, tree type) const
 {
   gcc_checking_assert (r.supports_type_p (type));
 
-  r.set_undefined ();
-  r.m_kind = m_kind;
-  r.m_type = type;
-  r.m_min = m_min;
-  r.m_max = m_max;
-  r.m_pos_nan = m_pos_nan;
-  r.m_neg_nan = m_neg_nan;
-  r.normalize_kind ();
-
-  if (flag_checking)
-    r.verify_range ();
+  // Handle explicit NANs.
+  if (m_kind == VR_NAN)
+    {
+      if (HONOR_NANS (type))
+	{
+	  if (m_pos_nan && m_neg_nan)
+	    r.set_nan (type);
+	  else
+	    r.set_nan (type, m_neg_nan);
+	}
+      else
+	r.set_undefined ();
+      return;
+    }
+
+  // Use the constructor because it will canonicalize the range.
+  r = frange (type, m_min, m_max, m_kind);
+
+  // The constructor will set the NAN bits for HONOR_NANS, but we must
+  // make sure to set the NAN sign if known.
+  if (HONOR_NANS (type) && (m_pos_nan ^ m_neg_nan) == 1)
+    r.update_nan (m_neg_nan);
 }
 
 bool