[v2] c: Extend the -Wpadded message with actual padding size

Message ID YrMCB2Vu1r45C362@czspare1-lap.sysgo.cz
State New
Headers
Series [v2] c: Extend the -Wpadded message with actual padding size |

Commit Message

Vit Kabele June 22, 2022, 11:50 a.m. UTC
  Hello,
I added the ! default_packed directive, and now the test is properly
skipped on the targets with that property. I tested with cris-elf
target and the test behaves properly.

Best regards,
Vit Kabele

-- >8 --
Subject: [PATCH v2] c: Extend the -Wpadded message with actual padding size

When the compiler warns about padding struct to alignment boundary, it
now also informs the user about the size of the alignment that needs to
be added to get rid of the warning.

This removes the need of using pahole or similar tools, or manually
determining the padding size.

Tested for x86_64-pc-linux-gnu and cris-elf targets.

gcc/ChangeLog:

	* stor-layout.cc (finalize_record_size): Extend warning message.

gcc/testsuite/ChangeLog:

	* c-c++-common/Wpadded.c: New test.

Signed-off-by: Vit Kabele <vit.kabele@sysgo.com>
---
 gcc/stor-layout.cc                   |  7 ++++++-
 gcc/testsuite/c-c++-common/Wpadded.c | 13 +++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)
 create mode 100644 gcc/testsuite/c-c++-common/Wpadded.c
  

Patch

diff --git a/gcc/stor-layout.cc b/gcc/stor-layout.cc
index 765f22f68b9..88923c4136b 100644
--- a/gcc/stor-layout.cc
+++ b/gcc/stor-layout.cc
@@ -1781,7 +1781,12 @@  finalize_record_size (record_layout_info rli)
       && simple_cst_equal (unpadded_size, TYPE_SIZE (rli->t)) == 0
       && input_location != BUILTINS_LOCATION
       && !TYPE_ARTIFICIAL (rli->t))
-    warning (OPT_Wpadded, "padding struct size to alignment boundary");
+  {
+	tree pad_size
+	  = size_binop (MINUS_EXPR, TYPE_SIZE_UNIT (rli->t), unpadded_size_unit);
+	  warning (OPT_Wpadded,
+		"padding struct size to alignment boundary with %E bytes", pad_size);
+  }
 
   if (warn_packed && TREE_CODE (rli->t) == RECORD_TYPE
       && TYPE_PACKED (rli->t) && ! rli->packed_maybe_necessary
diff --git a/gcc/testsuite/c-c++-common/Wpadded.c b/gcc/testsuite/c-c++-common/Wpadded.c
new file mode 100644
index 00000000000..9e7e9f240c1
--- /dev/null
+++ b/gcc/testsuite/c-c++-common/Wpadded.c
@@ -0,0 +1,13 @@ 
+/* { dg-do compile } */
+/* { dg-options "-Wpadded" } */
+
+/*
+ * The struct is on single line, because C++ compiler emits the -Wpadded
+ * warning at the first line of the struct definition, while the C compiler at
+ * the last line. This way the test passes on both.
+ * 
+ * The test is skipped on targets where default behavior is to pack the
+ * structs because there is no warning triggered.
+ */
+struct S { __UINT32_TYPE__ i; char c; } foo; /* { dg-warning "padding struct size to alignment boundary with 3 bytes" "" { target { ! default_packed } } } */
+