Skip to content

Commit dfde077

Browse files
authored
[SimplifyCFG] More accurate use legality check for sinking (#94462)
When sinking instructions, we have to make sure that the uses of that instruction are consistent: If used in a phi node in the sink target, then the phi operands have to match the sink candidates. This allows the phi to be removed when the instruction is sunk. This case is already handled accurately. However, what the current code doesn't handle are uses in the same block. These are just unconditionally accepted, even though this needs the same consistency check for the phi node that sinking the using instruction would introduce. Instead, the code has another check when actually performing the sinking, which repeats the phi check (just at a later time, where all the later instructions have already been sunk and any new phis introduced). This is problematic, because it messes up the profitability heuristic. The code will think that certain instructions will get sunk, but they actually won't. This may result in more phi nodes being created than is considered profitable. See the changed test for a case where we no longer do this after this patch. The new approach makes sure that the uses are consistent during the initial legality check. This is based on PhiOperands, which we already collect. The primary motivation for this is to generalize sinking to support more than one use, and doing that generalization is hard with the current split checking approach.
1 parent da249ca commit dfde077

File tree

2 files changed

+40
-54
lines changed

2 files changed

+40
-54
lines changed

llvm/lib/Transforms/Utils/SimplifyCFG.cpp

Lines changed: 36 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,7 +1932,7 @@ static bool replacingOperandWithVariableIsCheap(const Instruction *I,
19321932
// PHI node (because an operand varies in each input block), add to PHIOperands.
19331933
static bool canSinkInstructions(
19341934
ArrayRef<Instruction *> Insts,
1935-
DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
1935+
DenseMap<const Use *, SmallVector<Value *, 4>> &PHIOperands) {
19361936
// Prune out obviously bad instructions to move. Each instruction must have
19371937
// exactly zero or one use, and we check later that use is by a single, common
19381938
// PHI instruction in the successor.
@@ -1983,20 +1983,17 @@ static bool canSinkInstructions(
19831983
return false;
19841984
}
19851985

1986-
// All instructions in Insts are known to be the same opcode. If they have a
1987-
// use, check that the only user is a PHI or in the same block as the
1988-
// instruction, because if a user is in the same block as an instruction we're
1989-
// contemplating sinking, it must already be determined to be sinkable.
1986+
// Uses must be consistent: If I0 is used in a phi node in the sink target,
1987+
// then the other phi operands must match the instructions from Insts. This
1988+
// also has to hold true for any phi nodes that would be created as a result
1989+
// of sinking. Both of these cases are represented by PhiOperands.
19901990
if (HasUse) {
1991-
auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1992-
auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1993-
if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
1994-
auto *U = cast<Instruction>(*I->user_begin());
1995-
return (PNUse &&
1996-
PNUse->getParent() == Succ &&
1997-
PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1998-
U->getParent() == I->getParent();
1999-
}))
1991+
const Use &U = *I0->use_begin();
1992+
auto It = PHIOperands.find(&U);
1993+
if (It == PHIOperands.end())
1994+
// There may be uses in other blocks when sinking into a loop header.
1995+
return false;
1996+
if (!equal(Insts, It->second))
20001997
return false;
20011998
}
20021999

@@ -2063,8 +2060,9 @@ static bool canSinkInstructions(
20632060
!canReplaceOperandWithVariable(I0, OI))
20642061
// We can't create a PHI from this GEP.
20652062
return false;
2063+
auto &Ops = PHIOperands[&I0->getOperandUse(OI)];
20662064
for (auto *I : Insts)
2067-
PHIOperands[I].push_back(I->getOperand(OI));
2065+
Ops.push_back(I->getOperand(OI));
20682066
}
20692067
}
20702068
return true;
@@ -2073,7 +2071,7 @@ static bool canSinkInstructions(
20732071
// Assuming canSinkInstructions(Blocks) has returned true, sink the last
20742072
// instruction of every block in Blocks to their common successor, commoning
20752073
// into one instruction.
2076-
static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
2074+
static void sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
20772075
auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
20782076

20792077
// canSinkInstructions returning true guarantees that every block has at
@@ -2088,23 +2086,10 @@ static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
20882086
Insts.push_back(I);
20892087
}
20902088

2091-
// The only checking we need to do now is that all users of all instructions
2092-
// are the same PHI node. canSinkInstructions should have checked this but
2093-
// it is slightly over-aggressive - it gets confused by commutative
2094-
// instructions so double-check it here.
2095-
Instruction *I0 = Insts.front();
2096-
if (!I0->user_empty()) {
2097-
auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
2098-
if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
2099-
auto *U = cast<Instruction>(*I->user_begin());
2100-
return U == PNUse;
2101-
}))
2102-
return false;
2103-
}
2104-
21052089
// We don't need to do any more checking here; canSinkInstructions should
21062090
// have done it all for us.
21072091
SmallVector<Value*, 4> NewOperands;
2092+
Instruction *I0 = Insts.front();
21082093
for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
21092094
// This check is different to that in canSinkInstructions. There, we
21102095
// cared about the global view once simplifycfg (and instcombine) have
@@ -2172,8 +2157,6 @@ static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
21722157
I->replaceAllUsesWith(I0);
21732158
I->eraseFromParent();
21742159
}
2175-
2176-
return true;
21772160
}
21782161

21792162
namespace {
@@ -2314,9 +2297,19 @@ static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
23142297
// carry on. If we can sink an instruction but need to PHI-merge some operands
23152298
// (because they're not identical in each instruction) we add these to
23162299
// PHIOperands.
2300+
// We prepopulate PHIOperands with the phis that already exist in BB.
2301+
DenseMap<const Use *, SmallVector<Value *, 4>> PHIOperands;
2302+
for (PHINode &PN : BB->phis()) {
2303+
SmallDenseMap<BasicBlock *, const Use *, 4> IncomingVals;
2304+
for (const Use &U : PN.incoming_values())
2305+
IncomingVals.insert({PN.getIncomingBlock(U), &U});
2306+
auto &Ops = PHIOperands[IncomingVals[UnconditionalPreds[0]]];
2307+
for (BasicBlock *Pred : UnconditionalPreds)
2308+
Ops.push_back(*IncomingVals[Pred]);
2309+
}
2310+
23172311
int ScanIdx = 0;
23182312
SmallPtrSet<Value*,4> InstructionsToSink;
2319-
DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
23202313
LockstepReverseIterator LRI(UnconditionalPreds);
23212314
while (LRI.isValid() &&
23222315
canSinkInstructions(*LRI, PHIOperands)) {
@@ -2338,20 +2331,19 @@ static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
23382331
// actually sink before encountering instruction that is unprofitable to
23392332
// sink?
23402333
auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
2341-
unsigned NumPHIdValues = 0;
2342-
for (auto *I : *LRI)
2343-
for (auto *V : PHIOperands[I]) {
2344-
if (!InstructionsToSink.contains(V))
2345-
++NumPHIdValues;
2334+
unsigned NumPHIInsts = 0;
2335+
for (Use &U : (*LRI)[0]->operands()) {
2336+
auto It = PHIOperands.find(&U);
2337+
if (It != PHIOperands.end() && !all_of(It->second, [&](Value *V) {
2338+
return InstructionsToSink.contains(V);
2339+
})) {
2340+
++NumPHIInsts;
23462341
// FIXME: this check is overly optimistic. We may end up not sinking
23472342
// said instruction, due to the very same profitability check.
23482343
// See @creating_too_many_phis in sink-common-code.ll.
23492344
}
2350-
LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
2351-
unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
2352-
if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
2353-
NumPHIInsts++;
2354-
2345+
}
2346+
LLVM_DEBUG(dbgs() << "SINK: #phi insts: " << NumPHIInsts << "\n");
23552347
return NumPHIInsts <= 1;
23562348
};
23572349

@@ -2476,13 +2468,7 @@ static bool SinkCommonCodeFromPredecessors(BasicBlock *BB,
24762468
// sink is always at index 0.
24772469
LRI.reset();
24782470

2479-
if (!sinkLastInstruction(UnconditionalPreds)) {
2480-
LLVM_DEBUG(
2481-
dbgs()
2482-
<< "SINK: stopping here, failed to actually sink instruction!\n");
2483-
break;
2484-
}
2485-
2471+
sinkLastInstruction(UnconditionalPreds);
24862472
NumSinkCommonInstrs++;
24872473
Changed = true;
24882474
}

llvm/test/Transforms/SimplifyCFG/X86/sink-common-code.ll

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -568,16 +568,16 @@ define zeroext i1 @test_crash(i1 zeroext %flag, ptr %i4, ptr %m, ptr %n) {
568568
; CHECK-NEXT: br i1 [[FLAG:%.*]], label [[IF_THEN:%.*]], label [[IF_ELSE:%.*]]
569569
; CHECK: if.then:
570570
; CHECK-NEXT: [[TMP1:%.*]] = load i32, ptr [[I4:%.*]], align 4
571+
; CHECK-NEXT: [[TMP2:%.*]] = add i32 [[TMP1]], -1
571572
; CHECK-NEXT: br label [[IF_END:%.*]]
572573
; CHECK: if.else:
573574
; CHECK-NEXT: [[TMP3:%.*]] = load i32, ptr [[M:%.*]], align 4
574575
; CHECK-NEXT: [[TMP4:%.*]] = load i32, ptr [[N:%.*]], align 4
576+
; CHECK-NEXT: [[TMP5:%.*]] = add i32 [[TMP3]], [[TMP4]]
575577
; CHECK-NEXT: br label [[IF_END]]
576578
; CHECK: if.end:
577-
; CHECK-NEXT: [[TMP4_SINK:%.*]] = phi i32 [ [[TMP4]], [[IF_ELSE]] ], [ -1, [[IF_THEN]] ]
578-
; CHECK-NEXT: [[TMP3_SINK:%.*]] = phi i32 [ [[TMP3]], [[IF_ELSE]] ], [ [[TMP1]], [[IF_THEN]] ]
579-
; CHECK-NEXT: [[TMP5:%.*]] = add i32 [[TMP3_SINK]], [[TMP4_SINK]]
580-
; CHECK-NEXT: store i32 [[TMP5]], ptr [[I4]], align 4
579+
; CHECK-NEXT: [[TMP5_SINK:%.*]] = phi i32 [ [[TMP5]], [[IF_ELSE]] ], [ [[TMP2]], [[IF_THEN]] ]
580+
; CHECK-NEXT: store i32 [[TMP5_SINK]], ptr [[I4]], align 4
581581
; CHECK-NEXT: ret i1 true
582582
;
583583
entry:

0 commit comments

Comments
 (0)