[clang] [llvm] [AllocToken] Propagate !alloc_token through inlined malloc_span wrappers (PR #244314)

David Li via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 25 14:57:18 PST 2026


https://github.com/david-xl updated https://github.com/llvm/llvm-project/pull/244314

>From dd2eecc547a17fce47b7386e88f558aa0204048e Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Sun, 22 Nov 2026 20:19:50 -0800
Subject: [PATCH] [AllocToken] Propagate !alloc_token through inlined
 malloc_span wrappers

#198535 propagates the !alloc_token of a call to an inlined allocation
wrapper to the allocation call whose result the wrapper returns, so a type
known at the wrapper's call site (e.g. from a sizeof in the size argument)
applies to the underlying allocation. It only follows pointer-typed return
values, so for a malloc_span wrapper such as

  __attribute__((always_inline, malloc_span))
  inline sized_ptr_t AllocateBytes(size_t n) {
    return __size_returning_new(n);
  }

  sized_ptr_t s = AllocateBytes(n * sizeof(char));

the call site's pointer-free type was dropped and __size_returning_new kept
the fallback token. This lets size-returning wrappers shared by several
types be typed at each call site rather than inside the wrapper.

Follow the returned value as a whole, of any type, through casts, phis and
selects, and through a load of a local temporary from the value last
stored to it in the same block (FindAvailableLoadedValue), as before SROA.
Spans assembled from their fields are not followed: in particular
field-wise stores to the return temporary (x86-64 before SROA), sret
returns, and temporaries filled by memcpy keep the fallback token.

Assisted-by: Gemini
---
 clang/docs/AllocToken.md                     |   7 +-
 llvm/lib/Transforms/Utils/InlineFunction.cpp |  30 +++--
 llvm/test/Transforms/Inline/alloc-token.ll   | 123 +++++++++++++++++++
 3 files changed, 148 insertions(+), 12 deletions(-)

diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index cca7136b652abd..613338f962ec71 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -172,10 +172,13 @@ ptr2 = __alloc_token_my_malloc(size, token_id);
 ```
 
 Note: Even in the default mode (without `-fsanitize-alloc-token-extended`),
-an *inline* allocation wrapper marked with the [malloc][malloc-attribute] or
-[alloc_size][alloc-size-attribute] attribute is
+an *inline* allocation wrapper marked with the [malloc][malloc-attribute],
+`malloc_span`, or [alloc_size][alloc-size-attribute] attribute is
 supported if it is inlined into its caller: the inferred token is propagated to
 the allocation call the wrapper returns, which is then instrumented normally.
+The wrapper must return the allocation call's result unchanged, e.g.
+`return __size_returning_new(size);`; a span assembled from its fields is not
+supported.
 Wrappers that are not inlined still require
 `-fsanitize-alloc-token-extended`.
 
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 918c8c02493bd5..5a9f0341674fca 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -26,6 +26,7 @@
 #include "llvm/Analysis/CtxProfAnalysis.h"
 #include "llvm/Analysis/IndirectCallVisitor.h"
 #include "llvm/Analysis/InstructionSimplify.h"
+#include "llvm/Analysis/Loads.h"
 #include "llvm/Analysis/MemoryProfileInfo.h"
 #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
 #include "llvm/Analysis/ObjCARCUtil.h"
@@ -935,25 +936,34 @@ propagateMemProfMetadata(Function *Callee, CallBase &CB,
   }
 }
 
-/// Collect all calls that produce RetVal, following only pointer-preserving
-/// instructions (cast, phi, select).
-static void collectPointerReturningCalls(Value *RetVal,
-                                         SmallVectorImpl<CallBase *> &Out) {
+/// Collect the calls whose result RetVal returns as a whole, following casts,
+/// phis, selects, and a load of a local temporary from the value last stored
+/// to it in the same block (as emitted before SROA, e.g. when an always_inline
+/// wrapper is inlined at -O0).
+static void collectReturnedCalls(Value *RetVal,
+                                 SmallVectorImpl<CallBase *> &Out) {
   SmallVector<Value *, 8> Worklist{RetVal};
   SmallPtrSet<Value *, 8> Visited;
   while (!Worklist.empty()) {
     Value *V = Worklist.pop_back_val();
-    if (!V->getType()->isPointerTy() || !Visited.insert(V).second)
+    if (!Visited.insert(V).second)
       continue;
-    if (auto *CB = dyn_cast<CallBase>(V))
+    if (auto *CB = dyn_cast<CallBase>(V)) {
       Out.push_back(CB);
-    else if (isa<BitCastInst, AddrSpaceCastInst>(V))
+    } else if (isa<BitCastInst, AddrSpaceCastInst>(V)) {
       Worklist.push_back(cast<CastInst>(V)->getOperand(0));
-    else if (auto *PN = dyn_cast<PHINode>(V))
+    } else if (auto *PN = dyn_cast<PHINode>(V)) {
       append_range(Worklist, PN->incoming_values());
-    else if (auto *SI = dyn_cast<SelectInst>(V)) {
+    } else if (auto *SI = dyn_cast<SelectInst>(V)) {
       Worklist.push_back(SI->getTrueValue());
       Worklist.push_back(SI->getFalseValue());
+    } else if (auto *LI = dyn_cast<LoadInst>(V)) {
+      if (!isa<AllocaInst>(LI->getPointerOperand()->stripPointerCasts()))
+        continue;
+      BasicBlock::iterator ScanFrom = LI->getIterator();
+      Value *Stored = FindAvailableLoadedValue(LI, LI->getParent(), ScanFrom);
+      if (Stored && Stored->getType() == LI->getType())
+        Worklist.push_back(Stored);
     }
   }
 }
@@ -974,7 +984,7 @@ propagateAllocTokenMetadata(Function *CalledFunc, CallBase &CB,
   for (BasicBlock &BB : *CalledFunc)
     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
       if (Value *RV = RI->getReturnValue())
-        collectPointerReturningCalls(RV, AllocCalls);
+        collectReturnedCalls(RV, AllocCalls);
 
   for (CallBase *OrigCall : AllocCalls) {
     auto *ClonedCall = dyn_cast_or_null<CallBase>(VMap.lookup(OrigCall));
diff --git a/llvm/test/Transforms/Inline/alloc-token.ll b/llvm/test/Transforms/Inline/alloc-token.ll
index 99ab7160050508..dbf0c6317e081a 100644
--- a/llvm/test/Transforms/Inline/alloc-token.ll
+++ b/llvm/test/Transforms/Inline/alloc-token.ll
@@ -44,6 +44,129 @@ define ptr @overwrite_unknown() {
   ret ptr %c
 }
 
+declare { ptr, i64 } @__size_returning_new(i64)
+declare [2 x i64] @alloc_coerced(i64)
+declare { ptr, i8 } @find_or_insert(i64)
+
+; A malloc_span wrapper's allocation inherits the token when the span is
+; returned as a whole: directly, through a phi, or through a local temporary
+; it is stored to and loaded from (as before SROA; here coerced to [2 x i64]
+; as on AArch64).
+define internal { ptr, i64 } @span_direct(i64 %size) alwaysinline {
+  %s = call { ptr, i64 } @__size_returning_new(i64 %size)
+  ret { ptr, i64 } %s
+}
+
+define internal [2 x i64] @span_temporary(i64 %size) alwaysinline {
+  %retval = alloca { ptr, i64 }
+  %s = call [2 x i64] @alloc_coerced(i64 %size)
+  store [2 x i64] %s, ptr %retval
+  %r = load [2 x i64], ptr %retval
+  ret [2 x i64] %r
+}
+
+; The span from a non-allocating call, rebuilt from its fields, is not followed.
+define internal { ptr, i64 } @span_phi(i64 %size, i1 %c) alwaysinline {
+entry:
+  br i1 %c, label %reuse, label %fresh
+reuse:
+  %f = call { ptr, i8 } @find_or_insert(i64 %size)
+  %p = extractvalue { ptr, i8 } %f, 0
+  %s0 = insertvalue { ptr, i64 } poison, ptr %p, 0
+  %s1 = insertvalue { ptr, i64 } %s0, i64 %size, 1
+  br label %done
+fresh:
+  %n = call { ptr, i64 } @__size_returning_new(i64 %size)
+  br label %done
+done:
+  %r = phi { ptr, i64 } [ %s1, %reuse ], [ %n, %fresh ]
+  ret { ptr, i64 } %r
+}
+
+; CHECK-LABEL: define void @span_whole(
+; CHECK: call { ptr, i64 } @__size_returning_new(i64 4){{.*}}, !alloc_token [[MD]]
+; CHECK: call [2 x i64] @alloc_coerced(i64 4){{.*}}, !alloc_token [[MD]]
+; CHECK: call { ptr, i8 } @find_or_insert(i64 4){{$}}
+; CHECK: call { ptr, i64 } @__size_returning_new(i64 4){{.*}}, !alloc_token [[MD]]
+define void @span_whole(i1 %c) {
+  %a = call { ptr, i64 } @span_direct(i64 4), !alloc_token !0
+  %b = call [2 x i64] @span_temporary(i64 4), !alloc_token !0
+  %d = call { ptr, i64 } @span_phi(i64 4, i1 %c), !alloc_token !0
+  ret void
+}
+
+; A span assembled field by field in a temporary (as Clang emits on x86-64
+; before SROA) is not followed.
+define internal { ptr, i64 } @span_fields(i64 %size) alwaysinline {
+  %retval = alloca { ptr, i64 }
+  %s = call { ptr, i64 } @__size_returning_new(i64 %size)
+  %p = extractvalue { ptr, i64 } %s, 0
+  store ptr %p, ptr %retval
+  %n.addr = getelementptr inbounds { ptr, i64 }, ptr %retval, i32 0, i32 1
+  %n = extractvalue { ptr, i64 } %s, 1
+  store i64 %n, ptr %n.addr
+  %r = load { ptr, i64 }, ptr %retval
+  ret { ptr, i64 } %r
+}
+
+; CHECK-LABEL: define void @span_fields_unsupported(
+; CHECK: call { ptr, i64 } @__size_returning_new(i64 4){{$}}
+define void @span_fields_unsupported() {
+  %a = call { ptr, i64 } @span_fields(i64 4), !alloc_token !0
+  ret void
+}
+
+; A pointer wrapper returning through a temporary: the call whose result is
+; last stored before the load inherits the token, an earlier one does not.
+define internal ptr @ptr_temporary(i64 %size) alwaysinline {
+  %p = alloca ptr
+  %h = call ptr @helper()
+  store ptr %h, ptr %p
+  %m = call ptr @malloc(i64 %size)
+  store ptr %m, ptr %p
+  %r = load ptr, ptr %p
+  ret ptr %r
+}
+
+; A call that may write memory between the store and the load stops it.
+define internal ptr @ptr_clobbered(i64 %size) alwaysinline {
+  %p = alloca ptr
+  %m = call ptr @malloc(i64 %size)
+  store ptr %m, ptr %p
+  %h = call ptr @helper()
+  %r = load ptr, ptr %p
+  ret ptr %r
+}
+
+; CHECK-LABEL: define void @ptr_temporaries(
+; CHECK: call ptr @helper(){{$}}
+; CHECK: call ptr @malloc(i64 4){{.*}}, !alloc_token [[MD]]
+; CHECK: call ptr @malloc(i64 4){{$}}
+; CHECK: call ptr @helper(){{$}}
+define void @ptr_temporaries() {
+  %a = call ptr @ptr_temporary(i64 4), !alloc_token !0
+  %b = call ptr @ptr_clobbered(i64 4), !alloc_token !0
+  ret void
+}
+
+; A pointer taken out of a non-span struct such as {ptr, i8} returned by a
+; non-allocating call is not followed.
+define internal ptr @ptr_field(i64 %size, i1 %c) alwaysinline {
+  %f = call { ptr, i8 } @find_or_insert(i64 %size)
+  %p = extractvalue { ptr, i8 } %f, 0
+  %m = call ptr @malloc(i64 %size)
+  %r = select i1 %c, ptr %p, ptr %m
+  ret ptr %r
+}
+
+; CHECK-LABEL: define void @ptr_from_field(
+; CHECK: call { ptr, i8 } @find_or_insert(i64 4){{$}}
+; CHECK: call ptr @malloc(i64 4){{.*}}, !alloc_token [[MD]]
+define void @ptr_from_field(i1 %c) {
+  %a = call ptr @ptr_field(i64 4, i1 %c), !alloc_token !0
+  ret void
+}
+
 ; CHECK-DAG: [[MD]] = !{!"Outer", i1 true}
 ; CHECK-DAG: [[OWN]] = !{!"Inner", i1 false}
 ; CHECK-DAG: [[CALLER]] = !{!"Outer", i1 true, !"overwrite_unknown"}



More information about the cfe-commits mailing list