Skip to content

Commit

Permalink
Removed unused regs
Browse files Browse the repository at this point in the history
  • Loading branch information
LPeter1997 committed Oct 12, 2023
1 parent 5588b09 commit d2aaa51
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
11 changes: 10 additions & 1 deletion src/Draco.Compiler/Internal/Codegen/CilCodegen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public CilCodegen(MetadataCodegen metadataCodegen, IProcedure procedure)
private int? GetRegisterIndex(Register register)
{
if (SymbolEqualityComparer.Default.Equals(register.Type, IntrinsicSymbols.Unit)) return null;
if (this.stackifier.RegisterUses[register] == 0) return null;
if (!this.allocatedRegisters.TryGetValue(register, out var allocatedRegister))
{
// NOTE: We need to offset by the number of locals
Expand Down Expand Up @@ -484,7 +485,15 @@ private void StoreRegister(Register register)
if (this.treeDepth > 0) return;

var index = this.GetRegisterIndex(register);
if (index is null) return;
if (index is null)
{
if (!SymbolEqualityComparer.Default.Equals(register.Type, IntrinsicSymbols.Unit))
{
// Need to pop
this.InstructionEncoder.OpCode(ILOpCode.Pop);
}
return;
}
this.InstructionEncoder.StoreLocal(index.Value);
}

Expand Down
17 changes: 12 additions & 5 deletions src/Draco.Compiler/Internal/OptimizingIr/Stackifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,25 @@ private static ImmutableDictionary<Register, int> CountRegisterUses(IEnumerable<
return registerUses.ToImmutable();
}

/// <summary>
/// A dictionary for the number of register uses for each register.
/// </summary>
public ImmutableDictionary<Register, int> RegisterUses { get; }

private readonly IProcedure procedure;
private readonly ImmutableDictionary<Register, int> registerUses;

public Stackifier(IProcedure procedure)
{
this.procedure = procedure;
var instructions = procedure.BasicBlocks.Values.SelectMany(bb => bb.Instructions);
// Count the number of register uses
this.registerUses = CountRegisterUses(instructions);
this.RegisterUses = CountRegisterUses(instructions);
}

// TODO: Doc
/// <summary>
/// Stackifies the given basic block.
/// </summary>
/// <param name="basicBlock">The basic block to stackify.</param>
/// <returns>The new, stackified array of instructions.</returns>
public ImmutableArray<IInstruction> Stackify(IBasicBlock basicBlock)
{
if (!this.procedure.BasicBlocks.Values.Contains(basicBlock))
Expand Down Expand Up @@ -80,7 +87,7 @@ public ImmutableArray<IInstruction> Stackify(IBasicBlock basicBlock)
// If we have a single-use register as a result immediately before this instruction,
// all good, part of the tree
if (!stopped
&& this.registerUses[reg] == 1
&& this.RegisterUses[reg] == 1
&& instrIterator.Prev is IValueInstruction valueInstr
&& valueInstr.Target == reg)
{
Expand Down

0 comments on commit d2aaa51

Please sign in to comment.