[PATCH] D28161: [ADT] Use memcpy for type punning in MathExtras.

Justin Lebar via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Thu Dec 29 10:26:13 PST 2016


This revision was automatically updated to reflect the committed changes.
Closed by commit rL290715: [ADT] Use memcpy for type punning in MathExtras. (authored by jlebar).

Changed prior to commit:
  https://reviews.llvm.org/D28161?vs=82675&id=82679#toc

Repository:
  rL LLVM

https://reviews.llvm.org/D28161

Files:
  llvm/trunk/include/llvm/Support/MathExtras.h


Index: llvm/trunk/include/llvm/Support/MathExtras.h
===================================================================
--- llvm/trunk/include/llvm/Support/MathExtras.h
+++ llvm/trunk/include/llvm/Support/MathExtras.h
@@ -547,49 +547,41 @@
 /// BitsToDouble - This function takes a 64-bit integer and returns the bit
 /// equivalent double.
 inline double BitsToDouble(uint64_t Bits) {
-  union {
-    uint64_t L;
-    double D;
-  } T;
-  T.L = Bits;
-  return T.D;
+  double D;
+  static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
+  memcpy(&D, &Bits, sizeof(Bits));
+  return D;
 }
 
 /// BitsToFloat - This function takes a 32-bit integer and returns the bit
 /// equivalent float.
 inline float BitsToFloat(uint32_t Bits) {
-  union {
-    uint32_t I;
-    float F;
-  } T;
-  T.I = Bits;
-  return T.F;
+  float F;
+  static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
+  memcpy(&F, &Bits, sizeof(Bits));
+  return F;
 }
 
 /// DoubleToBits - This function takes a double and returns the bit
 /// equivalent 64-bit integer.  Note that copying doubles around
 /// changes the bits of NaNs on some hosts, notably x86, so this
 /// routine cannot be used if these bits are needed.
 inline uint64_t DoubleToBits(double Double) {
-  union {
-    uint64_t L;
-    double D;
-  } T;
-  T.D = Double;
-  return T.L;
+  uint64_t Bits;
+  static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
+  memcpy(&Bits, &Double, sizeof(Double));
+  return Bits;
 }
 
 /// FloatToBits - This function takes a float and returns the bit
 /// equivalent 32-bit integer.  Note that copying floats around
 /// changes the bits of NaNs on some hosts, notably x86, so this
 /// routine cannot be used if these bits are needed.
 inline uint32_t FloatToBits(float Float) {
-  union {
-    uint32_t I;
-    float F;
-  } T;
-  T.F = Float;
-  return T.I;
+  uint32_t Bits;
+  static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
+  memcpy(&Bits, &Float, sizeof(Float));
+  return Bits;
 }
 
 /// MinAlign - A and B are either alignments or offsets.  Return the minimum


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D28161.82679.patch
Type: text/x-patch
Size: 2138 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20161229/21361f18/attachment.bin>


More information about the llvm-commits mailing list