Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReplaceJumpWithRet #1159

Merged
merged 4 commits into from
Sep 8, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,11 @@ internal void Compile()
try
{
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
(nef, manifest, debugInfo) = Reachability.RemoveUncoveredInstructions(nef, manifest, debugInfo.Clone() as JObject);
(nef, manifest, debugInfo) = Reachability.RemoveUnnecessaryJumps(nef, manifest, debugInfo!.Clone() as JObject);
(nef, manifest, debugInfo) = Reachability.ReplaceJumpWithRet(nef, manifest, debugInfo!.Clone() as JObject);
(nef, manifest, debugInfo) = Reachability.RemoveUncoveredInstructions(nef, manifest, debugInfo!.Clone() as JObject);
(nef, manifest, debugInfo) = Reachability.RemoveUnnecessaryJumps(nef, manifest, debugInfo!.Clone() as JObject);
(nef, manifest, debugInfo) = Reachability.ReplaceJumpWithRet(nef, manifest, debugInfo!.Clone() as JObject);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public static (NefFile, ContractManifest, JObject?) BuildOptimizedAssets(
System.Collections.Specialized.OrderedDictionary simplifiedInstructionsToAddress,
Dictionary<Instruction, Instruction> jumpSourceToTargets,
Dictionary<Instruction, (Instruction, Instruction)> trySourceToTargets,
Dictionary<int, Instruction> oldAddressToInstruction)
Dictionary<int, Instruction> oldAddressToInstruction,
Dictionary<int, int>? oldSequencePointAddressToNew = null)
{
nef.Script = OptimizedScriptBuilder.BuildScriptWithJumpTargets(
simplifiedInstructionsToAddress,
Expand All @@ -36,7 +37,9 @@ public static (NefFile, ContractManifest, JObject?) BuildOptimizedAssets(
nef.CheckSum = NefFile.ComputeChecksum(nef);
foreach (ContractMethodDescriptor method in manifest.Abi.Methods)
method.Offset = (int)simplifiedInstructionsToAddress[oldAddressToInstruction[method.Offset]]!;
debugInfo = DebugInfoBuilder.ModifyDebugInfo(debugInfo, simplifiedInstructionsToAddress, oldAddressToInstruction);
debugInfo = DebugInfoBuilder.ModifyDebugInfo(
debugInfo, simplifiedInstructionsToAddress, oldAddressToInstruction,
oldSequencePointAddressToNew: oldSequencePointAddressToNew);
return (nef, manifest, debugInfo);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ static class DebugInfoBuilder
/// <returns></returns>
public static JObject? ModifyDebugInfo(JObject? debugInfo,
System.Collections.Specialized.OrderedDictionary simplifiedInstructionsToAddress,
Dictionary<int, Instruction> oldAddressToInstruction)
Dictionary<int, Instruction> oldAddressToInstruction,
Dictionary<int, int>? oldSequencePointAddressToNew = null)
{
if (debugInfo == null) return null;
//Dictionary<int, (int docId, int startLine, int startCol, int endLine, int endCol)> newAddrToSequencePoint = new();
Expand Down Expand Up @@ -58,6 +59,12 @@ static class DebugInfoBuilder
newSequencePoints.Add(new JString($"{startInstructionAddress}{sequencePointGroups[2]}"));
previousSequencePoint = startInstructionAddress;
}
else if (oldSequencePointAddressToNew != null
&& oldSequencePointAddressToNew.TryGetValue(startInstructionAddress, out int newStartInstructionAddress))
{
newSequencePoints.Add(new JString($"{newStartInstructionAddress}{sequencePointGroups[2]}"));
previousSequencePoint = startInstructionAddress;
}
else
newSequencePoints.Add(new JString($"{previousSequencePoint}{sequencePointGroups[2]}"));
}
Expand Down
78 changes: 76 additions & 2 deletions src/Neo.Compiler.CSharp/Optimizer/Strategies/Reachability.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace Neo.Optimizer
{
static class Reachability
{
[Strategy(Priority = int.MaxValue)]
[Strategy(Priority = int.MaxValue - 16)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a brief comment to explain what 16 means here would be great

Copy link
Contributor Author

@Hecate2 Hecate2 Sep 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It means nothing. Just reserving spaces for other optimizers. We are not even using the Strategy attribute now. In the future we may sort all the [Strategy] methods and execute them (cyclically) ordered by Priority.

public static (NefFile, ContractManifest, JObject?) RemoveUncoveredInstructions(NefFile nef, ContractManifest manifest, JObject? debugInfo = null)
{
InstructionCoverage oldContractCoverage = new InstructionCoverage(nef, manifest);
Expand Down Expand Up @@ -63,7 +63,7 @@ public static Dictionary<int, BranchType>
/// <param name="manifest"></param>
/// <param name="debugInfo"></param>
/// <returns></returns>
[Strategy(Priority = int.MaxValue - 16)]
[Strategy(Priority = int.MaxValue)]
public static (NefFile, ContractManifest, JObject?) RemoveUnnecessaryJumps(NefFile nef, ContractManifest manifest, JObject? debugInfo = null)
{
Script script = nef.Script;
Expand Down Expand Up @@ -118,5 +118,79 @@ public static (NefFile, ContractManifest, JObject?) RemoveUnnecessaryJumps(NefFi
jumpSourceToTargets, trySourceToTargets,
oldAddressToInstruction);
}

/// <summary>
/// If a JMP or JMP_L jumps to a RET, replace the JMP with RET
/// </summary>
/// <param name="nef"></param>
/// <param name="manifest"></param>
/// <param name="debugInfo"></param>
/// <returns></returns>
[Strategy(Priority = int.MaxValue - 4)]
public static (NefFile, ContractManifest, JObject?) ReplaceJumpWithRet(NefFile nef, ContractManifest manifest, JObject? debugInfo = null)
{
Script script = nef.Script;
List<(int a, Instruction i)> oldAddressAndInstructionsList = script.EnumerateInstructions().ToList();
Dictionary<int, Instruction> oldAddressToInstruction = new();
foreach ((int a, Instruction i) in oldAddressAndInstructionsList)
oldAddressToInstruction.Add(a, i);
(Dictionary<Instruction, Instruction> jumpSourceToTargets,
Dictionary<Instruction, (Instruction, Instruction)> trySourceToTargets,
Dictionary<Instruction, HashSet<Instruction>> jumpTargetToSources) =
FindAllJumpAndTrySourceToTargets(oldAddressAndInstructionsList);
Dictionary<int, int> oldSequencePointAddressToNew = new();

System.Collections.Specialized.OrderedDictionary simplifiedInstructionsToAddress = new();
int currentAddress = 0;
foreach ((int a, Instruction i) in oldAddressAndInstructionsList)
{
if (unconditionalJump.Contains(i.OpCode))
{
int target = ComputeJumpTarget(a, i);
if (!oldAddressToInstruction.TryGetValue(target, out Instruction? dstRet))
throw new BadScriptException($"Bad {nameof(oldAddressToInstruction)}. No target found for {i} jumping from {a} to {target}");
if (dstRet.OpCode == OpCode.RET)
{
oldSequencePointAddressToNew[a] = currentAddress;
// handle the reference of the deleted JMP
jumpSourceToTargets.Remove(i);
jumpTargetToSources[dstRet].Remove(i);
if (jumpTargetToSources[dstRet].Count == 0)
jumpTargetToSources.Remove(dstRet);
// handle the reference of the added RET
Instruction newRet = new Script(new byte[] { (byte)OpCode.RET }).GetInstruction(0);
// above is a workaround of new Instruction(OpCode.RET)
if (jumpTargetToSources.TryGetValue(i, out HashSet<Instruction>? othersJumpingToCurrentJmp))
{
foreach (Instruction iJumpingToCurrentRet in othersJumpingToCurrentJmp)
{
if (SingleJumpInOperand(iJumpingToCurrentRet))
jumpSourceToTargets[iJumpingToCurrentRet] = newRet;
if (iJumpingToCurrentRet.OpCode == OpCode.TRY || iJumpingToCurrentRet.OpCode == OpCode.TRY_L)
{
(Instruction t1, Instruction t2) = trySourceToTargets[iJumpingToCurrentRet];
if (t1 == i) t1 = newRet;
if (t2 == i) t2 = newRet;
trySourceToTargets[iJumpingToCurrentRet] = (t1, t2);
}
}
jumpTargetToSources.Remove(i);
jumpTargetToSources[newRet] = othersJumpingToCurrentJmp;
}
simplifiedInstructionsToAddress.Add(newRet, currentAddress);
currentAddress += newRet.Size;
continue;
}
}
simplifiedInstructionsToAddress.Add(i, currentAddress);
currentAddress += i.Size;
}

return AssetBuilder.BuildOptimizedAssets(nef, manifest, debugInfo,
simplifiedInstructionsToAddress,
jumpSourceToTargets, trySourceToTargets,
oldAddressToInstruction,
oldSequencePointAddressToNew: oldSequencePointAddressToNew);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ public abstract class Contract_Array(Neo.SmartContract.Testing.SmartContractInit
{
#region Compiled data

public static Neo.SmartContract.Manifest.ContractManifest Manifest => Neo.SmartContract.Manifest.ContractManifest.Parse(@"{""name"":""Contract_Array"",""groups"":[],""features"":{},""supportedstandards"":[],""abi"":{""methods"":[{""name"":""getTreeByteLengthPrefix"",""parameters"":[],""returntype"":""ByteArray"",""offset"":0,""safe"":false},{""name"":""getTreeByteLengthPrefix2"",""parameters"":[],""returntype"":""ByteArray"",""offset"":2,""safe"":false},{""name"":""testJaggedArray"",""parameters"":[],""returntype"":""Array"",""offset"":4,""safe"":false},{""name"":""testJaggedByteArray"",""parameters"":[],""returntype"":""Array"",""offset"":42,""safe"":false},{""name"":""testIntArray"",""parameters"":[],""returntype"":""Array"",""offset"":88,""safe"":false},{""name"":""testDefaultArray"",""parameters"":[],""returntype"":""Boolean"",""offset"":118,""safe"":false},{""name"":""testIntArrayInit"",""parameters"":[],""returntype"":""Array"",""offset"":137,""safe"":false},{""name"":""testIntArrayInit2"",""parameters"":[],""returntype"":""Array"",""offset"":162,""safe"":false},{""name"":""testIntArrayInit3"",""parameters"":[],""returntype"":""Array"",""offset"":187,""safe"":false},{""name"":""testDynamicArrayInit"",""parameters"":[{""name"":""length"",""type"":""Integer""}],""returntype"":""Array"",""offset"":212,""safe"":false},{""name"":""testDynamicArrayStringInit"",""parameters"":[{""name"":""input"",""type"":""String""}],""returntype"":""ByteArray"",""offset"":288,""safe"":false},{""name"":""testStructArray"",""parameters"":[],""returntype"":""Any"",""offset"":295,""safe"":false},{""name"":""testDefaultState"",""parameters"":[],""returntype"":""Any"",""offset"":343,""safe"":false},{""name"":""testEmptyArray"",""parameters"":[],""returntype"":""Array"",""offset"":362,""safe"":false},{""name"":""testStructArrayInit"",""parameters"":[],""returntype"":""Any"",""offset"":369,""safe"":false},{""name"":""testByteArrayOwner"",""parameters"":[],""returntype"":""ByteArray"",""offset"":426,""safe"":false},{""name"":""testByteArrayOwnerCall"",""parameters"":[],""returntype"":""ByteArray"",""offset"":428,""safe"":false},{""name"":""testSupportedStandards"",""parameters"":[],""returntype"":""Array"",""offset"":431,""safe"":false},{""name"":""testElementBinding"",""parameters"":[],""returntype"":""Void"",""offset"":433,""safe"":false},{""name"":""testCollectionexpressions"",""parameters"":[],""returntype"":""Array"",""offset"":469,""safe"":false},{""name"":""_initialize"",""parameters"":[],""returntype"":""Void"",""offset"":559,""safe"":false}],""events"":[]},""permissions"":[{""contract"":""0xacce6fd80d44e1796aa0c2c625e9e4e0ce39efc0"",""methods"":[""itoa""]},{""contract"":""0xda65b600f7124ce6c79950c1772a36403104f2be"",""methods"":[""getBlock""]}],""trusts"":[],""extra"":{""nef"":{""optimization"":""All""}}}");
public static Neo.SmartContract.Manifest.ContractManifest Manifest => Neo.SmartContract.Manifest.ContractManifest.Parse(@"{""name"":""Contract_Array"",""groups"":[],""features"":{},""supportedstandards"":[],""abi"":{""methods"":[{""name"":""getTreeByteLengthPrefix"",""parameters"":[],""returntype"":""ByteArray"",""offset"":0,""safe"":false},{""name"":""getTreeByteLengthPrefix2"",""parameters"":[],""returntype"":""ByteArray"",""offset"":2,""safe"":false},{""name"":""testJaggedArray"",""parameters"":[],""returntype"":""Array"",""offset"":4,""safe"":false},{""name"":""testJaggedByteArray"",""parameters"":[],""returntype"":""Array"",""offset"":42,""safe"":false},{""name"":""testIntArray"",""parameters"":[],""returntype"":""Array"",""offset"":88,""safe"":false},{""name"":""testDefaultArray"",""parameters"":[],""returntype"":""Boolean"",""offset"":118,""safe"":false},{""name"":""testIntArrayInit"",""parameters"":[],""returntype"":""Array"",""offset"":136,""safe"":false},{""name"":""testIntArrayInit2"",""parameters"":[],""returntype"":""Array"",""offset"":161,""safe"":false},{""name"":""testIntArrayInit3"",""parameters"":[],""returntype"":""Array"",""offset"":186,""safe"":false},{""name"":""testDynamicArrayInit"",""parameters"":[{""name"":""length"",""type"":""Integer""}],""returntype"":""Array"",""offset"":211,""safe"":false},{""name"":""testDynamicArrayStringInit"",""parameters"":[{""name"":""input"",""type"":""String""}],""returntype"":""ByteArray"",""offset"":287,""safe"":false},{""name"":""testStructArray"",""parameters"":[],""returntype"":""Any"",""offset"":294,""safe"":false},{""name"":""testDefaultState"",""parameters"":[],""returntype"":""Any"",""offset"":342,""safe"":false},{""name"":""testEmptyArray"",""parameters"":[],""returntype"":""Array"",""offset"":361,""safe"":false},{""name"":""testStructArrayInit"",""parameters"":[],""returntype"":""Any"",""offset"":368,""safe"":false},{""name"":""testByteArrayOwner"",""parameters"":[],""returntype"":""ByteArray"",""offset"":425,""safe"":false},{""name"":""testByteArrayOwnerCall"",""parameters"":[],""returntype"":""ByteArray"",""offset"":427,""safe"":false},{""name"":""testSupportedStandards"",""parameters"":[],""returntype"":""Array"",""offset"":430,""safe"":false},{""name"":""testElementBinding"",""parameters"":[],""returntype"":""Void"",""offset"":432,""safe"":false},{""name"":""testCollectionexpressions"",""parameters"":[],""returntype"":""Array"",""offset"":468,""safe"":false},{""name"":""_initialize"",""parameters"":[],""returntype"":""Void"",""offset"":558,""safe"":false}],""events"":[]},""permissions"":[{""contract"":""0xacce6fd80d44e1796aa0c2c625e9e4e0ce39efc0"",""methods"":[""itoa""]},{""contract"":""0xda65b600f7124ce6c79950c1772a36403104f2be"",""methods"":[""getBlock""]}],""trusts"":[],""extra"":{""nef"":{""optimization"":""All""}}}");

/// <summary>
/// Optimization: "All"
/// </summary>
public static Neo.SmartContract.NefFile Nef => Neo.IO.Helper.AsSerializable<Neo.SmartContract.NefFile>(Convert.FromBase64String(@"TkVGM1Rlc3RpbmdFbmdpbmUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK+8gQxQDYqd8FQmcfmTBL3ALZl2ghnZXRCbG9jawEAAQ/A7znO4OTpJcbCoGp54UQN2G/OrARpdG9hAQABDwAA/WsCWEBZQFcEABQTEhEUwHAYFxYVFMBxERITERTAchITFBUUwHNramloFMBAVwQADAQBAgME2zBwDAQFBgcI2zBxDAQBAwIB2zByDAQFBAMC2zBza2ppaBTAQFcBABPEIXAQSmgQUdBFEUpoEVHQRRJKaBJR0EVoQFcBABPEIXBoEM4QlyYFCCIDCUBXAQATEhETwHAUSmgRUdBFFUpoElHQRWhAVwEAExIRE8BwFEpoEVHQRRVKaBJR0EVoQFcBABMSERPAcBRKaBFR0EUVSmgSUdBFaEBXAgF4xCFwEHEiPGlKaGlR0EVpSpxKAgAAAIAuBCIKSgL///9/Mh4D/////wAAAACRSgL///9/MgwDAAAAAAEAAACfcUVpeLUkw2hAVwABeMqIQFcCAMVKC89KC89KEM9KNBJwE8QAcWhKaRJR0EVpEs5AVwABeBAL0HgRC9B4EhDQQFcBAMVKC89KC89KEM9KNOJwaEBXAQDCcGhAVwMAxUoLz0oLz0oQz0o0yHBoEcBxaRDOcmpAVwEADBT2ZENJjTh40yuZTk4Sg8aTRCHa/tswcGhAWkA04EBbQFcDABA3AABwaBHAcWlK2CQEEM5yakrYJAcUzjcBAEHP50eWQFcHABgXFhUUExIRGMBwDAV0aHJlZQwDdHdvDANvbmUTwHEZGBcTwBYVFBPAExIRE8ATwHITEhETwHMWFRQTwHQZGBcTwHVtbGsTwHbFSmjPSmnPSmrPSm7PQFYEDAIBA9swYAwCAQPbMGEMFPZkQ0mNOHjTK5lOThKDxpNEIdr+2zBiDAZORVAtMTAMBU5FUC01EsBjQBrqUzA="));
public static Neo.SmartContract.NefFile Nef => Neo.IO.Helper.AsSerializable<Neo.SmartContract.NefFile>(Convert.FromBase64String(@"TkVGM1Rlc3RpbmdFbmdpbmUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK+8gQxQDYqd8FQmcfmTBL3ALZl2ghnZXRCbG9jawEAAQ/A7znO4OTpJcbCoGp54UQN2G/OrARpdG9hAQABDwAA/WoCWEBZQFcEABQTEhEUwHAYFxYVFMBxERITERTAchITFBUUwHNramloFMBAVwQADAQBAgME2zBwDAQFBgcI2zBxDAQBAwIB2zByDAQFBAMC2zBza2ppaBTAQFcBABPEIXAQSmgQUdBFEUpoEVHQRRJKaBJR0EVoQFcBABPEIXBoEM4QlyYECEAJQFcBABMSERPAcBRKaBFR0EUVSmgSUdBFaEBXAQATEhETwHAUSmgRUdBFFUpoElHQRWhAVwEAExIRE8BwFEpoEVHQRRVKaBJR0EVoQFcCAXjEIXAQcSI8aUpoaVHQRWlKnEoCAAAAgC4EIgpKAv///38yHgP/////AAAAAJFKAv///38yDAMAAAAAAQAAAJ9xRWl4tSTDaEBXAAF4yohAVwIAxUoLz0oLz0oQz0o0EnATxABxaEppElHQRWkSzkBXAAF4EAvQeBEL0HgSENBAVwEAxUoLz0oLz0oQz0o04nBoQFcBAMJwaEBXAwDFSgvPSgvPShDPSjTIcGgRwHFpEM5yakBXAQAMFPZkQ0mNOHjTK5lOThKDxpNEIdr+2zBwaEBaQDTgQFtAVwMAEDcAAHBoEcBxaUrYJAQQznJqStgkBxTONwEAQc/nR5ZAVwcAGBcWFRQTEhEYwHAMBXRocmVlDAN0d28MA29uZRPAcRkYFxPAFhUUE8ATEhETwBPAchMSERPAcxYVFBPAdBkYFxPAdW1saxPAdsVKaM9Kac9Kas9Kbs9AVgQMAgED2zBgDAIBA9swYQwU9mRDSY04eNMrmU5OEoPGk0Qh2v7bMGIMBk5FUC0xMAwFTkVQLTUSwGNALn4FWw=="));

#endregion

Expand Down
Loading
Loading