[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 18:02:06 PST 2026
david-xl wrote:
> If I understand correctly, this is just finding any pair of malloc/new that refers to a given variable, and assuming they're related? So, for example,
>
> ```
> void *p = malloc(8);
> free(p);
> p = malloc(8);
> new (p) long(10);
> ```
>
> The first malloc gets the token, the second one doesn't?
>
> The whole approach feels really weird, but it might be hard to do better, I guess.
Agreed -- this is the weakness of syntatic pattern based type inference heursitics. I've replaced the "variable → initializer" link with a poor man's lexical def-use chain (6af1d9c): new (p) T resolves to the nearest preceding definition of p — initializer or p = <call> — provided that definition lexically dominates the use (same control-flow context or an enclosing one) and no later definition can reach it around a loop. Definitions in non-dominating branches, later definitions inside a loop containing the use, and other writes (+=, ++, &p) make the use ambiguous, and nothing is inferred for it.
Your example now gives: first malloc untyped (falls back to the existing sizeof/cast heuristics, which find nothing), second malloc long; it's in test_placement_new_reassign, with the branch/loop/address-taken cases in test_placement_new_ambiguous2.
It is still syntactic — not a CFG-based reaching-definitions analysis — so it is conservative on anything branchy, but it no longer attributes a type to an allocation that doesn't flow into the placement new. If more coverage turns out to matter, a real reaching-definitions pass over the Clang CFG would be the follow-up.
https://github.com/llvm/llvm-project/pull/241548
More information about the cfe-commits
mailing list