[llvm] r339521 - [Support][JSON][NFC] Silence GCC warning about broken strict aliasing rules

David Bolvansky via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 12 10:31:46 PDT 2018


Author: xbolva00
Date: Sun Aug 12 10:31:46 2018
New Revision: 339521

URL: http://llvm.org/viewvc/llvm-project?rev=339521&view=rev
Log:
[Support][JSON][NFC] Silence GCC warning about broken strict aliasing rules

Summary:
The as<T>() method would trigger the following warning on GCC <7:

   warning: dereferencing type-punned pointer will break
       strict-aliasing rules [-Wstrict-aliasing]

     return *reinterpret_cast<T *>(Union.buffer);
                                               ^

Union.buffer is guaranteed to be aligned to whatever types it contains,
and json::Value maintains the invariant that it only calls as<T>() for a
T it has previously placement-newed into Union.buffer. This should
follow the rules for strict aliasing.

Using two static_cast via void * instead of reinterpret_cast
silences the warning and presumably makes GCC understand that no
strict-aliasing violation is happening.

No functional change intended.

Patch by: kimgr (Kim Gräsman)

Reviewers: sammccall, xiangzhai, HaoLiu, llvm-commits, xbolva00

Reviewed By: sammccall, xbolva00

Subscribers: xbolva00

Differential Revision: https://reviews.llvm.org/D50608

Modified:
    llvm/trunk/include/llvm/Support/JSON.h

Modified: llvm/trunk/include/llvm/Support/JSON.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/JSON.h?rev=339521&r1=339520&r2=339521&view=diff
==============================================================================
--- llvm/trunk/include/llvm/Support/JSON.h (original)
+++ llvm/trunk/include/llvm/Support/JSON.h Sun Aug 12 10:31:46 2018
@@ -452,7 +452,10 @@ private:
     new (reinterpret_cast<T *>(Union.buffer)) T(std::forward<U>(V)...);
   }
   template <typename T> T &as() const {
-    return *reinterpret_cast<T *>(Union.buffer);
+    // Using this two-step static_cast via void * instead of reinterpret_cast
+    // silences a -Wstrict-aliasing false positive from GCC6 and earlier.
+    void *Storage = static_cast<void *>(Union.buffer);
+    return *static_cast<T *>(Storage);
   }
 
   template <typename Indenter>




More information about the llvm-commits mailing list