llvm / llvm/llvm-project

[InstCombine] How to eliminate the unnecessary masking instruction in common loops?

Open
#177,318 2 comments 0 reactions 1 assignee Claimed by @sreedivyakottilingal View on GitHub
llvm:instcombine
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

When **the IV's initial value is a variable and its end value is a constant**, this causes an unnecessary masking instruction.

```c
void func(int start, int a[100]){
for (int i = start; i < 56; i++){
a[i] += 1;
}
}
```

The corresponding IR is

```c++
define dso_local void @func(i32 noundef %0, ptr noundef captures(none) %1) local_unnamed_addr #0 {
%3 = icmp slt i32 %0, 56
br i1 %3, label %4, label %6

4: ; preds = %2
%5 = sext i32 %0 to i64
br label %7

6: ; preds = %7, %2
ret void

7: ; preds = %4, %7
%8 = phi i64 [ %5, %4 ], [ %12, %7 ]
%9 = getelementptr inbounds i32, ptr %1, i64 %8
%10 = load i32, ptr %9, align 4, !tbaa !5
%11 = add nsw i32 %10, 1
store i32 %11, ptr %9, align 4, !tbaa !5
%12 = add nsw i64 %8, 1
%13 = and i64 %12, 4294967295
%14 = icmp eq i64 %13, 56
br i1 %14, label %6, label %7, !llvm.loop !9
}
```

Currently, I understand that `IndVarSimplifyPass:linearFunctionTestReplace()` generates a trunc instruction when optimizing the loop exit condition, and that `InstCombinePass::foldICmpTruncConstant()` emits this masking instruction when folding "icmp (trunc X), C".

What should be done to reasonably eliminate this unnecessary masking instruction? Thanks!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.