1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// Early Value Propagation
//
// This phase performs an SSA-based value propagation optimization that currently only applies to array
// lengths, runtime type handles, and explicit null checks. An SSA-based backwards tracking of local variables
// is performed at each point of interest, e.g., an array length reference site, a method table reference site, or
// an indirection.
// The tracking continues until an interesting value is encountered. The value is then used to rewrite
// the source site or the value.
//
///////////////////////////////////////////////////////////////////////////////////////
#include "jitpch.h"
#include "ssabuilder.h"
bool Compiler::optDoEarlyPropForFunc()
{
bool propArrayLen = (optMethodFlags & OMF_HAS_NEWARRAY) && (optMethodFlags & OMF_HAS_ARRAYREF);
bool propGetType = (optMethodFlags & OMF_HAS_NEWOBJ) && (optMethodFlags & OMF_HAS_VTABLEREF);
bool propNullCheck = (optMethodFlags & OMF_HAS_NULLCHECK) != 0;
return propArrayLen || propGetType || propNullCheck;
}
bool Compiler::optDoEarlyPropForBlock(BasicBlock* block)
{
bool bbHasArrayRef = (block->bbFlags & BBF_HAS_IDX_LEN) != 0;
bool bbHasVtableRef = (block->bbFlags & BBF_HAS_VTABREF) != 0;
bool bbHasNullCheck = (block->bbFlags & BBF_HAS_NULLCHECK) != 0;
return bbHasArrayRef || bbHasVtableRef || bbHasNullCheck;
}
//--------------------------------------------------------------------
// gtIsVtableRef: Return true if the tree is a method table reference.
//
// Arguments:
// tree - The input tree.
//
// Return Value:
// Return true if the tree is a method table reference.
bool Compiler::gtIsVtableRef(GenTreePtr tree)
{
if (tree->OperGet() == GT_IND)
{
GenTree* addr = tree->AsIndir()->Addr();
if (addr->OperIsAddrMode())
{
GenTreeAddrMode* addrMode = addr->AsAddrMode();
return (!addrMode->HasIndex() && (addrMode->Base()->TypeGet() == TYP_REF));
}
}
return false;
}
//------------------------------------------------------------------------------
// getArrayLengthFromAllocation: Return the array length for an array allocation
// helper call.
//
// Arguments:
// tree - The array allocation helper call.
//
// Return Value:
// Return the array length node.
GenTreePtr Compiler::getArrayLengthFromAllocation(GenTreePtr tree)
{
assert(tree != nullptr);
if (tree->OperGet() == GT_CALL)
{
GenTreeCall* call = tree->AsCall();
if (call->gtCallType == CT_HELPER)
{
if (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_DIRECT) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_OBJ) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_VC) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_ALIGN8))
{
// This is an array allocation site. Grab the array length node.
return gtArgEntryByArgNum(call, 1)->node;
}
}
}
return nullptr;
}
//-----------------------------------------------------------------------------
// getObjectHandleNodeFromAllocation: Return the type handle for an object allocation
// helper call.
//
// Arguments:
// tree - The object allocation helper call.
//
// Return Value:
// Return the object type handle node.
GenTreePtr Compiler::getObjectHandleNodeFromAllocation(GenTreePtr tree)
{
assert(tree != nullptr);
if (tree->OperGet() == GT_CALL)
{
GenTreeCall* call = tree->AsCall();
if (call->gtCallType == CT_HELPER)
{
if (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWFAST) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWSFAST) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWSFAST_ALIGN8) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_DIRECT) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_OBJ) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_VC) ||
call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_NEWARR_1_ALIGN8))
{
// This is an object allocation site. Return the runtime type handle node.
fgArgTabEntryPtr argTabEntry = gtArgEntryByArgNum(call, 0);
return argTabEntry->node;
}
}
}
return nullptr;
}
//------------------------------------------------------------------------------------------
// optEarlyProp: The entry point of the early value propagation.
//
// Notes:
// This phase performs an SSA-based value propagation, including
// 1. Array length propagation.
// 2. Runtime type handle propagation.
// 3. Null check folding.
//
// For array length propagation, a demand-driven SSA-based backwards tracking of constant
// array lengths is performed at each array length reference site which is in form of a
// GT_ARR_LENGTH node. When a GT_ARR_LENGTH node is seen, the array ref pointer which is
// the only child node of the GT_ARR_LENGTH is tracked. This is only done for array ref
// pointers that have valid SSA forms.The tracking is along SSA use-def chain and stops
// at the original array allocation site where we can grab the array length. The
// GT_ARR_LENGTH node will then be rewritten to a GT_CNS_INT node if the array length is
// constant.
//
// Similarly, the same algorithm also applies to rewriting a method table (also known as
// vtable) reference site which is in form of GT_INDIR node. The base pointer, which is
// an object reference pointer, is treated in the same way as an array reference pointer.
//
// Null check folding tries to find GT_INDIR(obj + const) that GT_NULLCHECK(obj) can be folded into
/// and removed. Currently, the algorithm only matches GT_INDIR and GT_NULLCHECK in the same basic block.
void Compiler::optEarlyProp()
{
#ifdef DEBUG
if (verbose)
{
printf("*************** In optEarlyProp()\n");
}
#endif
assert(fgSsaPassesCompleted == 1);
if (!optDoEarlyPropForFunc())
{
return;
}
for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext)
{
if (!optDoEarlyPropForBlock(block))
{
continue;
}
compCurBB = block;
for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr;)
{
// Preserve the next link before the propagation and morph.
GenTreeStmt* next = stmt->gtNextStmt;
compCurStmt = stmt;
// Walk the stmt tree in linear order to rewrite any array length reference with a
// constant array length.
bool isRewritten = false;
for (GenTreePtr tree = stmt->gtStmt.gtStmtList; tree != nullptr; tree = tree->gtNext)
{
if (optEarlyPropRewriteTree(tree))
{
isRewritten = true;
}
}
// Morph the stmt and update the evaluation order if the stmt has been rewritten.
if (isRewritten)
{
gtSetStmtInfo(stmt);
fgSetStmtSeq(stmt);
}
stmt = next;
}
}
#ifdef DEBUG
if (verbose)
{
JITDUMP("\nAfter optEarlyProp:\n");
fgDispBasicBlocks(/*dumpTrees*/ true);
}
#endif
}
//----------------------------------------------------------------
// optEarlyPropRewriteValue: Rewrite a tree to the actual value.
//
// Arguments:
// tree - The input tree node to be rewritten.
//
// Return Value:
// Return true iff "tree" is successfully rewritten.
bool Compiler::optEarlyPropRewriteTree(GenTreePtr tree)
{
GenTreePtr objectRefPtr = nullptr;
optPropKind propKind = optPropKind::OPK_INVALID;
if (tree->OperGet() == GT_ARR_LENGTH)
{
objectRefPtr = tree->gtOp.gtOp1;
propKind = optPropKind::OPK_ARRAYLEN;
}
else if ((tree->OperGet() == GT_IND) && !varTypeIsStruct(tree))
{
// TODO-1stClassStructs: The above condition should apply equally to all indirections,
// but previously the implicit indirections due to a struct assignment were not
// considered, so we are currently limiting it to non-structs to preserve existing
// behavior.
// optFoldNullCheck takes care of updating statement info if a null check is removed.
optFoldNullCheck(tree);
if (gtIsVtableRef(tree))
{
// Don't propagate type handles that are used as null checks, which are usually in
// form of
// * stmtExpr void (top level)
// \--* indir int
// \--* lclVar ref V02 loc0
if (compCurStmt->gtStmt.gtStmtExpr == tree)
{
return false;
}
objectRefPtr = tree->gtOp.gtOp1;
propKind = optPropKind::OPK_OBJ_GETTYPE;
}
else
{
return false;
}
}
else
{
return false;
}
if (!objectRefPtr->OperIsScalarLocal() || fgExcludeFromSsa(objectRefPtr->AsLclVarCommon()->GetLclNum()))
{
return false;
}
bool isRewritten = false;
GenTreePtr root = compCurStmt;
unsigned lclNum = objectRefPtr->AsLclVarCommon()->GetLclNum();
unsigned ssaNum = objectRefPtr->AsLclVarCommon()->GetSsaNum();
GenTreePtr actualVal = optPropGetValue(lclNum, ssaNum, propKind);
if (actualVal != nullptr)
{
if (propKind == optPropKind::OPK_ARRAYLEN)
{
assert(actualVal->IsCnsIntOrI());
if (actualVal->gtIntCon.gtIconVal > INT32_MAX)
{
// Don't propagate array lengths that are beyond the maximum value of a GT_ARR_LENGTH.
// node. CORINFO_HELP_NEWARR_1_OBJ helper call allows to take a long integer as the
// array length argument, but the type of GT_ARR_LENGTH is always INT32.
return false;
}
}
else if (propKind == optPropKind::OPK_OBJ_GETTYPE)
{
assert(actualVal->IsCnsIntOrI());
}
#ifdef DEBUG
if (verbose)
{
printf("optEarlyProp Rewriting BB%02u\n", compCurBB->bbNum);
gtDispTree(root);
printf("\n");
}
#endif
// Rewrite the tree using a copy of "actualVal"
GenTreePtr actualValCopy;
var_types origType = tree->gtType;
// Propagating a constant into an array index expression requires calling
// LabelIndex to update the FieldSeq annotations. EarlyProp may replace
// array length expressions with constants, so check if this is an array
// length operator that is part of an array index expression.
bool isIndexExpr = (tree->OperGet() == GT_ARR_LENGTH && ((tree->gtFlags & GTF_ARRLEN_ARR_IDX) != 0));
if (actualVal->GetNodeSize() <= tree->GetNodeSize())
{
actualValCopy = tree;
}
else
{
actualValCopy = gtNewLargeOperNode(GT_ADD, TYP_INT);
}
fgWalkTreePre(&tree, Compiler::lvaDecRefCntsCB, (void*)this, true);
actualValCopy->CopyFrom(actualVal, this);
actualValCopy->gtType = origType;
if (isIndexExpr)
{
actualValCopy->LabelIndex(this);
}
fgWalkTreePre(&actualValCopy, Compiler::lvaIncRefCntsCB, (void*)this, true);
if (actualValCopy != tree)
{
gtReplaceTree(root, tree, actualValCopy);
}
isRewritten = true;
#ifdef DEBUG
if (verbose)
{
printf("to\n");
gtDispTree(compCurStmt);
printf("\n");
}
#endif
}
return isRewritten;
}
//-------------------------------------------------------------------------------------------
// optPropGetValue: Given an SSA object ref pointer, get the value needed based on valueKind.
//
// Arguments:
// lclNum - The local var number of the ref pointer.
// ssaNum - The SSA var number of the ref pointer.
// valueKind - The kind of value of interest.
//
// Return Value:
// Return the corresponding value based on valueKind.
GenTreePtr Compiler::optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind)
{
return optPropGetValueRec(lclNum, ssaNum, valueKind, 0);
}
//-----------------------------------------------------------------------------------
// optPropGetValueRec: Given an SSA object ref pointer, get the value needed based on valueKind
// within a recursion bound.
//
// Arguments:
// lclNum - The local var number of the array pointer.
// ssaNum - The SSA var number of the array pointer.
// valueKind - The kind of value of interest.
// walkDepth - Current recursive walking depth.
//
// Return Value:
// Return the corresponding value based on valueKind.
GenTreePtr Compiler::optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth)
{
if (ssaNum == SsaConfig::RESERVED_SSA_NUM)
{
return nullptr;
}
SSAName ssaName(lclNum, ssaNum);
GenTreePtr value = nullptr;
// Bound the recursion with a hard limit.
if (walkDepth > optEarlyPropRecurBound)
{
return nullptr;
}
// Track along the use-def chain to get the array length
GenTreePtr treelhs = lvaTable[lclNum].GetPerSsaData(ssaNum)->m_defLoc.m_tree;
if (treelhs == nullptr)
{
// Incoming parameters or live-in variables don't have actual definition tree node
// for their FIRST_SSA_NUM. See SsaBuilder::RenameVariables.
assert(ssaNum == SsaConfig::FIRST_SSA_NUM);
}
else
{
GenTreePtr* lhsPtr;
GenTreePtr treeDefParent = treelhs->gtGetParent(&lhsPtr);
if (treeDefParent->OperGet() == GT_ASG)
{
assert(treelhs == treeDefParent->gtGetOp1());
GenTreePtr treeRhs = treeDefParent->gtGetOp2();
if (treeRhs->OperIsScalarLocal() && !fgExcludeFromSsa(treeRhs->AsLclVarCommon()->GetLclNum()))
{
// Recursively track the Rhs
unsigned rhsLclNum = treeRhs->AsLclVarCommon()->GetLclNum();
unsigned rhsSsaNum = treeRhs->AsLclVarCommon()->GetSsaNum();
value = optPropGetValueRec(rhsLclNum, rhsSsaNum, valueKind, walkDepth + 1);
}
else
{
if (valueKind == optPropKind::OPK_ARRAYLEN)
{
value = getArrayLengthFromAllocation(treeRhs);
if (value != nullptr)
{
if (!value->IsCnsIntOrI())
{
// Leave out non-constant-sized array
value = nullptr;
}
}
}
else if (valueKind == optPropKind::OPK_OBJ_GETTYPE)
{
value = getObjectHandleNodeFromAllocation(treeRhs);
if (value != nullptr)
{
if (!value->IsCnsIntOrI())
{
// Leave out non-constant-sized array
value = nullptr;
}
}
}
}
}
}
return value;
}
//----------------------------------------------------------------
// optFoldNullChecks: Try to find a GT_NULLCHECK node that can be folded into the GT_INDIR node.
//
// Arguments:
// tree - The input GT_INDIR tree.
//
void Compiler::optFoldNullCheck(GenTreePtr tree)
{
//
// Check for a pattern like this:
//
// =
// / \
// x comma
// / \
// nullcheck +
// | / \
// y y const
//
//
// some trees in the same
// basic block with
// no unsafe side effects
//
// indir
// |
// x
//
// where the const is suitably small
// and transform it into
//
// =
// / \
// x +
// / \
// y const
//
//
// some trees with no unsafe side effects here
//
// indir
// |
// x
if ((compCurBB->bbFlags & BBF_HAS_NULLCHECK) == 0)
{
return;
}
assert(tree->OperGet() == GT_IND);
if (tree->gtGetOp1()->OperGet() == GT_LCL_VAR)
{
// Check if we have the pattern above and find the nullcheck node if we do.
// Find the definition of the indirected local (x in the picture)
GenTreePtr indLocalTree = tree->gtGetOp1();
unsigned lclNum = indLocalTree->AsLclVarCommon()->GetLclNum();
unsigned ssaNum = indLocalTree->AsLclVarCommon()->GetSsaNum();
if (ssaNum != SsaConfig::RESERVED_SSA_NUM)
{
DefLoc defLoc = lvaTable[lclNum].GetPerSsaData(ssaNum)->m_defLoc;
BasicBlock* defBlock = defLoc.m_blk;
if (compCurBB == defBlock)
{
GenTreePtr defTree = defLoc.m_tree;
GenTreePtr defParent = defTree->gtGetParent(nullptr);
if ((defParent->OperGet() == GT_ASG) && (defParent->gtNext == nullptr))
{
GenTreePtr defRHS = defParent->gtGetOp2();
if (defRHS->OperGet() == GT_COMMA)
{
if (defRHS->gtGetOp1()->OperGet() == GT_NULLCHECK)
{
GenTreePtr nullCheckTree = defRHS->gtGetOp1();
if (nullCheckTree->gtGetOp1()->OperGet() == GT_LCL_VAR)
{
// We found a candidate for 'y' in the picture
unsigned nullCheckLclNum = nullCheckTree->gtGetOp1()->AsLclVarCommon()->GetLclNum();
if (defRHS->gtGetOp2()->OperGet() == GT_ADD)
{
GenTreePtr additionNode = defRHS->gtGetOp2();
if ((additionNode->gtGetOp1()->OperGet() == GT_LCL_VAR) &&
(additionNode->gtGetOp1()->gtLclVarCommon.gtLclNum == nullCheckLclNum))
{
GenTreePtr offset = additionNode->gtGetOp2();
if (offset->IsCnsIntOrI())
{
if (!fgIsBigOffset(offset->gtIntConCommon.IconValue()))
{
// Walk from the use to the def in reverse execution order to see
// if any nodes have unsafe side effects.
GenTreePtr currentTree = indLocalTree->gtPrev;
bool isInsideTry = compCurBB->hasTryIndex();
bool canRemoveNullCheck = true;
const unsigned maxNodesWalked = 25;
unsigned nodesWalked = 0;
// First walk the nodes in the statement containing the indirection
// in reverse execution order starting with the indirection's
// predecessor.
while (canRemoveNullCheck && (currentTree != nullptr))
{
if ((nodesWalked++ > maxNodesWalked) ||
!optCanMoveNullCheckPastTree(currentTree, isInsideTry))
{
canRemoveNullCheck = false;
}
else
{
currentTree = currentTree->gtPrev;
}
}
// Then walk the statement list in reverse execution order
// until we get to the statement containing the null check.
// We only need to check the side effects at the root of each statement.
GenTreePtr curStmt = compCurStmt->gtPrev;
currentTree = curStmt->gtStmt.gtStmtExpr;
while (canRemoveNullCheck && (currentTree != defParent))
{
if ((nodesWalked++ > maxNodesWalked) ||
!optCanMoveNullCheckPastTree(currentTree, isInsideTry))
{
canRemoveNullCheck = false;
}
else
{
curStmt = curStmt->gtStmt.gtPrevStmt;
assert(curStmt != nullptr);
currentTree = curStmt->gtStmt.gtStmtExpr;
}
}
if (canRemoveNullCheck)
{
// Remove the null check
nullCheckTree->gtFlags &= ~(GTF_EXCEPT | GTF_DONT_CSE);
// Set this flag to prevent reordering
nullCheckTree->gtFlags |= GTF_ORDER_SIDEEFF;
defRHS->gtFlags &= ~(GTF_EXCEPT | GTF_DONT_CSE);
defRHS->gtFlags |=
additionNode->gtFlags & (GTF_EXCEPT | GTF_DONT_CSE);
// Re-morph the statement.
fgMorphBlockStmt(compCurBB, curStmt DEBUGARG("optFoldNullCheck"));
// Recalculate the gtCostSz, etc...
gtSetStmtInfo(curStmt);
// Re-thread the nodes
fgSetStmtSeq(curStmt);
}
}
}
}
}
}
}
}
}
}
}
}
}
//----------------------------------------------------------------
// optCanMoveNullCheckPastTree: Check if GT_NULLCHECK can be folded into a node that
// is after tree is execution order.
//
// Arguments:
// tree - The input GT_INDIR tree.
// isInsideTry - True if tree is inside try, false otherwise
//
// Return Value:
// True if GT_NULLCHECK can be folded into a node that is after tree is execution order,
// false otherwise.
bool Compiler::optCanMoveNullCheckPastTree(GenTreePtr tree, bool isInsideTry)
{
bool result = true;
if (isInsideTry)
{
// We disallow calls, exception sources, and all assignments.
// Assignments to locals are disallowed inside try because
// they may be live in the handler.
if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0)
{
result = false;
}
}
else
{
// We disallow calls, exception sources, and assignments to
// global memory.
if (GTF_GLOBALLY_VISIBLE_SIDE_EFFECTS(tree->gtFlags))
{
result = false;
}
}
return result;
}
|