llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[LoopPeel] Cloned llvm.assume calls are not registered in the AssumptionCache

Open fraglantia opened this issue 1 week ago • 1 comments

peelLoop clones the loop body, including any llvm.assume, but does not register the clones with the AssumptionCache it is given. The clones are remapped at LoopPeel.cpp:1323 on main, and nothing registers them.

The cache requires this: "Passes that create new assumptions are required to call registerAssumption()" (AssumptionCache.h:41-43).

UnrollLoop registers its copies (LoopUnroll.cpp:1341-1345), and so does UnrollAndJamLoop (LoopUnrollAndJam.cpp:430-434).

After peeling, the cache is incomplete, and every later pass in the same pipeline gets the incomplete cache. The cache is never invalidated (AssumptionCache.h:119), so it stays this way until the function analyses are cleared.

test.ll

target triple = "x86_64-unknown-linux-gnu"

; %prev is %init on the first iteration and %k afterwards, so loop-unroll-full peels one iteration.
define void @f(ptr %a, i64 %n, i32 %init, i32 %k) {
entry:
  br label %loop

loop:
  %i = phi i64 [ 0, %entry ], [ %i.next, %loop ]
  %prev = phi i32 [ %init, %entry ], [ %k, %loop ]
  %c = icmp ult i32 %prev, 100
  call void @llvm.assume(i1 %c)
  %p = getelementptr inbounds i32, ptr %a, i64 %i
  store i32 %prev, ptr %p, align 4
  %i.next = add nuw nsw i64 %i, 1
  %more = icmp ult i64 %i.next, %n
  br i1 %more, label %loop, label %exit

exit:
  ret void
}

declare void @llvm.assume(i1)

In the same pipeline, the cache has only the original assumption:

opt -passes='function(require<assumptions>,loop(loop-unroll-full),print<assumptions>)' -disable-output test.ll
Cached assumptions for function: f
    %c = icmp ult i32 %k, 100

The same peeled IR in a new process has both:

opt -passes='loop(loop-unroll-full)' test.ll | opt -passes='print<assumptions>' -disable-output
Cached assumptions for function: f
    %c.peel = icmp ult i32 %init, 100
    %c = icmp ult i32 %k, 100

fraglantia avatar Nov 24 '26 04:11 fraglantia

Fix. Register the clones as UnrollLoop does. With this change, the first command should also print %c.peel:

     remapInstructionsInBlocks(NewBlocks, VMap);
+
+    // Register the cloned assumptions, as UnrollLoop does for its copies.
+    if (AC)
+      for (BasicBlock *BB : NewBlocks)
+        for (Instruction &I : *BB)
+          if (auto *II = dyn_cast<AssumeInst>(&I))
+            AC->registerAssumption(II);

Drafting this fix.

fraglantia avatar Nov 24 '26 04:11 fraglantia