[compiler-rt] [compiler-rt][builtins] Switch to using __builtin_memcpy_inline (PR #69784)

Alexander Shaposhnikov via llvm-commits llvm-commits at lists.llvm.org
Fri Oct 20 14:38:30 PDT 2023


https://github.com/alexander-shaposhnikov created https://github.com/llvm/llvm-project/pull/69784

Switch to using __builtin_memcpy_inline.
This code has existed for quite a while, to the best of my knowledge compilers
try to be nice not to exploit this UB (writing to one field of a union and reading from the other),
yet strictly speaking this UB.

Test plan: ninja && ninja check-compiler-rt

>From 944315a8b8b2c1621312419c49514b60b5a4c52a Mon Sep 17 00:00:00 2001
From: Alexander Shaposhnikov <ashaposhnikov at google.com>
Date: Fri, 20 Oct 2023 21:35:12 +0000
Subject: [PATCH] [compiler-rt][builtins] Switch to using
 __builtin_memcpy_inline

---
 compiler-rt/lib/builtins/fp_extend.h | 17 +++++++----------
 compiler-rt/lib/builtins/fp_trunc.h  | 16 ++++++----------
 2 files changed, 13 insertions(+), 20 deletions(-)

diff --git a/compiler-rt/lib/builtins/fp_extend.h b/compiler-rt/lib/builtins/fp_extend.h
index d640bdcb0ec1fa4..dcf7f3ad2d57dc3 100644
--- a/compiler-rt/lib/builtins/fp_extend.h
+++ b/compiler-rt/lib/builtins/fp_extend.h
@@ -157,20 +157,17 @@ static inline dst_rep_t construct_dst_rep(dst_rep_t sign, dst_rep_t exp, dst_rep
 // floating-point data as integer values follow.
 
 static inline src_rep_t srcToRep(src_t x) {
-  const union {
-    src_t f;
-    src_rep_t i;
-  } rep = {.f = x};
-  return rep.i;
+  src_rep_t rep;
+  __builtin_memcpy_inline(&rep, &x, sizeof(rep));
+  return rep;
 }
 
 static inline dst_t dstFromRep(dst_rep_t x) {
-  const union {
-    dst_t f;
-    dst_rep_t i;
-  } rep = {.i = x};
-  return rep.f;
+  dst_t dst;
+  __builtin_memcpy_inline(&dst, &x, sizeof(dst));
+  return dst;
 }
+
 // End helper routines.  Conversion implementation follows.
 
 #endif // FP_EXTEND_HEADER
diff --git a/compiler-rt/lib/builtins/fp_trunc.h b/compiler-rt/lib/builtins/fp_trunc.h
index f62f8bafc7995f7..a55ffa9988e7839 100644
--- a/compiler-rt/lib/builtins/fp_trunc.h
+++ b/compiler-rt/lib/builtins/fp_trunc.h
@@ -146,19 +146,15 @@ static inline dst_rep_t construct_dst_rep(dst_rep_t sign, dst_rep_t exp, dst_rep
 // from the representation of floating-point data as integer values follow.
 
 static inline src_rep_t srcToRep(src_t x) {
-  const union {
-    src_t f;
-    src_rep_t i;
-  } rep = {.f = x};
-  return rep.i;
+  src_rep_t rep;
+  __builtin_memcpy_inline(&rep, &x, sizeof(rep));
+  return rep;
 }
 
 static inline dst_t dstFromRep(dst_rep_t x) {
-  const union {
-    dst_t f;
-    dst_rep_t i;
-  } rep = {.i = x};
-  return rep.f;
+  dst_t dst;
+  __builtin_memcpy_inline(&dst, &x, sizeof(dst));
+  return dst;
 }
 
 #endif // FP_TRUNC_HEADER



More information about the llvm-commits mailing list