Skip to content

Commit 5602636

Browse files
authored
[LoopPeel] Peel iterations based on and, or conditions (llvm#73413)
For example, this allows us to peel this loop with a `and`: ``` for (int i = 0; i < N; ++i) { if (i % 2 == 0 && i < 3) // can peel based on || as well f1(); f2(); ``` into: ``` for (int i = 0; i < 3; ++i) { // peel three iterations if (i % 2 == 0) f1(); f2(); } for (int i = 3; i < N; ++i) f2(); ```
1 parent 0008b9c commit 5602636

File tree

2 files changed

+472
-31
lines changed

2 files changed

+472
-31
lines changed

llvm/lib/Transforms/Utils/LoopPeel.cpp

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -351,11 +351,20 @@ static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
351351
MaxPeelCount =
352352
std::min((unsigned)SC->getAPInt().getLimitedValue() - 1, MaxPeelCount);
353353

354-
auto ComputePeelCount = [&](Value *Condition) -> void {
355-
if (!Condition->getType()->isIntegerTy())
354+
const unsigned MaxDepth = 4;
355+
std::function<void(Value *, unsigned)> ComputePeelCount =
356+
[&](Value *Condition, unsigned Depth) -> void {
357+
if (!Condition->getType()->isIntegerTy() || Depth >= MaxDepth)
356358
return;
357359

358360
Value *LeftVal, *RightVal;
361+
if (match(Condition, m_And(m_Value(LeftVal), m_Value(RightVal))) ||
362+
match(Condition, m_Or(m_Value(LeftVal), m_Value(RightVal)))) {
363+
ComputePeelCount(LeftVal, Depth + 1);
364+
ComputePeelCount(RightVal, Depth + 1);
365+
return;
366+
}
367+
359368
CmpInst::Predicate Pred;
360369
if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal))))
361370
return;
@@ -443,7 +452,7 @@ static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
443452
for (BasicBlock *BB : L.blocks()) {
444453
for (Instruction &I : *BB) {
445454
if (SelectInst *SI = dyn_cast<SelectInst>(&I))
446-
ComputePeelCount(SI->getCondition());
455+
ComputePeelCount(SI->getCondition(), 0);
447456
}
448457

449458
auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
@@ -454,7 +463,7 @@ static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount,
454463
if (L.getLoopLatch() == BB)
455464
continue;
456465

457-
ComputePeelCount(BI->getCondition());
466+
ComputePeelCount(BI->getCondition(), 0);
458467
}
459468

460469
return DesiredPeelCount;

0 commit comments

Comments
 (0)