[clang] [Clang][analyzer] add documentation for optin performance padding (padding checker) #73675 (PR #86411)

Balazs Benics via cfe-commits cfe-commits at lists.llvm.org
Mon Mar 25 08:01:57 PDT 2024


================
@@ -804,10 +804,38 @@ Check for performance anti-patterns when using Grand Central Dispatch.
 
 .. _optin-performance-Padding:
 
-optin.performance.Padding
-"""""""""""""""""""""""""
+optin.performance.Padding (C, C++, ObjC)
+""""""""""""""""""""""""""""""""""""""""
 Check for excessively padded structs.
 
+This checker detects structs with excessive padding, which can lead to wasted memory and decreased performance. Padding bytes are added by compilers to align data within the struct for performance optimization or memory alignment purposes. However, excessive padding can significantly increase the size of the struct without adding useful data, leading to inefficient memory usage, cache misses, and decreased performance.
+
+.. code-block:: c
+
+   #include <stdio.h>
+   // #pragma pack(1) // Uncomment it to disable structure padding
+   struct TestStruct {
+       char data1;  // 1 byte
+       char data2;  // 1 byte
+       int data3;   // 4 bytes
+   };             // Total size: 6 bytes
+   
+   int main () {
+       struct TestStruct struct1;
+       printf("Structure size: %d",sizeof(struct1)); // Structure size: 8
+       return 0;
+   }
+   
+Total memory used is 8 bytes due to structure padding. In this case, padding is of 2 bytes. Padding is done to decrease the number of CPU cycles needed to access data members of the structure, it increases the performance of the processor but at the penalty of memory.
+Padding can be disabled by using the pragma directive.
+Padding can also be decreased by putting data members of the structure in descending order of their size.
+
+Reports are only generated if the excessive padding exceeds ``AllowedPad`` in bytes. AllowedPad is the threshold value of padding.
----------------
steakhal wrote:

The `AllowedPad is the threshold value of padding.` part is not clear to me.
Does it apply if a single padding between two fields is larger than this, or the total padding within the struct?
Is the trailing padding, or padding between the fields included even if there is no better way ordering the fields? In other words, would I have a warning if my fields are in the optimal order, but the padding between two fields are larger than `AllowedPad`? 

https://github.com/llvm/llvm-project/pull/86411


More information about the cfe-commits mailing list