[llvm] Support non-malloc functions in malloc+memset->calloc fold (PR #138299)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Sat May 3 00:52:57 PDT 2025


================
@@ -2057,15 +2066,31 @@ struct DSEState {
 
     if (Malloc->getOperand(0) != MemSet->getLength())
       return false;
-    if (!shouldCreateCalloc(Malloc, MemSet) ||
-        !DT.dominates(Malloc, MemSet) ||
+    if (!shouldCreateCalloc(Malloc, MemSet) || !DT.dominates(Malloc, MemSet) ||
         !memoryIsNotModifiedBetween(Malloc, MemSet, BatchAA, DL, &DT))
       return false;
     IRBuilder<> IRB(Malloc);
-    Type *SizeTTy = Malloc->getArgOperand(0)->getType();
-    auto *Calloc =
-        emitCalloc(ConstantInt::get(SizeTTy, 1), Malloc->getArgOperand(0), IRB,
-                   TLI, Malloc->getType()->getPointerAddressSpace());
+    assert(Func == LibFunc_malloc || ZeroedVariantName.has_value());
+    Value *Calloc = nullptr;
+    if (ZeroedVariantName.has_value()) {
+      auto &Ctx = Malloc->getContext();
+      auto Attr = InnerCallee->getAttributes();
+      auto AllocKind = Attr.getFnAttr(Attribute::AllocKind).getAllocKind() |
+                       AllocFnKind::Zeroed;
+      Attr =
+          Attr.addFnAttribute(Ctx, Attribute::getWithAllocKind(Ctx, AllocKind));
+      auto ZeroedVariant = Malloc->getModule()->getOrInsertFunction(
+          *ZeroedVariantName, InnerCallee->getFunctionType(), Attr);
+      SmallVector<Value *, 3> Args;
+      for (unsigned I = 0; I < Malloc->arg_size(); I++)
+        Args.push_back(Malloc->getArgOperand(I));
----------------
nikic wrote:

Can `append_range(Args, Malloc->args())` here, I think.

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


More information about the llvm-commits mailing list