Skip to content

Commit

Permalink
String concat const folding (#2061)
Browse files Browse the repository at this point in the history
Co-authored-by: ike709 <[email protected]>
Co-authored-by: wixoa <[email protected]>
  • Loading branch information
3 people authored Nov 17, 2024
1 parent 9e1a9e6 commit 46b206a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 7 deletions.
7 changes: 0 additions & 7 deletions DMCompiler/DM/Builders/DMASTFolder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,6 @@ private DMASTExpression FoldExpression(DMASTExpression? expression) {

break;
}
case DMASTAdd add: {
DMASTConstantString? lhsString = add.LHS as DMASTConstantString;
DMASTConstantString? rhsString = add.RHS as DMASTConstantString;
if (lhsString != null && rhsString != null) return new DMASTConstantString(expression.Location, lhsString.Value + rhsString.Value);

break;
}

#endregion Math

Expand Down
4 changes: 4 additions & 0 deletions DMCompiler/Optimizer/AnnotatedBytecode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ public void SetLocation(Location loc) {
public Location GetLocation() {
return Location;
}

public string ResolveString(DMCompiler compiler) {
return compiler.DMObjectTree.StringTable[Id];
}
}

internal sealed class AnnotatedBytecodeArgumentType(DMCallArgumentsType value, Location location) : IAnnotatedBytecode {
Expand Down
27 changes: 27 additions & 0 deletions DMCompiler/Optimizer/PeepholeOptimizations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,33 @@ public void Apply(DMCompiler compiler, List<IAnnotatedBytecode> input, int index
}
}

// PushString [constant]
// PushString [constant]
// Add
// -> PushString [result]
internal sealed class ConstFoldAddStrings : IPeepholeOptimization {
public ReadOnlySpan<DreamProcOpcode> GetOpcodes() {
return [
DreamProcOpcode.PushString,
DreamProcOpcode.PushString,
DreamProcOpcode.Add,
];
}

public void Apply(DMCompiler compiler, List<IAnnotatedBytecode> input, int index) {
var firstInstruction = (AnnotatedBytecodeInstruction)input[index];
var firstString = firstInstruction.GetArg<AnnotatedBytecodeString>(0);
var secondString = ((AnnotatedBytecodeInstruction)input[index+1]).GetArg<AnnotatedBytecodeString>(0);

var combinedId = compiler.DMObjectTree.AddString(firstString.ResolveString(compiler) + secondString.ResolveString(compiler)); // TODO: Currently doesn't handle removing strings from the string tree that have no other references

var args = new List<IAnnotatedBytecode>(1) {new AnnotatedBytecodeString(combinedId, firstInstruction.Location)};

IPeepholeOptimization.ReplaceInstructions(input, index, 3,
new AnnotatedBytecodeInstruction(DreamProcOpcode.PushString, 1, args));
}
}

// PushFloat [constant]
// PushFloat [constant]
// Subtract
Expand Down

0 comments on commit 46b206a

Please sign in to comment.