You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 lines
6.9 KiB

  1. // Copyright (c) 2011-2015 Daniel Grunwald
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4. // software and associated documentation files (the "Software"), to deal in the Software
  5. // without restriction, including without limitation the rights to use, copy, modify, merge,
  6. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7. // to whom the Software is furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in all copies or
  10. // substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  14. // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  15. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. // DEALINGS IN THE SOFTWARE.
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.Linq;
  21. using ICSharpCode.Decompiler.TypeSystem;
  22. using ICSharpCode.Decompiler.Util;
  23. namespace ICSharpCode.Decompiler.IL.Transforms
  24. {
  25. /// <summary>
  26. /// Runs a very simple form of copy propagation.
  27. /// Copy propagation is used in two cases:
  28. /// 1) assignments from arguments to local variables
  29. /// If the target variable is assigned to only once (so always is that argument) and the argument is never changed (no ldarga/starg),
  30. /// then we can replace the variable with the argument.
  31. /// 2) assignments of address-loading instructions to local variables
  32. /// </summary>
  33. public class CopyPropagation : IILTransform
  34. {
  35. public static void Propagate(StLoc store, ILTransformContext context)
  36. {
  37. Debug.Assert(store.Variable.IsSingleDefinition);
  38. Block block = (Block)store.Parent;
  39. int i = store.ChildIndex;
  40. DoPropagate(store.Variable, store.Value, block, ref i, context);
  41. }
  42. public void Run(ILFunction function, ILTransformContext context)
  43. {
  44. var splitVariables = new HashSet<ILVariable>(ILVariableEqualityComparer.Instance);
  45. foreach (var g in function.Variables.GroupBy(v => v, ILVariableEqualityComparer.Instance))
  46. {
  47. if (g.Count() > 1)
  48. {
  49. splitVariables.Add(g.Key);
  50. }
  51. }
  52. foreach (var block in function.Descendants.OfType<Block>())
  53. {
  54. if (block.Kind != BlockKind.ControlFlow)
  55. continue;
  56. RunOnBlock(block, context, splitVariables);
  57. }
  58. }
  59. static void RunOnBlock(Block block, ILTransformContext context, HashSet<ILVariable> splitVariables = null)
  60. {
  61. for (int i = 0; i < block.Instructions.Count; i++)
  62. {
  63. if (block.Instructions[i].MatchStLoc(out ILVariable v, out ILInstruction copiedExpr))
  64. {
  65. if (v.IsSingleDefinition && v.LoadCount == 0 && v.Kind == VariableKind.StackSlot)
  66. {
  67. // dead store to stack
  68. if (SemanticHelper.IsPure(copiedExpr.Flags))
  69. {
  70. // no-op -> delete
  71. context.Step("remove dead store to stack: no-op -> delete", block.Instructions[i]);
  72. block.Instructions.RemoveAt(i);
  73. // This can open up new inlining opportunities:
  74. int c = ILInlining.InlineInto(block, i, InliningOptions.None, context: context);
  75. i -= c + 1;
  76. }
  77. else
  78. {
  79. // evaluate the value for its side-effects
  80. context.Step("remove dead store to stack: evaluate the value for its side-effects", block.Instructions[i]);
  81. copiedExpr.AddILRange(block.Instructions[i]);
  82. block.Instructions[i] = copiedExpr;
  83. }
  84. }
  85. else if (v.IsSingleDefinition && CanPerformCopyPropagation(v, copiedExpr, splitVariables))
  86. {
  87. DoPropagate(v, copiedExpr, block, ref i, context);
  88. }
  89. }
  90. }
  91. }
  92. static bool CanPerformCopyPropagation(ILVariable target, ILInstruction value, HashSet<ILVariable> splitVariables)
  93. {
  94. Debug.Assert(target.StackType == value.ResultType);
  95. if (target.Type.IsSmallIntegerType())
  96. return false;
  97. if (splitVariables != null && splitVariables.Contains(target))
  98. {
  99. return false; // non-local code move might change semantics when there's split variables
  100. }
  101. switch (value.OpCode)
  102. {
  103. case OpCode.LdLoca:
  104. // case OpCode.LdElema:
  105. // case OpCode.LdFlda:
  106. case OpCode.LdsFlda:
  107. // All address-loading instructions always return the same value for a given operand/argument combination,
  108. // so they can be safely copied.
  109. // ... except for LdElema and LdFlda, because those might throw an exception, and we don't want to
  110. // change the place where the exception is thrown.
  111. return true;
  112. case OpCode.LdLoc:
  113. var v = ((LdLoc)value).Variable;
  114. if (splitVariables != null && splitVariables.Contains(v))
  115. {
  116. return false; // non-local code move might change semantics when there's split variables
  117. }
  118. switch (v.Kind)
  119. {
  120. case VariableKind.Parameter:
  121. // Parameters can be copied only if they aren't assigned to (directly or indirectly via ldarga)
  122. // note: the initialization by the caller is the first store -> StoreCount must be 1
  123. return v.IsSingleDefinition;
  124. default:
  125. // Variables can be copied if both are single-definition.
  126. // To avoid removing too many variables, we do this only if the target
  127. // is either a stackslot or a ref local.
  128. Debug.Assert(target.IsSingleDefinition);
  129. return v.IsSingleDefinition && (target.Kind == VariableKind.StackSlot || target.StackType == StackType.Ref);
  130. }
  131. default:
  132. // All instructions without special behavior that target a stack-variable can be copied.
  133. return value.Flags == InstructionFlags.None && value.Children.Count == 0 && target.Kind == VariableKind.StackSlot;
  134. }
  135. }
  136. static void DoPropagate(ILVariable v, ILInstruction copiedExpr, Block block, ref int i, ILTransformContext context)
  137. {
  138. context.Step($"Copy propagate {v.Name}", copiedExpr);
  139. // un-inline the arguments of the ldArg instruction
  140. ILVariable[] uninlinedArgs = new ILVariable[copiedExpr.Children.Count];
  141. for (int j = 0; j < uninlinedArgs.Length; j++)
  142. {
  143. var arg = copiedExpr.Children[j];
  144. var type = context.TypeSystem.FindType(arg.ResultType);
  145. uninlinedArgs[j] = new ILVariable(VariableKind.StackSlot, type, arg.ResultType) {
  146. Name = "C_" + arg.StartILOffset,
  147. HasGeneratedName = true,
  148. };
  149. block.Instructions.Insert(i++, new StLoc(uninlinedArgs[j], arg));
  150. }
  151. v.Function.Variables.AddRange(uninlinedArgs);
  152. // perform copy propagation:
  153. foreach (var expr in v.LoadInstructions.ToArray())
  154. {
  155. var clone = copiedExpr.Clone();
  156. for (int j = 0; j < uninlinedArgs.Length; j++)
  157. {
  158. clone.Children[j].ReplaceWith(new LdLoc(uninlinedArgs[j]));
  159. }
  160. expr.ReplaceWith(clone);
  161. }
  162. block.Instructions.RemoveAt(i);
  163. int c = ILInlining.InlineInto(block, i, InliningOptions.None, context: context);
  164. i -= c + 1;
  165. }
  166. }
  167. }