[clang] [AllocToken] Infer the allocated type from placement new into the result (PR #241548)
David Li via cfe-commits
cfe-commits at lists.llvm.org
Wed Nov 11 14:46:52 PST 2026
https://github.com/david-xl updated https://github.com/llvm/llvm-project/pull/241548
>From 20efd37de41849dda7b7a10c0598566f58a802ce Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 13:18:40 -0800
Subject: [PATCH 1/2] [AllocToken] Infer the allocated type from placement new
into the result
-fsanitize=alloc-token infers the allocated type of an untyped allocation
call (malloc, size-returning new, or any malloc/alloc_size function) from
a sizeof in its size argument or from a cast of its result. A common
idiom has neither: the code allocates raw storage and then constructs the
object in place,
void *mem = alloc(size);
T *obj = new (mem) T();
sized_ptr res = size_returning_alloc(size);
T *rep = new (res.p) T();
Such allocations currently get no type and therefore the fallback token,
which with a pointer-split token mode puts pointer-free objects into the
pointer-containing partition. In one large C++ code base this pattern
(an absl::Cord flat node allocated this way) accounts for ~40% of all
fallback-token memory that a type-aware profile marks as cold.
Add a third inference step: if no sizeof or cast names the type, look
for a placement new whose single placement argument is the allocation
call's result, either directly, through casts, parentheses or member
accesses (e.g. the pointer member of a size-returning allocation), or
via a local variable initialized with it. The placement-new uses of the
enclosing function body are collected once, lazily, per function
(infer_alloc::PlacementNewTypes, owned by CodeGenFunction). If different
types are constructed into the same storage, nothing is inferred. Like
the existing heuristics this ignores control flow and reassignments.
Custom placement operators (new (arena) T) are not affected since the
storage is not their placement argument. __builtin_infer_alloc_token is
unchanged, as it has no enclosing allocation to inspect.
Assisted-by: Gemini
---
clang/docs/AllocToken.md | 28 ++++++
clang/docs/ReleaseNotes.md | 7 ++
clang/include/clang/AST/InferAlloc.h | 50 ++++++++++-
clang/lib/AST/InferAlloc.cpp | 123 +++++++++++++++++++++++++-
clang/lib/CodeGen/CGExpr.cpp | 7 +-
clang/lib/CodeGen/CodeGenFunction.h | 6 ++
clang/test/CodeGenCXX/alloc-token.cpp | 106 ++++++++++++++++++++++
7 files changed, 323 insertions(+), 4 deletions(-)
diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index cca7136b652abd..6e6c9d4c84327a 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -56,6 +56,34 @@ The following command-line options affect generated token IDs:
is of the form `2^k-1` (e.g. the default `SIZE_MAX`), all `k` bits are
used and token IDs are in `[0, N]`, i.e. a token ID may be equal to `N`.
+## Allocated Type Inference
+
+For `new` expressions the allocated type is known. For allocation functions
+such as `malloc` that return untyped memory, the type is inferred from the
+allocation call and its surroundings, in this order:
+
+- A `sizeof` in a size argument, possibly in arithmetic:
+ `malloc(sizeof(T))`, `malloc(n * sizeof(T))`, `malloc(sizeof(T) + extra)`,
+ or a variable initialized from such an expression.
+- A cast of the result: `(T *)malloc(n)`.
+- Placement new into the result: `new (malloc(n)) T`, or, through a local
+ variable and optionally a cast or member access of the result,
+
+ ```c++
+ void *mem = alloc(n);
+ T *obj = new (mem) T; // infers 'T' for alloc(n)
+
+ sized_ptr res = size_returning_alloc(n);
+ T *obj = new (res.p) T; // infers 'T' for size_returning_alloc(n)
+ ```
+
+ If different types are constructed into the same storage, no type is
+ inferred.
+
+These are heuristics: they ignore control flow and reassignments of the
+variables involved. If no type can be inferred, the allocation receives the
+fallback token.
+
## Querying Token IDs with `__builtin_infer_alloc_token`
For use cases where the token ID must be known at compile time, Clang provides
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 72db5e7074108b..a945546b46610e 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1554,6 +1554,13 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
modes for `-fsanitize=alloc-token`, selected with
`-Xclang -falloc-token-mode=<mode>`. These modes derive token IDs from both
the allocated type and the name of the function containing the allocation.
+- `-fsanitize=alloc-token` type inference now also recognizes memory that is
+ used as placement-new storage: for `new (p) T`, where `p` is the result of an
+ allocation call (directly, through a cast or member access such as the
+ pointer of a size-returning allocation, or via a local variable initialized
+ with it), the allocation is attributed to `T`. This covers the common
+ "allocate raw storage, then construct in place" idiom, which previously
+ received no type and therefore the fallback token.
### Python Binding Changes
diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index c3dc30204feafe..b6a6b28e1ba419 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -15,15 +15,63 @@
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
+#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/AllocToken.h"
#include <optional>
namespace clang {
+
+class Stmt;
+class VarDecl;
+
namespace infer_alloc {
+/// Lazily collects, for one function body, the types constructed by placement
+/// new into memory returned by allocation calls. This lets the allocated type
+/// be inferred for the common "allocate raw storage, then placement-new the
+/// object into it" idiom, where neither a sizeof nor a cast names the type:
+///
+/// void *mem = alloc(size);
+/// MyType *obj = new (mem) MyType(); // infers 'MyType' for alloc(size)
+///
+/// auto res = size_returning_alloc(size);
+/// new (res.p) MyType(); // infers 'MyType' (via member .p)
+///
+/// new (alloc(size)) MyType(); // infers 'MyType'
+///
+/// The placement argument may be wrapped in parentheses, casts, or member
+/// accesses of the call result (or of a local variable initialized with it).
+/// If placement news of different types use the same allocation, no type is
+/// inferred. Like the other inference heuristics, this ignores control flow
+/// and reassignments of the variable.
+class PlacementNewTypes {
+public:
+ explicit PlacementNewTypes(const Stmt *Body) : Body(Body) {}
+
+ /// Returns the type placement-constructed into the result of allocation call
+ /// \p E, or a null type if there is none or it is ambiguous.
+ QualType lookup(const CallExpr *E);
+
+private:
+ void collect();
+
+ const Stmt *Body;
+ bool Collected = false;
+ // Allocation call -> placement-new type (null if ambiguous).
+ llvm::DenseMap<const CallExpr *, QualType> CallTypes;
+ // Variable -> placement-new type of its contents (null if ambiguous).
+ llvm::DenseMap<const VarDecl *, QualType> VarTypes;
+ // Allocation call -> variable it initializes.
+ llvm::DenseMap<const CallExpr *, const VarDecl *> CallVars;
+};
+
/// Infer the possible allocated type from an allocation call expression.
+/// \p CastE is the cast the call result is immediately used in, if any, and
+/// \p PlacementTypes the placement-new types of the enclosing function, if
+/// available.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
- const CastExpr *CastE);
+ const CastExpr *CastE,
+ PlacementNewTypes *PlacementTypes = nullptr);
/// Get the information required for construction of an allocation token ID.
std::optional<llvm::AllocTokenMetadata>
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 6c99a81d739f1e..5f665d7bee115d 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -15,6 +15,8 @@
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Type.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/SmallPtrSet.h"
@@ -169,7 +171,8 @@ static QualType inferPossibleTypeFromCastExpr(const CallExpr *CallE,
QualType infer_alloc::inferPossibleType(const CallExpr *E,
const ASTContext &Ctx,
- const CastExpr *CastE) {
+ const CastExpr *CastE,
+ PlacementNewTypes *PlacementTypes) {
QualType AllocType;
// First check arguments.
for (const Expr *Arg : E->arguments()) {
@@ -182,9 +185,127 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
// Then check later casts.
if (AllocType.isNull())
AllocType = inferPossibleTypeFromCastExpr(E, CastE);
+ // Finally check if the result is used as placement-new storage.
+ if (AllocType.isNull() && PlacementTypes)
+ AllocType = PlacementTypes->lookup(E);
return AllocType;
}
+namespace {
+/// Strips the wrappers a placement argument may have around the expression
+/// that produced the storage: parentheses, casts, member accesses (e.g. the
+/// pointer member of a size-returning allocation result), and
+/// address-of/dereference pairs.
+const Expr *stripToStorageSource(const Expr *E) {
+ while (true) {
+ E = E->IgnoreParenCasts();
+ if (const auto *ME = dyn_cast<MemberExpr>(E)) {
+ E = ME->getBase();
+ continue;
+ }
+ if (const auto *UO = dyn_cast<UnaryOperator>(E);
+ UO && (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref)) {
+ E = UO->getSubExpr();
+ continue;
+ }
+ return E;
+ }
+}
+
+/// Finds the allocation call that initializes a variable, looking through the
+/// temporaries and elidable copies a class-typed initializer may carry.
+const CallExpr *initializingCall(const Expr *Init) {
+ while (Init) {
+ Init = Init->IgnoreParenImpCasts();
+ if (const auto *EWC = dyn_cast<ExprWithCleanups>(Init)) {
+ Init = EWC->getSubExpr();
+ } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
+ Init = MTE->getSubExpr();
+ } else if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) {
+ Init = BTE->getSubExpr();
+ } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Init);
+ CE && CE->getNumArgs() == 1 &&
+ (CE->isElidable() ||
+ CE->getConstructor()->isCopyOrMoveConstructor())) {
+ Init = CE->getArg(0);
+ } else if (const auto *FCE = dyn_cast<CXXFunctionalCastExpr>(Init)) {
+ Init = FCE->getSubExpr();
+ } else {
+ break;
+ }
+ }
+ return dyn_cast_or_null<CallExpr>(Init);
+}
+
+/// Records placement-new types per allocation call and per variable.
+class PlacementNewCollector
+ : public RecursiveASTVisitor<PlacementNewCollector> {
+public:
+ PlacementNewCollector(
+ llvm::DenseMap<const CallExpr *, QualType> &CallTypes,
+ llvm::DenseMap<const VarDecl *, QualType> &VarTypes,
+ llvm::DenseMap<const CallExpr *, const VarDecl *> &CallVars)
+ : CallTypes(CallTypes), VarTypes(VarTypes), CallVars(CallVars) {}
+
+ bool shouldVisitTemplateInstantiations() const { return true; }
+ bool shouldVisitImplicitCode() const { return true; }
+
+ bool VisitVarDecl(const VarDecl *VD) {
+ if (const CallExpr *CE = initializingCall(VD->getInit()))
+ CallVars.try_emplace(CE, VD);
+ return true;
+ }
+
+ bool VisitCXXNewExpr(const CXXNewExpr *NE) {
+ // Only the standard non-allocating placement form, new (storage) T, takes
+ // the storage as its single placement argument.
+ if (NE->getNumPlacementArgs() != 1)
+ return true;
+ const Expr *Source = stripToStorageSource(NE->getPlacementArg(0));
+ QualType T = NE->getAllocatedType();
+ if (const auto *CE = dyn_cast<CallExpr>(Source))
+ record(CallTypes, CE, T);
+ else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
+ if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
+ record(VarTypes, VD, T);
+ return true;
+ }
+
+private:
+ template <typename Key>
+ static void record(llvm::DenseMap<Key, QualType> &Map, Key K, QualType T) {
+ auto [It, Inserted] = Map.try_emplace(K, T);
+ // Different types constructed into the same storage: ambiguous.
+ if (!Inserted && !It->second.isNull() &&
+ It->second.getCanonicalType() != T.getCanonicalType())
+ It->second = QualType();
+ }
+
+ llvm::DenseMap<const CallExpr *, QualType> &CallTypes;
+ llvm::DenseMap<const VarDecl *, QualType> &VarTypes;
+ llvm::DenseMap<const CallExpr *, const VarDecl *> &CallVars;
+};
+} // namespace
+
+void PlacementNewTypes::collect() {
+ Collected = true;
+ if (!Body)
+ return;
+ PlacementNewCollector Collector(CallTypes, VarTypes, CallVars);
+ Collector.TraverseStmt(const_cast<Stmt *>(Body));
+}
+
+QualType PlacementNewTypes::lookup(const CallExpr *E) {
+ if (!Collected)
+ collect();
+ if (auto It = CallTypes.find(E); It != CallTypes.end())
+ return It->second;
+ if (auto VarIt = CallVars.find(E); VarIt != CallVars.end())
+ if (auto It = VarTypes.find(VarIt->second); It != VarTypes.end())
+ return It->second;
+ return QualType();
+}
+
std::optional<llvm::AllocTokenMetadata>
infer_alloc::getAllocTokenMetadata(QualType T, const ASTContext &Ctx) {
llvm::AllocTokenMetadata ATMD;
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ae5f4e723f5129..33d6d1e4d45a4e 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,8 +1407,11 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
}
llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
- return buildAllocToken(
- infer_alloc::inferPossibleType(E, getContext(), CurCast));
+ if (!AllocTokenPlacementTypes)
+ AllocTokenPlacementTypes = std::make_unique<infer_alloc::PlacementNewTypes>(
+ CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
+ return buildAllocToken(infer_alloc::inferPossibleType(
+ E, getContext(), CurCast, AllocTokenPlacementTypes.get()));
}
void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 2c7820ec572253..d8545b86aae928 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -26,6 +26,7 @@
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExprOpenMP.h"
+#include "clang/AST/InferAlloc.h"
#include "clang/AST/StmtOpenACC.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/StmtSYCL.h"
@@ -375,6 +376,11 @@ class CodeGenFunction : public CodeGenTypeCache {
/// expression.
const CastExpr *CurCast = nullptr;
+ /// Placement-new types of the current function body, collected lazily for
+ /// -fsanitize=alloc-token type inference (see
+ /// infer_alloc::PlacementNewTypes).
+ std::unique_ptr<infer_alloc::PlacementNewTypes> AllocTokenPlacementTypes;
+
/// Save Parameter Decl for coroutine.
llvm::SmallVector<const ParmVarDecl *, 4> FnArgs;
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 98842206dfc000..0f2310bb9331c2 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -150,6 +150,112 @@ TestClass *test_new_class_array() {
return arr;
}
+struct PlacedNoPtr {
+ long len;
+ unsigned char tag;
+ char data[1];
+};
+
+struct PlacedWithPtr {
+ void *next;
+ long len;
+};
+
+// Allocation calls whose result is only named by a later placement new.
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z25test_placement_new_directv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR:![0-9]+]]
+PlacedNoPtr *test_placement_new_direct() {
+ return new (malloc(64)) PlacedNoPtr();
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z24test_placement_new_localv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR:![0-9]+]]
+PlacedWithPtr *test_placement_new_local() {
+ void *mem = malloc(64);
+ if (!mem)
+ return nullptr;
+ return new (mem) PlacedWithPtr();
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z30test_placement_new_sized_localv(
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_sized_local() {
+ __sized_ptr_t res = __size_returning_new(64);
+ PlacedNoPtr *rep = new (res.p) PlacedNoPtr();
+ rep->len = res.n;
+ return rep;
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z29test_placement_new_sized_castv(
+// CHECK: call { ptr, i64 } @__size_returning_new_hot_cold(i64 noundef 64, i8 noundef zeroext 1){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_sized_cast() {
+ auto res = __size_returning_new_hot_cold(64, __hot_cold_t{1});
+ return new (static_cast<char *>(res.p)) PlacedNoPtr();
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z24test_placement_new_arrayv(
+// CHECK: call noalias ptr @malloc(i64 noundef 640){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_array() {
+ void *mem = malloc(640);
+ return new (mem) PlacedNoPtr[10];
+}
+
+// A sizeof in the size argument or a cast of the result still takes precedence.
+// CHECK-LABEL: define dso_local noundef ptr @_Z34test_placement_new_sizeof_prevailsv(
+// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+PlacedNoPtr *test_placement_new_sizeof_prevails() {
+ void *mem = malloc(sizeof(PlacedWithPtr));
+ return new (mem) PlacedNoPtr();
+}
+
+// Storage constructed into with different types: no type is inferred.
+// CHECK-LABEL: define dso_local void @_Z28test_placement_new_ambiguousi(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_ambiguous(int which) {
+ void *mem = malloc(64);
+ if (which)
+ sink = new (mem) PlacedNoPtr();
+ else
+ sink = new (mem) PlacedWithPtr();
+}
+
+// Custom placement operators do not take the storage as placement argument, so
+// the malloc stays untyped (the custom operator new call itself is typed).
+struct Arena {};
+void *operator new(size_t, Arena &);
+// CHECK-LABEL: define dso_local void @_Z24test_placement_new_arenaR5Arena(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+// CHECK: call noundef ptr @_ZnwmR5Arena(i64 noundef 16, {{.*}} !alloc_token [[META_PLACEDNOPTR]]
+void test_placement_new_arena(Arena &arena) {
+ sink = malloc(64);
+ sink = new (arena) PlacedNoPtr();
+}
+
+template <typename T>
+T *placement_construct(size_t size) {
+ __sized_ptr_t res = __size_returning_new(size);
+ return new (res.p) T();
+}
+
+// CHECK-LABEL: define dso_local void @_Z27test_placement_new_templatev(
+// CHECK: call noundef ptr @_Z19placement_constructI11PlacedNoPtrEPT_m(
+// CHECK: call noundef ptr @_Z19placement_constructI13PlacedWithPtrEPT_m(
+void test_placement_new_template() {
+ sink = placement_construct<PlacedNoPtr>(64);
+ sink = placement_construct<PlacedWithPtr>(64);
+}
+
+// CHECK-LABEL: define linkonce_odr noundef ptr @_Z19placement_constructI11PlacedNoPtrEPT_m(
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef {{.*}}){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+// CHECK-LABEL: define linkonce_odr noundef ptr @_Z19placement_constructI13PlacedWithPtrEPT_m(
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef {{.*}}){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+
// CHECK: [[META_INT]] = !{!"int", i1 false}
// CHECK: [[META_LONG]] = !{!"long", i1 false}
// CHECK: [[META_TESTCLASS]] = !{!"TestClass", i1 true}
+// CHECK: [[META_PLACEDNOPTR]] = !{!"PlacedNoPtr", i1 false}
+// CHECK: [[META_PLACEDWITHPTR]] = !{!"PlacedWithPtr", i1 true}
>From 294e6290e76f4fdaff42668c7c69ecce6fab732b Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 14:46:40 -0800
Subject: [PATCH 2/2] Address review: stop at -> and unmatched &/*, require
reserved placement operator new
- Only look through non-arrow member accesses of a by-value result and
cancelling &*/*& pairs; indirect accesses and unmatched operators stop.
- Require the resolved operator new to be the reserved global placement
form, as EmitCXXNewExpr does.
- Add regression tests and document the limits.
---
clang/docs/AllocToken.md | 6 +++-
clang/lib/AST/InferAlloc.cpp | 27 +++++++++++-----
clang/test/CodeGenCXX/alloc-token.cpp | 44 +++++++++++++++++++++++++++
3 files changed, 69 insertions(+), 8 deletions(-)
diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index 6e6c9d4c84327a..1641f026e24d6c 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -78,7 +78,11 @@ allocation call and its surroundings, in this order:
```
If different types are constructed into the same storage, no type is
- inferred.
+ inferred. Only the reserved non-allocating placement form
+ `::operator new(size_t, void *)` is considered; user-provided placement
+ operators may construct elsewhere. Likewise, indirect member accesses
+ (`h->p`) and unmatched `&`/`*` name storage other than the allocation and
+ are not looked through.
These are heuristics: they ignore control flow and reassignments of the
variables involved. If no type can be inferred, the allocation receives the
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 5f665d7bee115d..36425c4062ee1a 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -193,19 +193,28 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
namespace {
/// Strips the wrappers a placement argument may have around the expression
-/// that produced the storage: parentheses, casts, member accesses (e.g. the
-/// pointer member of a size-returning allocation result), and
-/// address-of/dereference pairs.
+/// that produced the storage: parentheses, casts, direct (non-arrow) member
+/// accesses of a by-value result (e.g. the pointer member of a size-returning
+/// allocation result), and cancelling `&*` / `*&` pairs. Anything that follows
+/// a pointer into different storage (`->`, an unmatched dereference) or takes
+/// the address of a different object (an unmatched address-of) stops the walk.
const Expr *stripToStorageSource(const Expr *E) {
while (true) {
E = E->IgnoreParenCasts();
if (const auto *ME = dyn_cast<MemberExpr>(E)) {
+ if (ME->isArrow())
+ return E;
E = ME->getBase();
continue;
}
if (const auto *UO = dyn_cast<UnaryOperator>(E);
UO && (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref)) {
- E = UO->getSubExpr();
+ const auto *Inner =
+ dyn_cast<UnaryOperator>(UO->getSubExpr()->IgnoreParens());
+ if (!Inner || Inner->getOpcode() == UO->getOpcode() ||
+ (Inner->getOpcode() != UO_AddrOf && Inner->getOpcode() != UO_Deref))
+ return E;
+ E = Inner->getSubExpr();
continue;
}
return E;
@@ -257,9 +266,13 @@ class PlacementNewCollector
}
bool VisitCXXNewExpr(const CXXNewExpr *NE) {
- // Only the standard non-allocating placement form, new (storage) T, takes
- // the storage as its single placement argument.
- if (NE->getNumPlacementArgs() != 1)
+ // Only the reserved non-allocating placement form, new (storage) T, is
+ // guaranteed to construct into its single placement argument. A
+ // class-specific or otherwise user-provided operator new(size_t, void *)
+ // may treat the argument as allocator state and return other storage.
+ const FunctionDecl *OperatorNew = NE->getOperatorNew();
+ if (NE->getNumPlacementArgs() != 1 || !OperatorNew ||
+ !OperatorNew->isReservedGlobalPlacementOperator())
return true;
const Expr *Source = stripToStorageSource(NE->getPlacementArg(0));
QualType T = NE->getAllocatedType();
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 0f2310bb9331c2..39d19833c89ced 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -235,6 +235,49 @@ void test_placement_new_arena(Arena &arena) {
sink = new (arena) PlacedNoPtr();
}
+// A class-specific operator new(size_t, void *) may use its argument as
+// allocator state rather than as the storage, so the allocation feeding it
+// stays untyped.
+struct ClassPlacement {
+ void *next;
+ static void *operator new(size_t, void *ctx);
+};
+// CHECK-LABEL: define dso_local void @_Z33test_placement_new_class_specificv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+// CHECK: call noundef ptr @_ZN14ClassPlacementnwEmPv(i64 noundef 8, {{.*}} !alloc_token [[META_CLASSPLACEMENT:![0-9]+]]
+void test_placement_new_class_specific() {
+ void *ctx = malloc(64);
+ sink = new (ctx) ClassPlacement;
+}
+
+// Indirect member access and an unmatched address-of name storage other than
+// the allocation itself.
+struct Holder {
+ void *p;
+};
+Holder *alloc_holder(size_t) __attribute__((malloc));
+// CHECK-LABEL: define dso_local void @_Z27test_placement_new_indirectv(
+// CHECK: call noalias noundef ptr @_Z12alloc_holderm(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_indirect() {
+ Holder *h = alloc_holder(64);
+ sink = new (h->p) PlacedNoPtr();
+ void *mem = malloc(64);
+ sink = new (&mem) unsigned char(0);
+}
+
+// Cancelling address-of/dereference pairs are still looked through.
+// CHECK-LABEL: define dso_local noundef ptr @_Z29test_placement_new_deref_addrv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_deref_addr() {
+ void *mem = malloc(64);
+ return new (*&mem) PlacedNoPtr();
+}
+
template <typename T>
T *placement_construct(size_t size) {
__sized_ptr_t res = __size_returning_new(size);
@@ -259,3 +302,4 @@ void test_placement_new_template() {
// CHECK: [[META_TESTCLASS]] = !{!"TestClass", i1 true}
// CHECK: [[META_PLACEDNOPTR]] = !{!"PlacedNoPtr", i1 false}
// CHECK: [[META_PLACEDWITHPTR]] = !{!"PlacedWithPtr", i1 true}
+// CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}
More information about the cfe-commits
mailing list