Skip to content

Commit

Permalink
String concat const folding
Browse files Browse the repository at this point in the history
  • Loading branch information
ike709 committed Oct 25, 2024
1 parent b974c59 commit d285143
Show file tree
Hide file tree
Showing 3 changed files with 32 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 @@ -254,13 +254,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 @@ -249,6 +249,10 @@ public void SetLocation(Location loc) {
public Location GetLocation() {
return Location;
}

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

internal sealed class AnnotatedBytecodeArgumentType : IAnnotatedBytecode {
Expand Down
28 changes: 28 additions & 0 deletions DMCompiler/Optimizer/PeepholeOptimizations.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using DMCompiler.Bytecode;
using DMCompiler.DM;

namespace DMCompiler.Optimizer;

Expand Down Expand Up @@ -678,6 +679,33 @@ public void Apply(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(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 = DMObjectTree.AddString(firstString.ResolveString() + secondString.ResolveString());

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 d285143

Please sign in to comment.