[clang] [clang][CodeGen] Zero init unspecified fields in initializers in C (PR #97121)

Eli Friedman via cfe-commits cfe-commits at lists.llvm.org
Tue Aug 27 13:43:06 PDT 2024


================
@@ -1745,13 +1748,48 @@ void AggExprEmitter::VisitCXXParenListOrInitListExpr(
       // Default-initialize to null.
       EmitNullInitializationToLValue(FieldLoc);
     }
+    if (ZeroInitPadding) {
+      CharUnits TotalSize =
+          Dest.getPreferredSize(CGF.getContext(), DestLV.getType());
+      CharUnits FieldSize =
+          CGF.getContext().getTypeSizeInChars(FieldLoc.getType());
+      if (FieldSize < TotalSize) {
+        CharUnits LeftSize = TotalSize - FieldSize;
+        llvm::Constant *LeftSizeVal =
+            CGF.Builder.getInt64(LeftSize.getQuantity());
+        Address BaseLoc = Dest.getAddress().withElementType(CGF.Int8Ty);
+        Address LeftLoc =
+            CGF.Builder.CreateConstGEP(BaseLoc, LeftSize.getQuantity());
+        CGF.Builder.CreateMemSet(LeftLoc, CGF.Builder.getInt8(0), LeftSizeVal,
+                                 false);
+      }
+    }
 
     return;
   }
 
   // Here we iterate over the fields; this makes it simpler to both
   // default-initialize fields and skip over unnamed fields.
+  const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(record);
+  Address BaseLoc = Dest.getAddress().withElementType(CGF.Int8Ty);
+  CharUnits SizeSoFar = CharUnits::Zero();
   for (const auto *field : record->fields()) {
+    if (ZeroInitPadding) {
+      unsigned FieldNo = field->getFieldIndex();
+      CharUnits Offset =
+          CGF.getContext().toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
+      if (SizeSoFar < Offset) {
+        llvm::Constant *PaddingSizeVal =
+            CGF.Builder.getInt64((Offset - SizeSoFar).getQuantity());
+        Address PaddingLoc =
+            CGF.Builder.CreateConstGEP(BaseLoc, SizeSoFar.getQuantity());
+        CGF.Builder.CreateMemSet(PaddingLoc, CGF.Builder.getInt8(0),
----------------
efriedma-quic wrote:

Use a lambda to unify the code a bit?

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


More information about the cfe-commits mailing list