Bad interaction between constant prop and CSE
Exploring the invariant hoisting code I found that it doesn't work with the assignments.
In optimizer.cpp there's a code:
if (treeIsInvariant)
{
// Tree must be a suitable CSE candidate for us to be able to hoist it.
treeIsHoistable = optIsCSEcandidate(tree);
optIsCSEcandidate is false for assignments.
Though it won't work with the assignment the analysis will detect that the the expression subtree of the assignment is invariant and will actually clone the expression to the prehead block of the loop.
We'll get a tree looking e.g. like this:
------------ BB04 [029..???), preds={BB01} succs={BB02}
***** BB04, stmt 8 (top level)
( 5, 5) [000098] ------------- * stmtExpr void (top level) (IL ???... ???)
N006 ( 0, 0) [000096] ------------- | /--* nop void
N007 ( 5, 5) [000097] ------------- \--* comma void
N004 ( 1, 1) [000095] -------H----- | /--* lclVar int V04 loc3 u:3 <l:$46, c:$1c1>
N005 ( 5, 5) [000091] -------H----- \--* + int <l:$4a, c:$1c6>
N002 ( 1, 1) [000094] -------H----- | /--* lclVar int V03 loc2 u:3 <l:$44, c:$1c0>
N003 ( 3, 3) [000092] -------H----- \--* + int <l:$49, c:$1c5>
N001 ( 1, 1) [000093] -------H----- \--* lclVar int V02 loc1 u:3 <l:$42, c:$101>
------------ BB02 [029..043) -> BB02 (cond), preds={BB02,BB04} succs={BB03,BB02}
The result of such a tree is not used and on the code generator no code is produced for such a tree.
/cc @BruceForstall @brucehoult @briansull @Dmitri-Botcharnikov
If we workaround the check with the code:
treeIsHoistable = optIsCSEcandidate(tree) || (tree->gtFlags & GTF_ASG);
We'll anyway get aborted by Compiler::optTreeIsValidAtLoopHead because the following check won't work:
// If the loop does not contains the SSA def we can hoist it.
if (!optLoopTable[lnum].lpContains(lvaTable[lclNum].GetPerSsaData(lclVar->GetSsaNum())->m_defLoc.m_blk))
return true;
The hoisting logic in the JIT leaves the assignment there and hoists out a copy of the rvalue from the assignment
while (!done) { j = a+b+c; ... }
That should turn into
cse0 = (a+b+c);
while (!done) {
j = cse0;
}
It should, I believe, according to the logic in the code: (a+b+c) is treated as subtree of j = a+b+c; the subtree is hoisted. But the resulting tree which we copy to the loop pre-head is useless. I think that is because in Compiler::optPerformHoistExpr we have such a code:
GenTreePtr hoist = hoistExpr;
// The value of the expression isn't used (unless it's an assignment).
if (hoistExpr->OperGet() != GT_ASG)
{
hoist = gtUnusedValNode(hoistExpr);
}
So we get such tree (for which e.g. the codegen doesn't do anything)
------------ BB04 [029..???), preds={BB01} succs={BB02}
***** BB04, stmt 8 (top level)
( 5, 5) [000098] ------------- * stmtExpr void (top level) (IL ???... ???)
N006 ( 0, 0) [000096] ------------- | /--* nop void
N007 ( 5, 5) [000097] ------------- \--* comma void
N004 ( 1, 1) [000095] -------H----- | /--* lclVar int V04 loc3 u:3 <l:$46, c:$1c1>
N005 ( 5, 5) [000091] -------H----- \--* + int <l:$4a, c:$1c6>
N002 ( 1, 1) [000094] -------H----- | /--* lclVar int V03 loc2 u:3 <l:$44, c:$1c0>
N003 ( 3, 3) [000092] -------H----- \--* + int <l:$49, c:$1c5>
N001 ( 1, 1) [000093] -------H----- \--* lclVar int V02 loc1 u:3 <l:$42, c:$101>
------------ BB02 [029..043) -> BB02 (cond), preds={BB02,BB04} succs={BB03,BB02}
That was why I named the issue not just for assignments.
Do you have a complete example? I'm sure I've seen invariant hoisting working, albeit with various limitations.
My example was similar to the one shown by @briansull
internal class Program
{
public static int ii;
private static int Main(string[] args)
{
int res = 0;
ii = 99;
int b = ii;
int d = ii - 98;
int e = ii - 93;
int f = 0;
for (int i = 0; i < b; ++i) {
f = b + d + e;
res += f;
}
return res;
}
}
The result for that code on ARM is the following (also showing the overhead of static variable load, stores and address computation, but the latter is codegen related):
G_M35508_IG01:
000000 E92D 4818 push {r3,r4,r11,lr}
000004 F10D 0B08 add r11, sp, 8
G_M35508_IG02:
000008 2000 movs r0, 0
00000A 2363 movs r3, 99
00000C F243 02C4 movw r2, 0x30c4
000010 F2CB 5287 movt r2, 0xb587
000014 6013 str r3, [r2]
000016 F243 02C4 movw r2, 0x30c4
00001A F2CB 5287 movt r2, 0xb587
00001E 6812 ldr r2, [r2]
000020 F243 03C4 movw r3, 0x30c4
000024 F2CB 5387 movt r3, 0xb587
000028 681B ldr r3, [r3]
00002A F1A3 0462 sub r4, r3, 98
00002E F243 03C4 movw r3, 0x30c4
000032 F2CB 5387 movt r3, 0xb587
000036 681B ldr r3, [r3]
000038 F1A3 0E5D sub lr, r3, 93
00003C 2300 movs r3, 0
00003E 2A00 cmp r2, 0
000040 DD05 ble SHORT G_M35508_IG04
G_M35508_IG03:
000042 1911 adds r1, r2, r4
000044 4471 add r1, lr
000046 4408 add r0, r1
000048 3301 adds r3, 1
00004A 4293 cmp r3, r2
00004C DBF9 blt SHORT G_M35508_IG03
G_M35508_IG04:
00004E E8BD 4818 pop {r3,r4,r11,lr}
000052 4770 bx lr
; Total bytes of code 84, prolog size 8 for method Program:Main(ref):int
; ============================================================
x64 version (albeit an earlier one) - has all the similar issues:
G_M35508_IG01:
55 push rbp
488BEC mov rbp, rsp
G_M35508_IG02:
33C0 xor eax, eax
48BF6439E283477F0000 mov rdi, 0x7F4783E23964
C70763000000 mov dword ptr [rdi], 99
8B3F mov edi, dword ptr [rdi]
48BE6439E283477F0000 mov rsi, 0x7F4783E23964
8B36 mov esi, dword ptr [rsi]
83C69E add esi, -98
48BA6439E283477F0000 mov rdx, 0x7F4783E23964
8B12 mov edx, dword ptr [rdx]
83C2A3 add edx, -93
33C9 xor ecx, ecx
85FF test edi, edi
7E10 jle SHORT G_M35508_IG04
G_M35508_IG03:
448D0437 lea r8d, [rdi+rsi]
4403C2 add r8d, edx
4103C0 add eax, r8d
FFC1 inc ecx
3BCF cmp ecx, edi
7CF0 jl SHORT G_M35508_IG03
G_M35508_IG04:
5D pop rbp
C3 ret
I think that GT_ASG should be allowed and when we check the SSA variable assignment in the loop block, we should check that there's a phi-node for that value in the loop instead.
Even if I add what I propose to the code:
optIsCSEcandidate(tree) || (tree->gtFlags & GTF_ASG);
and to Compiler::optTreeIsValidAtLoopHead:
// If the tree is the non-phi def itself then its the invariant assignment
GenTreePtr def_tree = lvaTable[lclNum].GetPerSsaData(lclVar->GetSsaNum())->m_defLoc.m_tree;
if (def_tree == tree && tree->OperIsNonPhiLocal())
return true;
// If the loop does not contains the SSA def we can hoist it.
if (!optLoopTable[lnum].lpContains(lvaTable[lclNum].GetPerSsaData(lclVar->GetSsaNum())->m_defLoc.m_blk))
return true;
The assignment will be hoisted. But the previous expression inside the loop will still be there, and in the end we again get the non-hoisted code generated.
In fact such a hoisted assignment, of course, breaks the SSA because the value has two defs now. So the def in loop should be removed and the block for the SSA def should be redirected to the loop pre head.
I think that GT_ASG should be allowed and when we check the SSA variable assignment in the loop block, we should check that there's a phi-node for that value in the loop instead.
That may not be enough. The check in optIsCSEcandidate doesn't specifically check if the node is an assignment, it checks if the tree contains any assignments.
Also, in this particular case the best solution would be to just get rid of the f variable which is simply not needed. This is something that come up before, for example in dotnet/runtime#4655.
Of course we shouldn't change the code for CSE, we'd rather make that in a somewhat different manner. For my workaround to test it I did just
optIsCSEcandidate(tree) || (tree->gtFlags & GTF_ASG);
But then there's an obstacle that once you have a ssa def in the loop for the value, you won't be allowed to hoist the tree.
As I wrote above I bypassed those check-related issues, but the result is bad SSA, and the original tree is still in the loop.
@mikedn what do you mean by getting rid of the f variable? it doesn't matter if you use the variable or not, you won't have invariant motion either way.
The issue you mentioned above dotnet/runtime#4655 is a more general one. The trees correspond to IL expressions and they live like that till the codegen. It was just the reason why I looked at the invariant motion.
I wanted to see how it will do some inter-tree thing on the example of invariant motion, but the latter just doesn't work.
Being said that the invariant motion is not so inter-tree activity anyway. It can just hoist some trees or subtrees without merging any trees with different IL's.
But cloning a tree to the loop prehead doesn't specify any IL:
( 5, 5) [000098] ------------- * stmtExpr void (top level) (IL ???... ???)
So, I hypothesize that IL pc is not that important to be preserved till the code generation.
it doesn't matter if you use the variable or not, you won't have invariant motion either way.
Right, because anyway there's the assignment to res so we're probably back at square one.
@briansull
while (!done) {
j = a+b+c;
...
}
That should turn into
cse0 = (a+b+c);
while (!done) {
j = cse0;
}
Did you actually mean that it could work the following way:
while (!done) {
j = a+b+c;
...
}
That should turn into
cse0 = a+b+c;
while (!done) {
j = a+b+c;
}
And then presumably a subsequent CSE would do:
cse0 = (a+b+c);
while (!done) {
j = cse0;
}
I believe CSE won't push expression copies to the loop though. Or, perhaps it would, but the transformation doesn't happen anyway.
A straight cse example also doesn't work
res += b + d + e;
res += b + d + e;
The generated code still does all the things twice:
000030 1898 adds r0, r3, r2
000032 4408 add r0, r1
000034 4418 add r0, r3
000036 4410 add r0, r2
000038 4408 add r0, r1
And even in a single tree:
for (int i = 0; i < b; ++i) {
res += (b + d + e) + (b + d + e);
}
return res;
The result is:
G_M10576_IG03:
000042 4418 add r0, r3
000044 4408 add r0, r1
000046 4420 add r0, r4
000048 4418 add r0, r3
00004A 4408 add r0, r1
00004C 4420 add r0, r4
00004E 3201 adds r2, 1
000050 429A cmp r2, r3
000052 DBF6 blt SHORT G_M10576_IG03
A straight cse example also doesn't work...
This looks like a different issue: dotnet/runtime#5121
@mikedn so, do you mean that the re-association is the root for the no cse application in that case?