diff --git a/src/coreclr/jit/priorityqueue.h b/src/coreclr/jit/priorityqueue.h index dc51f0efdea0f6..b3f8b4a74d1524 100644 --- a/src/coreclr/jit/priorityqueue.h +++ b/src/coreclr/jit/priorityqueue.h @@ -18,6 +18,11 @@ class PriorityQueue { } + const int Size() const + { + return static_cast(data.size()); + } + const T& Top() const { assert(!data.empty()); diff --git a/src/coreclr/jit/regallocwasm.cpp b/src/coreclr/jit/regallocwasm.cpp index f8e8f516557732..9627d6f8001a2d 100644 --- a/src/coreclr/jit/regallocwasm.cpp +++ b/src/coreclr/jit/regallocwasm.cpp @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#include "algorithm.h" #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop @@ -33,6 +34,7 @@ PhaseStatus WasmRegAlloc::doRegisterAllocation() IdentifyCandidates(); CollectReferences(); + BuildIntervals(); ResolveReferences(); PublishAllocationResults(); @@ -47,6 +49,7 @@ PhaseStatus WasmRegAlloc::doRegisterAllocation() // bb - the basic block whose start is being processed // // Notes: + // This relies on m_currentFunclet to try and avoid work in some cases. // void WasmRegAlloc::recordVarLocationsAtStartOfBB(BasicBlock* bb) @@ -1009,6 +1012,346 @@ regNumber WasmRegAlloc::RequestInternalRegister(GenTree* node, var_types type) return reg; } +void WasmRegAlloc::BuildIntervals() +{ + for (FuncInfoDsc* const funcInfo : m_compiler->Funcs()) + { + m_currentFunclet = funcInfo->GetFuncletIdx(m_compiler); + PerFuncletData* const funcletData = m_perFuncletData[m_currentFunclet]; + assert(m_compiler->lvaTrackedCount == funcletData->m_intervals.size()); + BuildFuncIntervals(funcInfo, funcletData); + } + + DumpIntervals(); +} + +GenTree* getNonContainedUser(GenTree* node, LIR::Range& blockRange) +{ + GenTree* useNode = node; + LIR::Use treeUse; + bool foundUse; + do + { + foundUse = blockRange.TryGetUse(useNode, &treeUse); + useNode = treeUse.User(); + assert(foundUse); + } while (useNode->isContained()); + + return useNode; +} + +bool WasmRegAlloc::isIntervalCandidate(LclVarDsc* varDsc, PerFuncletData* funcletData) +{ + if (varDsc->lvIsRegCandidate()) + { + // Don't permit params or SP/FP locals to be tracked interval candidates; + regNumber reg = varDsc->GetRegNum(); + assert(genIsValidReg(reg)); + return !varDsc->lvIsParam && !varDsc->lvIsParamRegTarget && reg != funcletData->m_fpReg && + reg != funcletData->m_spReg; + } + return false; +} + +void WasmRegAlloc::BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData) +{ + struct PendingLclUse + { + GenTree* UserNode; + unsigned int trackedLcl; + }; + + for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++) + { + LclVarDsc* varDsc = m_compiler->lvaGetDescByTrackedIndex(i); + Interval* interval = nullptr; + if (isIntervalCandidate(varDsc, funcletData)) + { + regNumber virtReg = varDsc->GetRegNum(); + interval = new (m_compiler->getAllocator(CMK_LSRA_Interval)) Interval(virtReg, i); + } + funcletData->m_intervals[i] = interval; + } + + auto updateIntervalStart = [&](unsigned trackedIdx, unsigned pos) { + Interval* interval = funcletData->m_intervals[trackedIdx]; + if (interval != nullptr) + { + int prev = interval->start; + interval->start = min(interval->start, static_cast(pos)); + if (interval->start != prev) + { + JITDUMP("V%02u start: %d -> %d\n", m_compiler->lvaTrackedIndexToLclNum(trackedIdx), prev, + interval->start); + } + } + }; + + auto updateIntervalEnd = [&](unsigned trackedIdx, unsigned pos) { + Interval* interval = funcletData->m_intervals[trackedIdx]; + if (interval != nullptr) + { + int prev = interval->end; + interval->end = max(interval->end, static_cast(pos)); + if (interval->end != prev) + { + JITDUMP("V%02u end: %d -> %d\n", m_compiler->lvaTrackedIndexToLclNum(trackedIdx), prev, interval->end); + } + } + }; + + auto updateIntervalStarts = [&](VARSET_TP toUpdate, unsigned pos) { + VarSetOps::Iter iter(m_compiler, toUpdate); + unsigned trackedIdx; + while (iter.NextElem(&trackedIdx)) + { + updateIntervalStart(trackedIdx, pos); + } + }; + + auto updateIntervalEnds = [&](VARSET_TP toUpdate, unsigned pos) { + VarSetOps::Iter iter(m_compiler, toUpdate); + unsigned trackedIdx; + while (iter.NextElem(&trackedIdx)) + { + updateIntervalEnd(trackedIdx, pos); + } + }; + + JITDUMP("----------------------------------------\n"); + JITDUMP("Building intervals for funclet %u\n", m_currentFunclet); + JITDUMP("----------------------------------------\n"); + ArrayStack pendingMultipleUse(m_compiler->getAllocator(CMK_LSRA)); + + // Note: This phase should run after fgWasmControlFlow, so can expect each funclet's blocks to be ordered in + // a Wasm-compatible loop-aware RPO + unsigned pos = 0; + for (BasicBlock* const block : funcInfo->Blocks(m_compiler)) + { + m_currentBlock = block; + + JITDUMPEXEC(block->dspBlockHeader()); + JITDUMP("liveIn="); + JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveIn)); + JITDUMP(" "); + JITDUMP("liveOut="); + JITDUMPEXEC(dumpConvertedVarSet(m_compiler, block->bbLiveOut)); + JITDUMP("\n"); + + // Potentially update the start points of any intervals live at block entry. + updateIntervalStarts(block->bbLiveIn, pos); + + for (GenTree* tree : LIR::AsRange(block)) + { + JITDUMP("%10u: ", pos); + DISPNODE(tree); + // Consume any multiple-use local reads used by this node; + // if a read of a reg candidate is MultiplyUsed, its underlying local lifetime must extend through the node + // that consumes it since it won't get a separate temp. + while (!pendingMultipleUse.Empty() && tree == pendingMultipleUse.TopRef().UserNode) + { + PendingLclUse pendingUse = pendingMultipleUse.Pop(); + updateIntervalEnd(pendingUse.trackedLcl, pos); + } + + if (tree->OperIsLocal()) + { + GenTreeLclVarCommon* lcl = tree->AsLclVarCommon(); + LclVarDsc* dsc = m_compiler->lvaGetDesc(lcl->GetLclNum()); + + if (isIntervalCandidate(dsc, funcletData)) + { + assert(dsc->lvIsInReg()); + assert(tree->OperIs(GT_STORE_LCL_VAR, GT_LCL_VAR)); + assert(!tree->isContained()); + + if (tree->OperIs(GT_STORE_LCL_VAR)) + { + updateIntervalStart(dsc->lvVarIndex, pos); + // Update the interval end here too, in case this is a dead store + // and we never have a use + // TODO: could we check flags to determine if it's a dead store? + updateIntervalEnd(dsc->lvVarIndex, pos); + } + else if (tree->OperIs(GT_LCL_VAR)) + { + if ((tree->gtLIRFlags & LIR::Flags::MultiplyUsed) != 0) + { + GenTree* user = getNonContainedUser(tree, CurrentRange()); + pendingMultipleUse.Push({user, dsc->lvVarIndex}); + } + else + { + // Ordinary single-use local var read; extend the var's interval to potentially end here + updateIntervalEnd(dsc->lvVarIndex, pos); + } + } + } + } + + pos++; + } + + // Extend interval ends to the end of the block for live-out locals, + // and assign them pos + 1, where pos is the last position in the block + updateIntervalEnds(block->bbLiveOut, pos); + } + + // Remove empty intervals which correspond to virtual registers that were never used in this funclet. + for (size_t i = 0; i < funcletData->m_intervals.size(); i++) + { + Interval* interval = funcletData->m_intervals[i]; + if (interval != nullptr && interval->start > interval->end) + { + // An empty interval should always be one that was never set + assert(interval->start == INT_MAX && interval->end == INT_MIN); + funcletData->m_intervals[i] = nullptr; + } + } +} + +void WasmRegAlloc::DumpIntervals() +{ + JITDUMP("Final intervals:\n"); + JITDUMP("----------------\n") + for (FuncInfoDsc* const funcInfo : m_compiler->Funcs()) + { + PerFuncletData* funcletData = m_perFuncletData[funcInfo->GetFuncletIdx(m_compiler)]; + JITDUMP("Funclet %u:\n", funcInfo->GetFuncletIdx(m_compiler)); + for (unsigned trackedIdx = 0; trackedIdx < funcletData->m_intervals.size(); trackedIdx++) + { + unsigned lclNum = m_compiler->lvaTrackedIndexToLclNum(trackedIdx); + const LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum); + Interval* interval = funcletData->m_intervals[trackedIdx]; + if (interval == nullptr) + { + continue; + } + + JITDUMP("Interval %2u: (V%02u) %s range:[%d, %d] virtReg:$%u:%s%s\n", trackedIdx, lclNum, + varTypeName(varDsc->TypeGet()), interval->start, interval->end, WasmRegToIndex(interval->virtReg), + WasmValueTypeName(WasmRegToType(interval->virtReg)), + varDsc->lvWasmGCWriteThru ? " (GCWriteThru)" : ""); + } + } +} + +unsigned int WasmRegAlloc::ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spVirtReg, regNumber fpVirtReg) +{ + unsigned int indexBase = 0; + switch (funcInfo->funKind) + { + case FuncKind::FUNC_ROOT: + { + for (unsigned argLclNum = 0; argLclNum < m_compiler->info.compArgsCount; argLclNum++) + { + const ABIPassingInformation& abiInfo = m_compiler->lvaGetParameterABIInfo(argLclNum); + for (const ABIPassingSegment& segment : abiInfo.Segments()) + { + if (segment.IsPassedInRegister()) + { + WasmValueType argType; + regNumber argReg = segment.GetRegister(); + unsigned argIndex = UnpackWasmReg(argReg, &argType); + indexBase = max(indexBase, argIndex + 1); + } + } + } + } + break; + + case FuncKind::FUNC_HANDLER: + case FuncKind::FUNC_FILTER: + { + assert(spVirtReg != REG_NA && fpVirtReg != REG_NA && spVirtReg != fpVirtReg); + EHblkDsc* const ehDsc = funcInfo->GetEHDesc(m_compiler); + + // Filter funclets take an additional argument for the exception object. Otherwise, + // the only args for a funclet should be (SP, FP) = (local 0, local 1) + indexBase = ehDsc->HasCatchHandler() ? 3 : 2; + } + + break; + + default: + unreached(); + } + + return indexBase; +} + +void WasmRegAlloc::AssignIntervals(jitstd::vector& intervals, PhysicalRegBank* regBankMap) +{ + jitstd::list* physRegPoolMap[static_cast(WasmValueType::Count)]{}; + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + physRegPoolMap[static_cast(type)] = + new (m_compiler->getAllocator(CMK_LSRA)) jitstd::list(m_compiler->getAllocator(CMK_LSRA)); + } + + auto releaseIntervalReg = [&](Interval* interval) { + assert(genIsValidReg(interval->physReg)); + WasmValueType type = WasmRegToType(interval->physReg); + physRegPoolMap[static_cast(type)]->push_back(interval->physReg); + }; + + auto numAvail = [&](WasmValueType type) { + return physRegPoolMap[static_cast(type)]->size(); + }; + + auto nextReg = [&](WasmValueType type) { + jitstd::list* regs = physRegPoolMap[static_cast(type)]; + assert(!regs->empty()); + regNumber reg = regs->front(); + regs->pop_front(); + return reg; + }; + + auto laterEnd = [](Interval* a, Interval* b) { + // Compare intervals by end first to expire old intervals earlier then by tracked index to break ties. + return (a->end != b->end) ? a->end > b->end : a->trackedIdx > b->trackedIdx; + }; + + PriorityQueue activeQueue(m_compiler->getAllocator(CMK_LSRA), laterEnd); + + auto expireOld = [&](Interval* current) { + while (activeQueue.Size() > 0 && activeQueue.Top()->end <= current->start) + { + JITDUMP("Expiring interval [%d, %d]:virtReg $%d\n", activeQueue.Top()->start, activeQueue.Top()->end, + WasmRegToIndex(activeQueue.Top()->virtReg)); + Interval* interval = activeQueue.Top(); + activeQueue.Pop(); + assert(genIsValidReg(interval->physReg)); + releaseIntervalReg(interval); + } + }; + + jitstd::sort(intervals.begin(), intervals.end(), [](Interval* a, Interval* b) { + // Sort intervals by start first to process earlier intervals first, then use tracked index to break ties. + return (a->start != b->start) ? a->start < b->start : a->trackedIdx < b->trackedIdx; + }); + + for (Interval* interval : intervals) + { + assert(interval->physReg == REG_NA && genIsValidReg(interval->virtReg)); + expireOld(interval); + WasmValueType type = WasmRegToType(interval->virtReg); + if (numAvail(type) == 0) + { + interval->physReg = + regBankMap[static_cast(type)].AllocPhysReg(interval->virtReg, /*relative=*/true); + } + else + { + interval->physReg = nextReg(type); + } + JITDUMP("Assigning (relative) reg for interval: [%d, %d]:virtReg $%d = $%d\n", interval->start, interval->end, + WasmRegToIndex(interval->virtReg), WasmRegToIndex(interval->physReg)); + + activeQueue.Push(interval); + } +} + //------------------------------------------------------------------------ // ResolveReferences: Translate virtual registers to physical ones (WASM locals). // @@ -1042,17 +1385,25 @@ void WasmRegAlloc::ResolveReferences() } } - struct PhysicalRegBank - { - unsigned DeclaredCount; - unsigned IndexBase; - unsigned Index; - }; - auto canReuseAbiReg = [](regNumber virtReg, regNumber abiReg) { return genIsValidReg(virtReg) && (WasmRegToType(virtReg) == WasmRegToType(abiReg)); }; + auto mergeAssignments = [&](int destIdx, int srcIdx) { + PerFuncletData* srcData = m_perFuncletData[srcIdx]; + PerFuncletData* destData = m_perFuncletData[destIdx]; + + for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++) + { + regNumber srcAssigned = srcData->m_physicalRegAssignments[i]; + regNumber destAssigned = destData->m_physicalRegAssignments[i]; + if (srcAssigned != REG_STK && destAssigned == REG_STK) + { + destData->m_physicalRegAssignments[i] = srcAssigned; + } + } + }; + // Resolve funclet by funclet, in reverse order, so that we process the main method region last. // for (FuncInfoDsc* const funcInfo : m_compiler->Funcs().Reverse()) @@ -1061,97 +1412,34 @@ void WasmRegAlloc::ResolveReferences() // m_currentFunclet = funcInfo->GetFuncletIdx(m_compiler); - PhysicalRegBank virtToPhysRegMap[static_cast(WasmValueType::Count)]; - for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) - { - VirtualRegStack& virtRegs = m_virtualRegs[static_cast(type)]; - PhysicalRegBank& physRegs = virtToPhysRegMap[static_cast(type)]; - physRegs.DeclaredCount = virtRegs.Count(); - } + PhysicalRegBank physRegMap[static_cast(WasmValueType::Count)]{}; - unsigned indexBase = 0; const bool inFunclet = funcInfo->funKind != FuncKind::FUNC_ROOT; PerFuncletData* const data = m_perFuncletData[m_currentFunclet]; regNumber const spVirtReg = data->m_spReg; regNumber const fpVirtReg = data->m_fpReg; + unsigned indexBase = ComputeIndexBase(funcInfo, spVirtReg, fpVirtReg); - switch (funcInfo->funKind) - { - case FuncKind::FUNC_ROOT: + auto isABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) { + if (virtReg == spVirtReg || virtReg == fpVirtReg) { - for (unsigned argLclNum = 0; argLclNum < m_compiler->info.compArgsCount; argLclNum++) - { - const ABIPassingInformation& abiInfo = m_compiler->lvaGetParameterABIInfo(argLclNum); - for (const ABIPassingSegment& segment : abiInfo.Segments()) - { - if (segment.IsPassedInRegister()) - { - WasmValueType argType; - regNumber argReg = segment.GetRegister(); - unsigned argIndex = UnpackWasmReg(argReg, &argType); - indexBase = max(indexBase, argIndex + 1); - - LclVarDsc* argVarDsc = m_compiler->lvaGetDesc(argLclNum); - if (canReuseAbiReg(argVarDsc->GetRegNum(), argReg) || - (argLclNum == m_compiler->lvaWasmSpArg)) - { - assert(abiInfo.HasExactlyOneRegisterSegment()); - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - - const ParameterRegisterLocalMapping* mapping = - m_compiler->FindParameterRegisterLocalMappingByRegister(argReg); - if ((mapping != nullptr) && - canReuseAbiReg(m_compiler->lvaGetDesc(mapping->LclNum)->GetRegNum(), argReg)) - { - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - } - } - } + return true; } - break; - - case FuncKind::FUNC_HANDLER: - case FuncKind::FUNC_FILTER: + if ((varDsc != nullptr) && varDsc->lvIsRegArg && !varDsc->lvIsStructField) { - // TODO-WASM: add ABI information for funclets? - // - WasmValueType argType = TypeToWasmValueType(TYP_I_IMPL); - - if (spVirtReg != REG_NA) - { - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - - if ((fpVirtReg != REG_NA) && (fpVirtReg != spVirtReg)) - { - virtToPhysRegMap[static_cast(argType)].DeclaredCount--; - } - - EHblkDsc* const ehDsc = funcInfo->GetEHDesc(m_compiler); - indexBase = ehDsc->HasCatchHandler() ? 3 : 2; + return true; } + if ((varDsc != nullptr) && varDsc->lvIsParamRegTarget) + { + return true; + } + return false; + }; - break; - - default: - unreached(); - } + auto allocABIReg = [&](regNumber virtReg, LclVarDsc* varDsc) { + assert(isABIReg(virtReg, varDsc)); - for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) - { - PhysicalRegBank& physRegs = virtToPhysRegMap[static_cast(type)]; - physRegs.IndexBase = indexBase; - physRegs.Index = indexBase; - indexBase += physRegs.DeclaredCount; - } - - // Allocate all our virtual registers to physical ones. - // - auto allocPhysReg = [&](regNumber virtReg, LclVarDsc* varDsc) { regNumber physReg = REG_NA; - if (!inFunclet) { // ABI registers in the main method @@ -1185,19 +1473,20 @@ void WasmRegAlloc::ResolveReferences() // ABI registers in the funclets if (virtReg == spVirtReg) { - physReg = MakeWasmReg(0, TypeToWasmValueType(TYP_I_IMPL)); + physReg = MakeWasmReg(0, TypeToWasmValueType(TYP_I_IMPL), /*relative=*/false); } else if (virtReg == fpVirtReg) { - physReg = MakeWasmReg(1, TypeToWasmValueType(TYP_I_IMPL)); + physReg = MakeWasmReg(1, TypeToWasmValueType(TYP_I_IMPL), /*relative=*/false); } } + // If we couldn't reuse a the ABI parameter register, allocate + // a new phys reg now if (physReg == REG_NA) { - WasmValueType type = WasmRegToType(virtReg); - unsigned physRegIndex = virtToPhysRegMap[static_cast(type)].Index++; - physReg = MakeWasmReg(physRegIndex, type); + physReg = physRegMap[static_cast(WasmRegToType(virtReg))].AllocPhysReg(virtReg, + /*relative=*/true); } assert(genIsValidReg(physReg)); @@ -1212,50 +1501,120 @@ void WasmRegAlloc::ResolveReferences() // if (spVirtReg != REG_NA) { - data->m_spReg = allocPhysReg(spVirtReg, m_compiler->lvaGetDesc(m_compiler->lvaWasmSpArg)); + data->m_spReg = allocABIReg(spVirtReg, m_compiler->lvaGetDesc(m_compiler->lvaWasmSpArg)); } if (fpVirtReg != REG_NA) { - data->m_fpReg = (spVirtReg == fpVirtReg) ? data->m_spReg : allocPhysReg(fpVirtReg, nullptr); + data->m_fpReg = (spVirtReg == fpVirtReg) ? data->m_spReg : allocABIReg(fpVirtReg, nullptr); } - // Do likewise for the enregistered locals. - // - // Note we do not update the LclVarDsc here. - // - // We will update the LclVarDsc at the end of this method to be the assignments - // for the main method. + // Allocate non-FP/SP param registers + for (unsigned lclNum = 0; lclNum < m_compiler->lvaCount; lclNum++) + { + LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum); + if (varDsc->lvIsRegCandidate()) + { + regNumber virtReg = varDsc->GetRegNum(); + assert(genIsValidReg(virtReg)); + if (virtReg == spVirtReg || virtReg == fpVirtReg) + { + continue; + } + + if (isABIReg(virtReg, varDsc)) + { + regNumber reg = allocABIReg(virtReg, varDsc); + assert(genIsValidReg(reg)); + } + } + } + + // At this point, physRegMap should reflect the declaration count necessary for any extra locals needed + // for ABI parameters. Each local index remains relative to the final IndexBase, which is unset at this point. + // We can't set it until we know how many locals we will actually need. Once we have the final local count, we + // will resolve the indices to their actual physical register assignments. // - // Then when codegen calls back to the allocator via recordVarLocationsAtStartOfBB - // we will either verify the assignments are correct for the block, or update them + // At the end of this method, we will update the LclVarDsc + // to be the assignments for the main method. Then when codegen calls back to the allocator via + // recordVarLocationsAtStartOfBB we will either verify the assignments are correct for the block, or update them // using the per-funclet mappings kept in the per-funclet m_physicalRegAssignments. // - for (unsigned varIndex = 0; varIndex < m_compiler->lvaTrackedCount; varIndex++) - { - unsigned lclNum = m_compiler->lvaTrackedIndexToLclNum(varIndex); - LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum); - if (lclNum == m_compiler->lvaWasmSpArg) + // Assign registers to intervals to assign homes for the enregistered locals + jitstd::vector intervals(m_compiler->getAllocator(CMK_LSRA)); + for (size_t i = 0; i < data->m_intervals.size(); i++) + { + if (data->m_intervals[i] != nullptr) { - // Allocation was handled above. + intervals.push_back(data->m_intervals[i]); } - else if (!varDsc->lvIsRegCandidate()) + } + AssignIntervals(intervals, physRegMap); + + for (Interval* interval : intervals) + { + assert(genIsValidReg(interval->physReg)); + PhysicalRegBank& physRegs = physRegMap[static_cast(WasmRegToType(interval->physReg))]; + data->m_physicalRegAssignments[interval->trackedIdx] = interval->physReg; + } + + // Allocate temporary regs to physical regs for each wasm value type + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; + for (unsigned i = 0; i < regs.Count; i++) { - continue; + regs.Regs[i] = physRegMap[static_cast(type)].AllocPhysReg(regs.Regs[i], /*relative=*/true); } - else + } + + // At this point, we know how many physical registers are needed for ABI + enregistered locals + + // temporary registers; We can now adjust the IndexBase for each local group to reflect the actual number of + // physical registers needed, and re-write the index-relative local indices to reflect the final physical + // register indices. + + for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) + { + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; + physRegs.IndexBase = indexBase; // iteration 0: pre-computed index base from the number of ABI registers + physRegs.Index += indexBase; + indexBase += physRegs.DeclaredCount; + } + + // Resolve relative local -> physical register assignments to their actual physical register indices. + for (unsigned i = 0; i < data->m_physicalRegAssignments.size(); i++) + { + if (genIsRelativeReg(data->m_physicalRegAssignments[i])) { - allocPhysReg(varDsc->GetRegNum(), varDsc); + WasmValueType type = WasmRegToType(data->m_physicalRegAssignments[i]); + data->m_physicalRegAssignments[i] = ResolveRegOffset(data->m_physicalRegAssignments[i], + physRegMap[static_cast(type)].IndexBase); } } + // Resolve SP and FP register relative offsets to their actual physical register indices if they haven't + // been adjusted already + if (data->m_spReg != REG_NA && genIsRelativeReg(data->m_spReg)) + { + data->m_spReg = + ResolveRegOffset(data->m_spReg, physRegMap[static_cast(WasmValueType::I)].IndexBase); + } + + if (data->m_fpReg != REG_NA && genIsRelativeReg(data->m_fpReg)) + { + data->m_fpReg = + ResolveRegOffset(data->m_fpReg, physRegMap[static_cast(WasmValueType::I)].IndexBase); + } + + // Resolve temporary register banks relative offsets to their actual physical register indices. for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; + TemporaryRegBank& regs = temporaryRegMap[static_cast(type)]; + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; for (unsigned i = 0; i < regs.Count; i++) { - regs.Regs[i] = allocPhysReg(regs.Regs[i], nullptr); + regs.Regs[i] = ResolveRegOffset(regs.Regs[i], physRegs.IndexBase); } } @@ -1294,6 +1653,7 @@ void WasmRegAlloc::ResolveReferences() if (physReg != REG_NA) { + assert(!genIsRelativeReg(physReg)); node->SetRegNum(physReg); } @@ -1326,7 +1686,7 @@ void WasmRegAlloc::ResolveReferences() for (WasmValueType type = WasmValueType::First; type < WasmValueType::Count; ++type) { - PhysicalRegBank& physRegs = virtToPhysRegMap[static_cast(type)]; + PhysicalRegBank& physRegs = physRegMap[static_cast(type)]; assert(physRegs.Index <= physRegs.IndexBase + physRegs.DeclaredCount); if (physRegs.DeclaredCount != 0) { @@ -1343,6 +1703,11 @@ void WasmRegAlloc::ResolveReferences() funcInfo->funWasmExnRefLocalIndex = indexBase; decls->push_back({WasmValueType::ExnRef, 1}); } + + // Copy any local -> reg mappings in this funclet to the root funclets if they don't exist there already. + // This allows us to ensure the root funclet knows about all reg assignments, + // even for locals which may not ever be used in the root funclet. + mergeAssignments(ROOT_FUNC_IDX, m_currentFunclet); } // Set all lcl var assignments to the main method's allocations. @@ -1355,6 +1720,7 @@ void WasmRegAlloc::ResolveReferences() if (genIsValidReg(assignedReg)) { + assert(!genIsRelativeReg(assignedReg)); varDsc->SetRegNum(mainFuncAssignment[varIndex]); // While register allocations are fixed per-funclet, they are unlikely diff --git a/src/coreclr/jit/regallocwasm.h b/src/coreclr/jit/regallocwasm.h index 07863cc2fccadd..bb8e5d3083ad5d 100644 --- a/src/coreclr/jit/regallocwasm.h +++ b/src/coreclr/jit/regallocwasm.h @@ -73,6 +73,26 @@ struct VirtualRegReferences VirtualRegReferences* Prev = nullptr; }; +struct Interval +{ + int start; + int end; + regNumber virtReg; + unsigned trackedIdx; + + // Assigned later by the allocator + regNumber physReg; + + Interval(regNumber virtReg, unsigned trackedIdx) + : start(INT_MAX) + , end(INT_MIN) + , virtReg(virtReg) + , trackedIdx(trackedIdx) + , physReg(REG_NA) + { + } +}; + class WasmRegAlloc : public RegAllocInterface { Compiler* m_compiler; @@ -93,6 +113,7 @@ class WasmRegAlloc : public RegAllocInterface , m_lastVirtualRegRefsCount(0) , m_virtualRegRefs(nullptr) , m_physicalRegAssignments(comp->lvaTrackedCount, REG_STK, comp->getAllocator(CMK_LSRA)) + , m_intervals(comp->lvaTrackedCount, nullptr, comp->getAllocator(CMK_LSRA)) { } @@ -114,6 +135,9 @@ class WasmRegAlloc : public RegAllocInterface // Map from local tracked index to phys reg for that local, in this funclet. // jitstd::vector m_physicalRegAssignments; + + // Map from local tracked index to live interval for this local, in this funclet + jitstd::vector m_intervals; }; jitstd::vector m_perFuncletData; @@ -130,10 +154,28 @@ class WasmRegAlloc : public RegAllocInterface #endif // TRACK_LSRA_STATS bool isRegCandidate(LclVarDsc* varDsc); + bool isIntervalCandidate(LclVarDsc* varDsc, PerFuncletData* funcletData); bool isContainableMemoryOp(GenTree* node); void checkForDNER(unsigned lclNum, LclVarDsc* varDsc); private: + struct PhysicalRegBank + { + unsigned DeclaredCount; + unsigned IndexBase; + unsigned Index; + + // Create a new phys reg in the regbank for the given virtReg + regNumber AllocPhysReg(regNumber virtReg, bool relative) + { + WasmValueType type = WasmRegToType(virtReg); + unsigned physRegIndex = Index++; + DeclaredCount++; + regNumber physReg = MakeWasmReg(physRegIndex, type, relative); + return physReg; + } + }; + LIR::Range& CurrentRange(); void IdentifyCandidates(); @@ -167,7 +209,13 @@ class WasmRegAlloc : public RegAllocInterface regNumber RequestInternalRegister(GenTree* node, var_types type); void ConsumeTemporaryRegForOperand(GenTree* operand DEBUGARG(const char* reason)); + void BuildIntervals(); + unsigned int ComputeIndexBase(FuncInfoDsc* funcInfo, regNumber spVirtReg, regNumber fpVirtReg); + void BuildFuncIntervals(FuncInfoDsc* funcInfo, PerFuncletData* funcletData); + void DumpIntervals(); + void ResolveReferences(); + void AssignIntervals(jitstd::vector& intervals, PhysicalRegBank* regBankByType); void PublishAllocationResults(); }; diff --git a/src/coreclr/jit/registeropswasm.cpp b/src/coreclr/jit/registeropswasm.cpp index 112520dd9928b1..841bd81b97b342 100644 --- a/src/coreclr/jit/registeropswasm.cpp +++ b/src/coreclr/jit/registeropswasm.cpp @@ -8,9 +8,12 @@ using RegNumUnderlyingType = regNumberSmall; static const RegNumUnderlyingType WASM_REG_TYPE_BITS = 3; +static const RegNumUnderlyingType WASM_REG_REL_BITS = 1; static const RegNumUnderlyingType WASM_REG_TYPE_SHIFT = 8 * sizeof(RegNumUnderlyingType) - WASM_REG_TYPE_BITS; +static const RegNumUnderlyingType WASM_REG_REL_SHIFT = WASM_REG_TYPE_SHIFT - WASM_REG_REL_BITS; static const RegNumUnderlyingType WASM_REG_TYPE_MASK = ~0u << WASM_REG_TYPE_SHIFT; -static const unsigned WASM_LOCAL_INDEX_LIMIT = WASM_REG_TYPE_MASK; +static const RegNumUnderlyingType WASM_REG_REL_MASK = ((1u << WASM_REG_REL_BITS) - 1) << WASM_REG_REL_SHIFT; +static const unsigned WASM_LOCAL_INDEX_LIMIT = WASM_REG_REL_MASK - 1; static_assert(sizeof(RegNumUnderlyingType) >= sizeof(unsigned)); static_assert(((static_cast(WasmValueType::Count) - 1) >> WASM_REG_TYPE_BITS) == 0); @@ -20,15 +23,24 @@ static_assert(((static_cast(WasmValueType::Count) - 1) >> // // Arguments: // index - The index of the WASM local -// type - Its type, must be directly mappable to the WASM type system +// type - Its type +// isRelative - Whether the index is relative to some base (default: false) // // Return Value: // 'regNumber' representing a tuple of '(index, type)'. // -regNumber MakeWasmReg(unsigned index, var_types type) +regNumber MakeWasmReg(unsigned index, WasmValueType type, bool isRelative) { - WasmValueType wasmType = TypeToWasmValueType(type); - return MakeWasmReg(index, wasmType); + assert((WasmValueType::Invalid < type) && (type < WasmValueType::Count)); + + // WASM engines have a much smaller limit on the number of locals (50K) than this. + if ((index & WASM_REG_TYPE_MASK) != 0) + { + IMPL_LIMITATION("Too many locals"); + } + RegNumUnderlyingType regValue = index | (isRelative ? (1u << WASM_REG_REL_SHIFT) : 0) | + (static_cast(type) << WASM_REG_TYPE_SHIFT); + return static_cast(regValue); } //------------------------------------------------------------------------ @@ -36,22 +48,20 @@ regNumber MakeWasmReg(unsigned index, var_types type) // // Arguments: // index - The index of the WASM local -// type - Its type +// type - Its type, must be directly mappable to the WASM type system +// isRelative - Whether the index is relative to a base (default: false) // // Return Value: // 'regNumber' representing a tuple of '(index, type)'. // -regNumber MakeWasmReg(unsigned index, WasmValueType type) +// Notes: +// isRelative is only used by the wasm register allocator to indicate whether a local +// is relative to an index base. This is because we don't know the exact final counts of locals while allocating. +// It has no effect on the actual encoding of the register number outside the allocator. +regNumber MakeWasmReg(unsigned index, var_types type, bool isRelative) { - assert((WasmValueType::Invalid < type) && (type < WasmValueType::Count)); - - // WASM engines have a much smaller limit on the number of locals (50K) than this. - if ((index & WASM_REG_TYPE_MASK) != 0) - { - IMPL_LIMITATION("Too many locals"); - } - RegNumUnderlyingType regValue = index | (static_cast(type) << WASM_REG_TYPE_SHIFT); - return static_cast(regValue); + WasmValueType wasmType = TypeToWasmValueType(type); + return MakeWasmReg(index, wasmType, isRelative); } //------------------------------------------------------------------------ @@ -174,7 +184,22 @@ unsigned UnpackWasmReg(regNumber reg, WasmValueType* pType) { *pType = static_cast(regValue >> WASM_REG_TYPE_SHIFT); } - return regValue & ~WASM_REG_TYPE_MASK; + return regValue & ~WASM_REG_TYPE_MASK & ~WASM_REG_REL_MASK; +} + +bool genIsRelativeReg(regNumber reg) +{ + RegNumUnderlyingType regValue = static_cast(reg); + return (regValue & WASM_REG_REL_MASK) != 0; +} + +regNumber ResolveRegOffset(regNumber reg, unsigned offset) +{ + assert(genIsRelativeReg(reg)); + WasmValueType type; + unsigned index = UnpackWasmReg(reg, &type); + index += offset; + return MakeWasmReg(index, type, false); } //------------------------------------------------------------------------ @@ -244,6 +269,11 @@ const char* getRegName(regNumber reg) return "NA"; } + if (reg == REG_STK) + { + return "STK"; + } + // TODO-Wasm: remove this hardcoded list workaround by refactoring this API. // clang-format off static const char* const s_names[] = { diff --git a/src/coreclr/jit/registeropswasm.h b/src/coreclr/jit/registeropswasm.h index 6c12d31a6003d8..0ce83a6f394d13 100644 --- a/src/coreclr/jit/registeropswasm.h +++ b/src/coreclr/jit/registeropswasm.h @@ -25,14 +25,16 @@ inline WasmValueType& operator++(WasmValueType& type) return type = static_cast(static_cast(type) + 1); } -regNumber MakeWasmReg(unsigned index, var_types type); -regNumber MakeWasmReg(unsigned index, WasmValueType type); +regNumber MakeWasmReg(unsigned index, var_types type, bool relative = false); +regNumber MakeWasmReg(unsigned index, WasmValueType type, bool relative = false); +regNumber ResolveRegOffset(regNumber reg, unsigned offset); WasmValueType TypeToWasmValueType(var_types type); WasmValueType ActualTypeToWasmValueType(var_types type); const char* WasmValueTypeName(WasmValueType type); unsigned UnpackWasmReg(regNumber reg, WasmValueType* pType = nullptr); unsigned WasmRegToIndex(regNumber reg); WasmValueType WasmRegToType(regNumber reg); +bool genIsRelativeReg(regNumber reg); bool genIsValidReg(regNumber reg); bool genIsValidIntReg(regNumber reg); bool genIsValidIntOrFakeReg(regNumber reg); diff --git a/src/tests/JIT/Directed/Directed_1.csproj b/src/tests/JIT/Directed/Directed_1.csproj index 3e258f1253cd89..40ba526f2f39ea 100644 --- a/src/tests/JIT/Directed/Directed_1.csproj +++ b/src/tests/JIT/Directed/Directed_1.csproj @@ -18,6 +18,7 @@ + diff --git a/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs new file mode 100644 index 00000000000000..aae471d357d78c --- /dev/null +++ b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.cs @@ -0,0 +1,469 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; +using Xunit; + +public class WasmRegalloc +{ + private sealed class Box + { + public Box Next; + public int A; + public int B; + } + + private struct SingleFloat + { + public float Value; + } + + [Theory] + [InlineData(1, 0)] + [InlineData(5, 4)] + [InlineData(10, 8)] + [InlineData(-3, 0)] + [InlineData(0, 0)] + public static void ConditionalBackedge(int n, int expected) + { + if (n == 0) + { + Assert.Throws(() => ConditionalBackedgeMultiUse(n)); + } + else + { + Assert.Equal(expected, ConditionalBackedgeMultiUse(n)); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int ConditionalBackedgeMultiUse(int n) + { + int sum = 0; + for (int i = 0; i < n; i++) + { + sum += i; + } + + int result = sum / n; + return result + result; + } + + [Theory] + [InlineData(4, 7, 28)] + [InlineData(-4, -7, 28)] + [InlineData(-4, 7, int.MaxValue)] + [InlineData(int.MaxValue, 1, int.MaxValue)] + [InlineData(46341, 46341, int.MaxValue)] + [InlineData(int.MinValue, -1, int.MaxValue)] + public static void CheckedConversion(int a, int b, int expected) + { + Assert.Equal(expected, EHNonEH(a, b)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int EHNonEH(int a, int b) + { + uint value; + try + { + value = checked((uint)(a * b)); + } + catch (OverflowException) + { + return int.MaxValue; + } + + return (int)value; + } + + [Theory] + [InlineData(0, false, 23)] + [InlineData(1, false, 40)] + [InlineData(2, false, 57)] + [InlineData(1, true, 34)] + public static void ContainedTree(int index, bool alias, int expected) + { + Box first = new Box { A = 17, B = -1 }; + Box second = alias ? first : new Box { A = 23, B = -2 }; + first.Next = second; + Box[] boxes = { first, first, first }; + Assert.Equal(expected, CandidateInContainedTree(boxes, index)); + Assert.Equal(expected, second.B); + Assert.Equal(17, first.A); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int CandidateInContainedTree(Box[] boxes, int k) + { + Box p = boxes[k]; + Box q = p.Next; + int a = p.A; + q.B = a * k + q.A; + return q.B; + } + + [Theory] + [InlineData(0, 0)] + [InlineData(5, 50)] + [InlineData(-7, 98)] + public static void ContainedStore(int seed, int expected) + { + Box sentinel = new Box { B = -1 }; + Box destination = new Box { B = -2 }; + StoreCandidate(new Box[] { sentinel, destination }, 1, seed); + Assert.Equal(expected, destination.B); + Assert.Equal(-1, sentinel.B); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void StoreCandidate(Box[] boxes, int index, int seed) + { + Box destination = boxes[index]; + // The CSE definition on the RHS must not reuse the still-needed store base. + destination.B = checked(seed * seed + seed * seed); + } + + [Theory] + [InlineData(41, 5, 8)] + [InlineData(-41, 5, -8)] + [InlineData(int.MinValue, 1, int.MinValue)] + [InlineData(int.MinValue, -1, 0)] + [InlineData(1, 0, 0)] + public static void SignedDivision(int numerator, int denominator, int quotient) + { + if (denominator == 0) + { + Assert.Throws(() => DivideCandidate(numerator, denominator)); + } + else if (denominator == -1 && numerator == int.MinValue) + { + Assert.Throws(() => DivideCandidate(numerator, denominator)); + } + else + { + Assert.Equal(quotient, DivideCandidate(numerator, denominator)); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int DivideCandidate(int numerator, int denominator) + { + int divisor = Opaque(denominator); + int dividend = Opaque(numerator); + return dividend / divisor; + } + + [Theory] + [InlineData(11, 101L, 1.5f, 2.25, 262.75)] + [InlineData(-5, -11L, -1.5f, 0.25, 1.75)] + public static void ABIHomeRetention(int i, long l, float f, double d, double expected) + { + int home = 7; + Box box = new Box { A = 3, B = 5 }; + Assert.Equal(expected, RetainABIHomes(i, l, f, d, box, ref home)); + Assert.Equal(12, home); + Assert.Equal(f + i, RetainPromotedHome(new SingleFloat { Value = f }, i)); + Assert.Equal(2 * (i + 13), AddressExposedHome(i)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static double RetainABIHomes(int i, long l, float f, double d, Box box, ref int home) + { + i += box.A; + l += home; + f += i; + d += l; + home += box.B; + return Opaque(i) + l + f + d + home + box.A; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static float RetainPromotedHome(SingleFloat value, int delta) + { + return value.Value + Opaque(delta); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int AddressExposedHome(int argument) + { + Mutate(ref argument); + return argument + Opaque(argument); + } + + [Theory] + [InlineData(0, 25004)] + [InlineData(1, 134124)] + [InlineData(2, 29145)] + [InlineData(3, 53034)] + public static void FuncletHomes(int scenario, int expected) + { + Assert.Equal(expected, MultipleFunclets(scenario)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int MultipleFunclets(int scenario) + { + int shared = Opaque(17); + int trace = 0; + try + { + try + { + ThrowForScenario(scenario); + shared += Opaque(3); + } + catch (DivideByZeroException) when (CheckFilter(scenario, ref trace)) + { + int a = Opaque(11); + long b = Opaque(101L); + shared += a + (int)b; + trace = trace * 10 + 2; + } + catch (OverflowException) + { + float c = Opaque(13.5f); + double d = Opaque(17.5); + shared += (int)(c + d); + trace = trace * 10 + 3; + } + finally + { + shared += Opaque(5); + trace = trace * 10 + 4; + } + } + catch (DivideByZeroException) + { + shared += Opaque(7); + trace = trace * 10 + 5; + } + + return shared * 1000 + trace; + } + + [Theory] + [InlineData(3, 2, 45, 69)] + [InlineData(-5, 7, 29, 34)] + [InlineData(11, 32, 61, 139)] + public static void FrameHomes(int seed, int length, int fixedExpected, int dynamicExpected) + { + Assert.Equal(fixedExpected, FixedFrame(seed)); + Assert.Equal(dynamicExpected, DynamicFrame(seed, length)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int FixedFrame(int seed) + { + int home = seed; + Mutate(ref home); + int saved = Opaque(home); + Mutate(ref home); + return saved + home; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int DynamicFrame(int seed, int length) + { + ArgumentOutOfRangeException.ThrowIfLessThan(length, 2); + ArgumentOutOfRangeException.ThrowIfGreaterThan(length, 32); + int home = seed; + Mutate(ref home); + Span buffer = stackalloc int[length]; + for (int i = 0; i < buffer.Length; i++) + { + buffer[i] = home + i; + } + + int saved = Opaque(home); + buffer[0] += Opaque(seed + 1); + return saved + buffer[0] + buffer[length - 1] + home; + } + + [Theory] + [InlineData(0, 2, 69364)] + [InlineData(0, 32, 69364)] + [InlineData(1, 2, 190484)] + [InlineData(1, 7, 190484)] + [InlineData(2, 7, 215584)] + [InlineData(3, 2, 91705)] + [InlineData(3, 32, 91705)] + public static void DynamicFuncletHomes(int scenario, int length, int expected) + { + Assert.Equal(expected, MultipleFuncletsLocalloc(scenario, length)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int MultipleFuncletsLocalloc(int scenario, int length) + { + ArgumentOutOfRangeException.ThrowIfLessThan(length, 2); + ArgumentOutOfRangeException.ThrowIfGreaterThan(length, 32); + Span buffer = stackalloc int[length]; + buffer[0] = 11; + buffer[length - 1] = 23; + int shared = Opaque(19); + int trace = 0; + try + { + try + { + buffer[0] += Opaque(scenario); + ThrowForScenario(scenario); + shared += buffer[length - 1]; + } + catch (DivideByZeroException) + { + int a = Opaque(buffer[0]); + int b = Opaque(shared); + shared = a * a + b; + trace = 2; + } + finally + { + buffer[length - 1] += Opaque(3); + shared += buffer[length - 1]; + trace = trace * 10 + 4; + } + } + catch (OverflowException) + { + long value = Opaque((long)shared); + shared = (int)(value * 2); + trace = trace * 10 + 5; + } + + return shared * 1000 + buffer[0] * 100 + buffer[length - 1] * 10 + trace; + } + + [Theory] + [InlineData(3, 103, 72, 115, -53, 261.5)] + [InlineData(-5, 671, -72, -5, -77, 197.5)] + public static void IntervalBoundaries( + int seed, int disjointExpected, int overlapExpected, int firstExpected, int secondExpected, double banksExpected) + { + Assert.Equal(disjointExpected, DisjointIntervals(seed)); + Assert.Equal(overlapExpected, OverlappingIntervals(seed)); + Assert.Equal(firstExpected, BranchIntervals(seed, true)); + Assert.Equal(secondExpected, BranchIntervals(seed, false)); + Assert.Equal(banksExpected, TypedIntervals(seed)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int DisjointIntervals(int seed) + { + int a = Opaque(seed); + int b = a * a + 1; + return b * b + Opaque(seed); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int OverlappingIntervals(int seed) + { + int a = Opaque(seed); + int b = Opaque(seed + 1); + int c = a * a + b; + int d = Opaque(seed + 2); + return c * d + a + b; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int BranchIntervals(int seed, bool first) + { + int a = Opaque(seed); + int b = first ? Opaque(a + 5) : Opaque(a - 7); + int c = Opaque(seed + 11); + return a + b * c; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static double TypedIntervals(int seed) + { + int a = Opaque(seed); + long b = Opaque(seed + 101L); + float c = Opaque(seed + 0.5f); + double d = Opaque(seed + 0.25); + int a2 = Opaque(a + 7); + long b2 = Opaque(b + 11); + float c2 = Opaque(c + 3); + double d2 = Opaque(d + 13); + return a + a2 + b + b2 + c + c2 + d + d2; + } + + [Theory] + [InlineData(0, 58)] + [InlineData(1, 173)] + [InlineData(2, 248)] + [InlineData(3, 456)] + [InlineData(4, 757)] + public static void BackedgeIntervals(int count, int expected) + { + Assert.Equal(expected, LoopIntervals(count)); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int LoopIntervals(int count) + { + int left = Opaque(3); + int right = Opaque(7); + for (int i = 0; i < count; i++) + { + int next = Opaque(left + i); + left = right + next; + right = next - i; + } + + return left * 17 + right; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool CheckFilter(int scenario, ref int trace) + { + trace = trace * 10 + 1; + return (scenario & 1) != 0; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ThrowForScenario(int scenario) + { + if (scenario is 1 or 2) + { + throw new DivideByZeroException(); + } + + if (scenario == 3) + { + throw new OverflowException(); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Mutate(ref int value) + { + value += 13; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static int Opaque(int value) + { + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static long Opaque(long value) + { + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static float Opaque(float value) + { + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static double Opaque(double value) + { + return value; + } +} diff --git a/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj new file mode 100644 index 00000000000000..be9a80a20865e4 --- /dev/null +++ b/src/tests/JIT/Directed/WasmRegalloc/WasmRegalloc.csproj @@ -0,0 +1,9 @@ + + + true + 1 + + + + +