[clang] 507bbc4 - [AST][NFC] Silence GCC warning about broken strict aliasing rules

Thomas Preud'homme via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 4 06:34:59 PST 2020


Author: Thomas Preud'homme
Date: 2020-12-04T14:34:51Z
New Revision: 507bbc45bba90fab3f1a2b42e94ae4fbebdd6498

URL: https://github.com/llvm/llvm-project/commit/507bbc45bba90fab3f1a2b42e94ae4fbebdd6498
DIFF: https://github.com/llvm/llvm-project/commit/507bbc45bba90fab3f1a2b42e94ae4fbebdd6498.diff

LOG: [AST][NFC] Silence GCC warning about broken strict aliasing rules

The deserialize() method would trigger the following warning on GCC <7:

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

       ParamIdx P(*reinterpret_cast<ParamIdx *>(&S));
                                                  ^

&S was previously reinterpret_casted from a ParamIdx into a SerialType,
it is therefore safe to cast back into a ParamIdx. Similar to what was
done in D50608, we replace it with two static_cast via void * which
silences the warning and presumably makes GCC understand that no
strict-aliasing violation is happening.

No functional change intended.

Reviewed By: aaron.ballman

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

Added: 
    

Modified: 
    clang/include/clang/AST/Attr.h

Removed: 
    


################################################################################
diff  --git a/clang/include/clang/AST/Attr.h b/clang/include/clang/AST/Attr.h
index 545dc992c5ed..8d9fb8f2bf27 100644
--- a/clang/include/clang/AST/Attr.h
+++ b/clang/include/clang/AST/Attr.h
@@ -259,7 +259,10 @@ class ParamIdx {
 
   /// Construct from a result from \c serialize.
   static ParamIdx deserialize(SerialType S) {
-    ParamIdx P(*reinterpret_cast<ParamIdx *>(&S));
+    // Using this two-step static_cast via void * instead of reinterpret_cast
+    // silences a -Wstrict-aliasing false positive from GCC7 and earlier.
+    void *ParamIdxPtr = static_cast<void *>(&S);
+    ParamIdx P(*static_cast<ParamIdx *>(ParamIdxPtr));
     assert((!P.IsValid || P.Idx >= 1) && "valid Idx must be one-origin");
     return P;
   }


        


More information about the cfe-commits mailing list