Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 73 additions & 3 deletions src/coreclr/jit/assertionprop.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3477,6 +3477,50 @@ GenTree* Compiler::optVNBasedFoldConstExpr(BasicBlock* block, GenTree* parent, G
}
}

//------------------------------------------------------------------------------
// lclHasSingleSsaStoreDef: Checks if a local in SSA has exactly one store definition
//
// Arguments:
// varDsc - the local's descriptor
//
// Returns:
// True if exactly one SSA definition has a defining store node
//
static bool lclHasSingleSsaStoreDef(LclVarDsc* varDsc)
{
unsigned storeDefs = 0;
for (unsigned i = 0; i < varDsc->lvPerSsaData.GetCount(); i++)
{
if (varDsc->lvPerSsaData.GetSsaDefByIndex(i)->GetDefNode() != nullptr)
{
storeDefs++;
}
}
return storeDefs == 1;
}

//------------------------------------------------------------------------------
// isCheapIntegralConstant: Estimate the cost of substituting an integer constant
//
// Arguments:
// value - the constant's value
//
// Returns:
// True if the value is cheap enough on this target to replace a register read.
//
static bool isCheapIntegralConstant(ssize_t value)
{
#if defined(TARGET_ARM64)
return emitter::emitIns_valid_imm_for_add(value, EA_8BYTE) || emitter::emitIns_valid_imm_for_mov(value, EA_8BYTE);
#elif defined(TARGET_AMD64)
return GenTreeIntConCommon::FitsInI32(value);
#elif defined(TARGET_X86)
return true;
#else
return (value >= -0x10000) && (value <= 0xFFFF);
#endif
}

//------------------------------------------------------------------------------
// optIsProfitableToSubstitute: Checks if value worth substituting to dest
//
Expand Down Expand Up @@ -3509,6 +3553,18 @@ bool Compiler::optIsProfitableToSubstitute(GenTree* dest, BasicBlock* destBlock,

const GenTreeLclVar* lcl = dest->AsLclVar();

// A reused local with multiple stores may stay in a register after this use is folded.
// Keep the register read if substituting the constant would materialize it again at greater cost.
LclVarDsc* const lclDsc = lvaGetDesc(lcl);
if (lclDsc->lvIsCSE && !lclDsc->lvDoNotEnregister && !lclDsc->lvHasLdAddrOp && !lclHasSingleSsaStoreDef(lclDsc))
{
gtPrepareCost(value);
if (value->IsIconHandle() || (value->GetCostEx() > 1) || (value->GetCostSz() > 4))
{
return false;
}
}

if (value->IsCnsVec())
{
#if defined(FEATURE_HW_INTRINSICS)
Expand Down Expand Up @@ -3614,9 +3670,20 @@ GenTree* Compiler::optConstantAssertionProp(const AssertionDsc& curAssertion,

if (lclNumIsCSE(lclNum))
{
// Propagation can eliminate a single-store local or save a load from a stack local.
// For other reused locals, compare the cost of the immediate with a register read.
LclVarDsc* const varDsc = lvaGetDesc(lclNum);
bool cheapConst = false;
if ((curAssertion.GetOp2().GetKind() == O2K_CONST_INT) && !curAssertion.GetOp2().HasIconFlag())
{
cheapConst = isCheapIntegralConstant((ssize_t)curAssertion.GetOp2().GetIntConstant());
}
const bool reuseAllows = varDsc->lvIsCSEReuse && (cheapConst || varDsc->lvDoNotEnregister ||
varDsc->lvHasLdAddrOp || lclHasSingleSsaStoreDef(varDsc));

// Ignore the CSE flag in Global Assertion Prop for checked bound as those usually
// unlock more opportunities for BCE.
if (optLocalAssertionProp || !vnStore->IsVNCheckedBound(optConservativeNormalVN(tree)))
if (!reuseAllows && (optLocalAssertionProp || !vnStore->IsVNCheckedBound(optConservativeNormalVN(tree))))
{
return nullptr;
}
Expand Down Expand Up @@ -6684,12 +6751,15 @@ Compiler::fgWalkResult Compiler::optVNBasedFoldCurStmt(BasicBlock* block,

case GT_LCL_VAR:
case GT_LCL_FLD:
// Let's not conflict with CSE (to save the movw/movt).
if (lclNumIsCSE(tree->AsLclVarCommon()->GetLclNum()))
{
// Preserve fresh CSE temps. For reused locals, optIsProfitableToSubstitute checks the replacement cost.
LclVarDsc* const lclDsc = lvaGetDesc(tree->AsLclVarCommon()->GetLclNum());
if (lclDsc->lvIsCSE && !lclDsc->lvIsCSEReuse)
{
return WALK_CONTINUE;
}
break;
}

case GT_CALL:
// The checks aren't for correctness, but to avoid unnecessary work.
Expand Down
1 change: 1 addition & 0 deletions src/coreclr/jit/compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ class LclVarDsc

unsigned char lvInSsa : 1; // The variable is in SSA form (set by SsaBuilder)
unsigned char lvIsCSE : 1; // Indicates if this LclVar is a CSE variable.
unsigned char lvIsCSEReuse : 1; // Existing local reused by CSE, retaining normal constant propagation.
unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.

unsigned char lvHasILStoreOp : 1; // there is at least one STLOC or STARG on this local
Expand Down
204 changes: 173 additions & 31 deletions src/coreclr/jit/optcse.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5041,15 +5041,100 @@ bool CSE_HeuristicCommon::IsCompatibleType(var_types cseLclVarTyp, var_types exp
}

//------------------------------------------------------------------------
// PerformCSE: takes a successful candidate and performs the appropriate replacements
// CseStoreReachesAllUses: Can each CSE use read the value written by store?
//
// Arguments:
// successfulCandidate - cse candidate to perform
//
// It will replace all of the CSE defs with writes to a new "cse0" LclVar
// and will replace all of the CSE uses with reads of the "cse0" LclVar
static bool CseStoreReachesAllUses(Compiler* comp, CSEdsc* dsc, GenTreeLclVar* store)
{
LclVarDsc* varDsc = comp->lvaGetDesc(store);
bool onlyDef = true;
for (unsigned i = 0; i < varDsc->lvPerSsaData.GetCount(); i++)
{
GenTreeLclVarCommon* def = varDsc->lvPerSsaData.GetSsaDefByIndex(i)->GetDefNode();
if ((def != nullptr) && (def != store))
{
onlyDef = false;
break;
}
}
// The single CSE definition already dominates the uses.
if (onlyDef)
{
return true;
}
if (comp->compHndBBtabCount > 0)
{
return false;
}

// Pruned SSA can omit a phi where we are about to add a use. Check each incoming
// path back to its first store, including paths around backedges.
BitVecTraits traits(comp->compBasicBlockID, comp);
BitVec visited = BitVecOps::MakeEmpty(&traits);
ArrayStack<BasicBlock*> pending(comp->getAllocator(CMK_CSE));
const int useIndex = static_cast<int>(dsc->csdIndex);
auto checkPrefix = [&](BasicBlock* block, Statement* stmt, GenTree* tree) {
while (stmt != nullptr)
{
for (; tree != nullptr; tree = tree->gtPrev)
{
if (tree->OperIsLocalStore() && (tree->AsLclVarCommon()->GetLclNum() == store->GetLclNum()))
{
return tree == store;
}
if (tree->gtCSEnum == useIndex)
{
// The earlier use has the same reaching value and is checked separately.
return true;
}
}
if (stmt == block->firstStmt())
{
break;
}
stmt = stmt->GetPrevStmt();
tree = stmt->GetRootNode();
}

if (block == comp->fgFirstBB)
{
return false;
}
for (FlowEdge* edge : block->PredEdges())
{
BasicBlock* pred = edge->getSourceBlock();
if (BitVecOps::TryAddElemD(&traits, visited, pred->bbID))
{
pending.Push(pred);
}
}
return true;
};

for (treeStmtLst* use = &dsc->csdTreeList; use != nullptr; use = use->tslNext)
{
if ((use->tslTree->gtCSEnum == useIndex) && !checkPrefix(use->tslBlock, use->tslStmt, use->tslTree->gtPrev))
{
return false;
}
}
while (!pending.Empty())
{
BasicBlock* block = pending.Pop();
Statement* stmt = block->lastStmt();
if (!checkPrefix(block, stmt, (stmt == nullptr) ? nullptr : stmt->GetRootNode()))
{
return false;
}
}
return true;
}

//------------------------------------------------------------------------
// PerformCSE: Store definitions in a CSE temp or reusable destination local,
// replace uses with local reads, and update SSA where possible.
//
// It will also put cse0 into SSA if there is just one def.
// Arguments:
// successfulCandidate - the candidate to transform
//
void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate)
{
Expand Down Expand Up @@ -5090,20 +5175,58 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate)

#endif // DEBUG

// Allocate a CSE temp
//
unsigned cseLclVarNum = m_compiler->lvaGrabTemp(false DEBUGARG(grabTempMessage));
var_types cseLclVarTyp = genActualType(successfulCandidate->Expr()->TypeGet());
// Reuse the destination of a single CSE definition to avoid a temp and copy.
UseDefLocation reuseDef;
if ((dsc->csdDefCount == 1) && !successfulCandidate->IsSharedConst())
{
for (treeStmtLst* defLst = &dsc->csdTreeList; defLst != nullptr; defLst = defLst->tslNext)
{
GenTree* const defExp = defLst->tslTree;
if (!IS_CSE_DEF(defExp->gtCSEnum))
{
continue;
}

// A STORE_LCL_VAR immediately follows its only operand in execution order.
GenTree* parent = defExp->gtNext;
if ((parent != nullptr) && parent->OperIs(GT_STORE_LCL_VAR) && (parent->AsLclVar()->Data() == defExp))
{
GenTreeLclVar* store = parent->AsLclVar();
LclVarDsc* varDsc = m_compiler->lvaGetDesc(store);
if (store->HasSsaName() && !varDsc->IsAddressExposed() && !varDsc->lvDoNotEnregister &&
!(varDsc->lvTracked && varDsc->IsLiveInOutOfHandler()) && !varDsc->lvIsCSE &&
!varTypeIsStruct(varDsc) && (varDsc->TypeGet() == genActualType(defExp->TypeGet())) &&
CseStoreReachesAllUses(m_compiler, dsc, store))
{
reuseDef = UseDefLocation(defLst->tslBlock, defLst->tslStmt, store);
}
}
break;
}
}

unsigned cseLclVarNum = (reuseDef.Tree != nullptr) ? reuseDef.Tree->GetLclNum()
: m_compiler->lvaGrabTemp(false DEBUGARG(grabTempMessage));
var_types cseLclVarTyp = genActualType(successfulCandidate->Expr()->TypeGet());
LclVarDsc* const lclDsc = m_compiler->lvaGetDesc(cseLclVarNum);

LclVarDsc* const lclDsc = m_compiler->lvaGetDesc(cseLclVarNum);
if (cseLclVarTyp == TYP_STRUCT)
if (reuseDef.Tree != nullptr)
{
m_compiler->lvaSetStruct(cseLclVarNum, successfulCandidate->Expr()->GetLayout(m_compiler), false);
JITDUMP("Using V%02u, which the definition is stored to, as the temp for " FMT_CSE "\n", cseLclVarNum,
dsc->csdIndex);
}
else
{
if (cseLclVarTyp == TYP_STRUCT)
{
m_compiler->lvaSetStruct(cseLclVarNum, successfulCandidate->Expr()->GetLayout(m_compiler), false);
}
lclDsc->lvType = cseLclVarTyp;
}
lclDsc->lvType = cseLclVarTyp;
lclDsc->lvIsCSE = true;
lclDsc->lvIsCSE = true;
lclDsc->lvIsCSEReuse = reuseDef.Tree != nullptr;

// Record that we created a new LclVar for use as a CSE temp
// Record the CSE temp
//
m_addCSEcount++;
m_compiler->optCSEcount++;
Expand Down Expand Up @@ -5263,6 +5386,14 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate)
}
#endif // DEBUG

if (reuseDef.Tree != nullptr)
{
// The store that consumes the value is the definition.
reuseDef.Tree->gtCSEnum = exp->gtCSEnum;
exp->gtCSEnum = NO_CSE;
continue;
}

GenTree* val = exp;
if (isSharedConst)
{
Expand Down Expand Up @@ -5339,15 +5470,17 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate)
defUses.Emplace(blk, stmt, cseLclVar);
}

bool insertIntoSsa = ssaBuilder.FinalizeDefs();
IncrementalLiveInBuilder liveInBuilder(m_compiler);
bool insertIntoSsa = (reuseDef.Tree == nullptr) && ssaBuilder.FinalizeDefs();

// Start out by inserting all the uses we created as part of defs into SSA.
if (insertIntoSsa)
{
JITDUMP("Inserting each use created for defs into SSA\n");
for (UseDefLocation& defUse : defUses.BottomUpOrder())
{
InsertUseIntoSsa(ssaBuilder, defUse);
ssaBuilder.InsertUse(defUse);
AdoptReachingDefVN(defUse.Tree);
}
}

Expand Down Expand Up @@ -5440,10 +5573,24 @@ void CSE_HeuristicCommon::PerformCSE(CSE_Candidate* successfulCandidate)

ReplaceCSENode(stmt, exp, cse);

if (insertIntoSsa)
if (insertIntoSsa || (reuseDef.Tree != nullptr))
{
ValueNumPair oldLclVNP = cseLclVar->gtVNPair;
InsertUseIntoSsa(ssaBuilder, UseDefLocation(blk, stmt, cseLclVar));
ValueNumPair oldLclVNP = cseLclVar->gtVNPair;
UseDefLocation useLoc(blk, stmt, cseLclVar);
if (reuseDef.Tree != nullptr)
{
unsigned ssaNum = reuseDef.Tree->GetSsaNum();
JITDUMP("Inserting use [%06u] of V%02u d:%u into SSA\n", Compiler::dspTreeID(cseLclVar), cseLclVarNum,
ssaNum);
cseLclVar->SetSsaNum(ssaNum);
liveInBuilder.MarkLiveInBackwards(cseLclVarNum, useLoc, reuseDef);
m_compiler->lvaGetDesc(cseLclVar)->GetPerSsaData(ssaNum)->AddUse(blk);
}
else
{
ssaBuilder.InsertUse(useLoc);
}
AdoptReachingDefVN(cseLclVar);

// Update conservative VN of comma node in case we changed
// conservative VNs due to a new reaching def
Expand Down Expand Up @@ -5508,19 +5655,14 @@ void CSE_HeuristicCommon::ReplaceCSENode(Statement* stmt, GenTree* exp, GenTree*
}

//------------------------------------------------------------------------
// InsertUseIntoSsa:
// Insert a use into SSA form, updating its conservative VN to match its
// reaching definition in the process.
// AdoptReachingDefVN:
// Give a CSE temp use the value number of its reaching definition.
//
// Parameters:
// ssaBuilder - Incremental SSA builder that has already had definitions inserted
// useDefLoc - Location of the new use
// lcl - The use, already in SSA
//
void CSE_HeuristicCommon::InsertUseIntoSsa(IncrementalSsaBuilder& ssaBuilder, const UseDefLocation& useDefLoc)
void CSE_HeuristicCommon::AdoptReachingDefVN(GenTreeLclVar* lcl)
{
ssaBuilder.InsertUse(useDefLoc);

GenTreeLclVar* lcl = useDefLoc.Tree;
assert(lcl->HasSsaName());

LclVarDsc* lclDsc = m_compiler->lvaGetDesc(lcl);
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/jit/optcse.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ class CSE_HeuristicCommon

private:
void ReplaceCSENode(Statement* stmt, GenTree* exp, GenTree* newNode);
void InsertUseIntoSsa(class IncrementalSsaBuilder& ssaBuilder, const struct UseDefLocation& useDefLoc);
void AdoptReachingDefVN(GenTreeLclVar* lcl);
};

#ifdef DEBUG
Expand Down
Loading
Loading