Skip to content

[LangRef] Clarify invariant.group semantics - #224222

Open
nikic wants to merge 1 commit into
llvm:mainfrom
nikic:invariant-group-docs
Open

nikic wants to merge 1 commit into
llvm:mainfrom
nikic:invariant-group-docs

Conversation

@nikic

@nikic nikic commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

LangRef for !invariant.group currently says that it is based on the SSA value identity, with some exceptions like bitcasts and zero-offset GEPs. This results in incoherent semantics: Under a strict reading, it means that eliminating no-op operations on pointers (like phis, selects, or geps that cancel out) is illegal, because it would change SSA value identity for !invariant.group. Generally, reasoning based on SSA value identity is only possible for token types.

Instead, we basically specify that the pointers need to have the same provenance, with the caveat that we only care about provenance changes due to strip.invariant and launder.invariant. (Otherwise we'd again run into trouble when dropping provenance-restricting operations, e.g. as a result of inlining.)

Some things worth noting here:

  • I specified that writing back the same value is allowed. I don't know whether we actually use that ability anywhere, but there was an example that implied it is valid, so I went with it.
  • I clarified that only the memory accessed by the initial !invariant.group access is covered. From a cursory look, it seems like neither findReachingValuesForLoad() in GVN nor getInvariantGroupClobberingInstruction() in MSSA actually reason about the access size -- I haven't checked whether this can result in practical miscompiles (it's possible this is a latent issue because a smaller clobbering access is typically not useful for anything).
  • I dropped the part at the end about replacing pointers. At this point, we know that it's generally invalid to replace pointers with different provenance based on equality, not just for invariant.group. However, it seems like we don't property implement handling for this where invariant.group stripping is concerned. I've put up [Loads] Fix incorrect replacement of pointers with different provenance #224281 to fix this.

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-llvm-ir

Author: Nikita Popov (nikic)

Changes

LangRef for !invariant.group currently says that it is based on the SSA value identity, with some exceptions like bitcasts and zero-offset GEPs. This results in incoherent semantics: Under a strict reading, it means that eliminating no-op operations on pointers (like phis, selects, or geps that cancel out) is illegal, because it would change SSA value identity for !invariant.group. Generally, reasoning based on SSA value identity is only possible for token types.

Instead, we basically specify that the pointers need to have the same provenance, with the caveat that we only care about provenance changes due to strip.invariant and launder.invariant. (Otherwise we'd again run into trouble when dropping provenance-restricting operations, e.g. as a result of inlining.)

Some things worth noting here:

  • I specified that writing back the same value is allowed. I don't know whether we actually use that ability anywhere, but there was an example that implied it is valid, so I went with it.
  • I clarified that only the memory accessed by the initial !invariant.group access is covered. From a cursory look, it seems like neither findReachingValuesForLoad() in GVN nor getInvariantGroupClobberingInstruction() in MSSA actually reason about the access size -- I haven't checked whether this can result in practical miscompiles (it's possible this is a latent issue because a smaller clobbering access is typically not useful for anything).
  • I dropped the part at the end about replacing pointers. At this point, we know that it's generally invalid to replace pointers with different provenance based on equality, not just for invariant.group. However, it seems like we don't property implement handling for this where invariant.group stripping is concerned: https://llvm.godbolt.org/z/Txf3386z3 This is because getUnderlyingObject() looks through these intrinsic. That's correct in most cases, but not when we want to check for same provenance when replacing pointers.

Full diff: https://github.com/llvm/llvm-project/pull/224222.diff

1 Files Affected:

  • (modified) llvm/docs/LangRef.md (+38-23)
diff --git a/llvm/docs/LangRef.md b/llvm/docs/LangRef.md
index 27e20fde8dc5f..5656b119461a4 100644
--- a/llvm/docs/LangRef.md
+++ b/llvm/docs/LangRef.md
@@ -8704,11 +8704,18 @@ call i32 @llvm.read_register.i32(metadata !1), !invariant.load !0
 The experimental `invariant.group` metadata may be attached to
 `load`/`store` instructions referencing a single metadata with no entries.
 The existence of the `invariant.group` metadata on the instruction tells
-the optimizer that every `load` and `store` to the same pointer operand
-can be assumed to load or store the same
-value (but see the `llvm.launder.invariant.group` intrinsic which affects
-when two pointers are considered the same). Pointers returned by bitcast or
-getelementptr with only zero indices are considered the same.
+the optimizer that every `load` and `store` to the "same" pointer operand
+can be assumed to load or store the same value.
+
+More precisely, if memory is accessed through a pointer `%p` using an
+instruction with `!invariant.group` metadata, then, if the same memory (or
+parts of it) are later modified through a pointer that is *invariant-compatible*
+with `%p`, the behavior is undefined. Two pointers are *invariant-compatible*
+if they are *based-on* a common pointer, such that no
+`llvm.strip.invariant.group` or `llvm.launder.invariant.group` intrinsic needs
+to be passed to reach it. For the purposes of `!invariant.group`, writing back
+the same value that is already stored in the location does not count as a
+modification.
 
 Note that the metadata value in invariant.group carries no semantic value.
 Because it must have no entries, all invariant.group annotations in a module
@@ -8717,24 +8724,42 @@ reference the same uniqued empty node.
 Examples:
 
 ```llvm
-@unknownPtr = external global i8
+@unknownPtr = external global i32
 ...
-%ptr = alloca i8
-store i8 42, ptr %ptr, !invariant.group !0
+%ptr = alloca i32
+store i32 42, ptr %ptr, !invariant.group !0
 call void @foo(ptr %ptr)
 
-%a = load i8, ptr %ptr, !invariant.group !0 ; Can assume that value under %ptr didn't change
+; Can assume that value under %ptr didn't change
+%a = load i32, ptr %ptr, !invariant.group !0
+call void @foo(ptr %ptr)
+
+; Can still assume that value under %ptr didn't change.
+; Having !invariant.group on the later load is not required for the invariance
+; property to be used, though it may be used as an optimization heuristic to
+; determine whether finding a dominating !invariant.group access is worthwhile.
+%b = load i32, ptr %ptr
+call void @foo(ptr %ptr)
+
+; Can still assume that the accessed sub-bytes did not change.
+%ptr.plus.2 = getelementptr i8, ptr %ptr, i64 2
+%c = load i16, ptr %ptr.plus.2
+call void @foo(ptr %ptr)
+
+; Can not assume that the entire value did not change, because more memory is
+; loaded than the original !invariant.group access stored.
+%x = load i64, ptr %ptr
 call void @foo(ptr %ptr)
 
 %newPtr = call ptr @getPointer(ptr %ptr)
-%c = load i8, ptr %newPtr, !invariant.group !0 ; Can't assume anything, because we only have information about %ptr
+%c = load i32, ptr %newPtr, !invariant.group !0 ; Can't assume anything, because we only have information about %ptr
 
-%unknownValue = load i8, ptr @unknownPtr
-store i8 %unknownValue, ptr %ptr, !invariant.group !0 ; Can assume that %unknownValue == 42
+%unknownValue = load i32, ptr @unknownPtr
+store i32 %unknownValue, ptr %ptr, !invariant.group !0 ; Can assume that %unknownValue == 42
 
 call void @foo(ptr %ptr)
 %newPtr2 = call ptr @llvm.launder.invariant.group.p0(ptr %ptr)
-%d = load i8, ptr %newPtr2, !invariant.group !0  ; Can't step through launder.invariant.group to get value of %ptr
+%d = load i32, ptr %newPtr2, !invariant.group !0  ; Can't step through launder.invariant.group to get value of %ptr
 
 ...
 declare void @foo(ptr)
@@ -8744,16 +8769,6 @@ declare ptr @llvm.launder.invariant.group.p0(ptr)
 !0 = !{}
 ```
 
-The `invariant.group` metadata must be dropped when replacing one pointer by
-another based on aliasing information. This is because `invariant.group` is tied
-to the SSA value of the pointer operand.
-
-```llvm
-%v = load i8, ptr %x, !invariant.group !0
-; if %x mustalias %y then we can replace the above instruction with
-%v = load i8, ptr %y
-```
-
 Note that this is an experimental feature, which means that its semantics might
 change in the future.
 

Comment thread llvm/docs/LangRef.md
; Can still assume that value under %ptr didn't change.
; Having !invariant.group on the later load is not required for the invariance
; property to be used, though it may be used as an optimization heuristic to
; determine whether finding a dominating !invariant.group access is worthwhile.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a possible alternative semantics here where we only have UB if a later !invariant.group access observes/writes a different value to the memory. That would make something like

store i32 0, ptr %p, !invariant.group !0
store i32 1, ptr %p

well-defined, and

store i32 0, ptr %p, !invariant.group !0
store i32 1, ptr %p
load i32, ptr %p, !invariant.group !0

undefined behavior.

I believe those semantics would be sufficient for current invariant.group based optimizations as well. I'm not sure if one of them is better than the other. I guess the advantage of this version is that only accesses with !invariant.group need to be checked by llubi.

Comment thread llvm/docs/LangRef.md

More precisely, if memory is accessed through a pointer `%p` using an
instruction with `!invariant.group` metadata, then, if the same memory (or
parts of it) are later modified through a pointer that is *invariant-compatible*

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

don't we also need to forbid other pointers from modifying the same memory? or else we wouldn't be able to forward a previous invariant.group store to a later invariant.group load with arbitrary code in between

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer the semantics in https://github.com/llvm/llvm-project/pull/224222/files#r4034463328. Then we only care about the observed value of memory accesses with !invariant.group.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pseudocode for llubi:

struct provenance {
  map<offset, value> invariant; // or a flatten byte buffer
};

visitLoad(p) {
    prov = p->provenance;
    v = load(prov, p->offset)
    if (v2 = prov->invariant.get(p->offset)) {
       if (v != v2) ub();
   }
    if (!prov->invariant.empty() || LI.has_invariant_group())
       prov->invariant.set(p->offset, v);
   return v;
}

visitStore(p, v) {
    prov = p->provenance;
    if (v2 = prov->invariant.get(p->offset)) {
       if (v != v2) ub();
   }
   if (!prov->invariant.empty() || SI.has_invariant_group())
      prov->invariant.set(p->offset, v);
    store(prov, p->offset, v);
}

visitLaunderInvariantGroup(p) {
  new_prov = p->provenance->clone();
  new_prov->invariant.clear();
  return p->withNewProvenance(new_prov);
} 

Correct me if I missed any UB.

nikic added a commit that referenced this pull request Sep 18, 2026
…ce (#224281)

isPointerAlwaysReplaceable() uses getUnderlyingObject() to check whether
the two pointers have the same provenance, because in that case the
replacement is always legal. However, getUnderlyingObject() does not
actually guarantee that the provenance is the same: In particular, it
can look through some intrinsics like strip.invariant.group and
launder.invariant.group, which do change the provenance of the pointer.
And replacing the result of those intrinsics with their argument is
indeed incorrect.

Fix this by adding a MustPreserveProvenance argument to the relevant
APIs, and enable it in isPointerAlwaysReplaceable().

Noticed while working on
#224222.
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Sep 18, 2026
…nt provenance (#224281)

isPointerAlwaysReplaceable() uses getUnderlyingObject() to check whether
the two pointers have the same provenance, because in that case the
replacement is always legal. However, getUnderlyingObject() does not
actually guarantee that the provenance is the same: In particular, it
can look through some intrinsics like strip.invariant.group and
launder.invariant.group, which do change the provenance of the pointer.
And replacing the result of those intrinsics with their argument is
indeed incorrect.

Fix this by adding a MustPreserveProvenance argument to the relevant
APIs, and enable it in isPointerAlwaysReplaceable().

Noticed while working on
llvm/llvm-project#224222.
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Sep 18, 2026
…nt provenance (#224281)

isPointerAlwaysReplaceable() uses getUnderlyingObject() to check whether
the two pointers have the same provenance, because in that case the
replacement is always legal. However, getUnderlyingObject() does not
actually guarantee that the provenance is the same: In particular, it
can look through some intrinsics like strip.invariant.group and
launder.invariant.group, which do change the provenance of the pointer.
And replacing the result of those intrinsics with their argument is
indeed incorrect.

Fix this by adding a MustPreserveProvenance argument to the relevant
APIs, and enable it in isPointerAlwaysReplaceable().

Noticed while working on
llvm/llvm-project#224222.
nekoshirro pushed a commit to nekoshirro/Alchemist-LLVM that referenced this pull request Sep 20, 2026
…ce (#224281)

isPointerAlwaysReplaceable() uses getUnderlyingObject() to check whether
the two pointers have the same provenance, because in that case the
replacement is always legal. However, getUnderlyingObject() does not
actually guarantee that the provenance is the same: In particular, it
can look through some intrinsics like strip.invariant.group and
launder.invariant.group, which do change the provenance of the pointer.
And replacing the result of those intrinsics with their argument is
indeed incorrect.

Fix this by adding a MustPreserveProvenance argument to the relevant
APIs, and enable it in isPointerAlwaysReplaceable().

Noticed while working on
llvm/llvm-project#224222.
Signed-off-by: Hafidz Muzakky <[email protected]>
Comment thread llvm/docs/LangRef.md
parts of it) are later modified through a pointer that is *invariant-compatible*
with `%p`, the behavior is undefined. Two pointers are *invariant-compatible*
if they are *based-on* a common pointer, such that no
`llvm.strip.invariant.group` or `llvm.launder.invariant.group` intrinsic needs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

llvm.strip.invariant.group is dropped.

@antoniofrighetto antoniofrighetto left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Comment thread llvm/docs/LangRef.md
instruction with `!invariant.group` metadata, then, if the same memory (or
parts of it) are later modified through a pointer that is *invariant-compatible*
with `%p`, the behavior is undefined. Two pointers are *invariant-compatible*
if they are *based-on* a common pointer, such that no

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess your earlier wording (which I particularly liked) may not be used here, as we would be assuming provenance forming a tree (which hasn't been formalized yet)...

Comment thread llvm/docs/LangRef.md

%newPtr = call ptr @getPointer(ptr %ptr)
%c = load i8, ptr %newPtr, !invariant.group !0 ; Can't assume anything, because we only have information about %ptr
%c = load i32, ptr %newPtr, !invariant.group !0 ; Can't assume anything, because we only have information about %ptr

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: %d as %c already defined?

Comment thread llvm/docs/LangRef.md

; Can not assume that the entire value did not change, because more memory is
; loaded than the original !invariant.group access stored.
%x = load i64, ptr %ptr

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: maybe make the alloca i64 (as the load itself would otherwise be UB)?

@aeubanks aeubanks left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the proposed alternative seems more in line with what the intrinsic is meant to do

@YonahGoldberg

Copy link
Copy Markdown
Contributor

@nikic FYI I believe #212472 and the corresponding fix for this issue is wrong under these clarified semantics and is now unnecessarily dropping !invariant.group. In the reproducer the rewritten store is storing a subset of the bytes of the original store with !invariant.group. Under these provenance based semantics I think this is legal, but @ParkHanbum read the LangRef literally like I did.

I think now that we have so many people checking correctness of their PRs with AI, it's becoming increasingly important to make the LangRef well-specified so AI doesn't keep flagging down correctness issues incorrectly.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants