Browse Source

Merge branch 'master' of github.com:icsharpcode/ILSpy

pull/70/head
Daniel Grunwald 15 years ago
parent
commit
accfe8c889
  1. 430
      ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs
  2. 44
      ICSharpCode.Decompiler/ILAst/GotoRemoval.cs
  3. 226
      ICSharpCode.Decompiler/ILAst/ILAstOptimizer.cs
  4. 26
      ICSharpCode.Decompiler/ILAst/ILAstTypes.cs
  5. 4
      ICSharpCode.Decompiler/ILAst/ILCodes.cs
  6. 2
      ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs
  7. 18
      NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs

430
ICSharpCode.Decompiler/Ast/AstMethodBodyBuilder.cs

@ -80,9 +80,7 @@ namespace ICSharpCode.Decompiler.Ast
{ {
Ast.BlockStatement astBlock = new BlockStatement(); Ast.BlockStatement astBlock = new BlockStatement();
if (block != null) { if (block != null) {
if (block.EntryGoto != null) foreach(ILNode node in block.GetChildren()) {
astBlock.Add((Statement)TransformExpression(block.EntryGoto));
foreach(ILNode node in block.Body) {
astBlock.AddRange(TransformNode(node)); astBlock.AddRange(TransformNode(node));
} }
} }
@ -123,11 +121,15 @@ namespace ICSharpCode.Decompiler.Ast
}; };
} else if (node is ILSwitch) { } else if (node is ILSwitch) {
ILSwitch ilSwitch = (ILSwitch)node; ILSwitch ilSwitch = (ILSwitch)node;
SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition.Arguments[0]) }; SwitchStatement switchStmt = new SwitchStatement() { Expression = (Expression)TransformExpression(ilSwitch.Condition) };
for (int i = 0; i < ilSwitch.CaseBlocks.Count; i++) { foreach (var caseBlock in ilSwitch.CaseBlocks) {
SwitchSection section = new SwitchSection(); SwitchSection section = new SwitchSection();
section.CaseLabels.Add(new CaseLabel() { Expression = new PrimitiveExpression(i) }); if (caseBlock.Values != null) {
section.Statements.Add(TransformBlock(ilSwitch.CaseBlocks[i])); section.CaseLabels.AddRange(caseBlock.Values.Select(i => new CaseLabel() { Expression = AstBuilder.MakePrimitive(i, ilSwitch.Condition.InferredType) }));
} else {
section.CaseLabels.Add(new CaseLabel());
}
section.Statements.Add(TransformBlock(caseBlock));
switchStmt.SwitchSections.Add(section); switchStmt.SwitchSections.Add(section);
} }
yield return switchStmt; yield return switchStmt;
@ -155,41 +157,6 @@ namespace ICSharpCode.Decompiler.Ast
} }
} }
List<Ast.Expression> TransformExpressionArguments(ILExpression expr)
{
List<Ast.Expression> args = new List<Ast.Expression>();
// Args generated by nested expressions (which must be closed)
foreach(ILExpression arg in expr.Arguments) {
args.Add((Ast.Expression)TransformExpression(arg));
}
return args;
}
static string FormatByteCodeOperand(object operand)
{
if (operand == null) {
return string.Empty;
//} else if (operand is ILExpression) {
// return string.Format("IL_{0:X2}", ((ILExpression)operand).Offset);
} else if (operand is MethodReference) {
return ((MethodReference)operand).Name + "()";
} else if (operand is Cecil.TypeReference) {
return ((Cecil.TypeReference)operand).FullName;
} else if (operand is VariableDefinition) {
return ((VariableDefinition)operand).Name;
} else if (operand is ParameterDefinition) {
return ((ParameterDefinition)operand).Name;
} else if (operand is FieldReference) {
return ((FieldReference)operand).Name;
} else if (operand is string) {
return "\"" + operand + "\"";
} else if (operand is int) {
return operand.ToString();
} else {
return operand.ToString();
}
}
AstNode TransformExpression(ILExpression expr) AstNode TransformExpression(ILExpression expr)
{ {
AstNode node = TransformByteCode(expr); AstNode node = TransformByteCode(expr);
@ -205,57 +172,57 @@ namespace ICSharpCode.Decompiler.Ast
object operand = byteCode.Operand; object operand = byteCode.Operand;
AstType operandAsTypeRef = AstBuilder.ConvertType(operand as Cecil.TypeReference); AstType operandAsTypeRef = AstBuilder.ConvertType(operand as Cecil.TypeReference);
List<Ast.Expression> args = TransformExpressionArguments(byteCode); List<Ast.Expression> args = new List<Expression>();
foreach(ILExpression arg in byteCode.Arguments) {
args.Add((Ast.Expression)TransformExpression(arg));
}
Ast.Expression arg1 = args.Count >= 1 ? args[0] : null; Ast.Expression arg1 = args.Count >= 1 ? args[0] : null;
Ast.Expression arg2 = args.Count >= 2 ? args[1] : null; Ast.Expression arg2 = args.Count >= 2 ? args[1] : null;
Ast.Expression arg3 = args.Count >= 3 ? args[2] : null; Ast.Expression arg3 = args.Count >= 3 ? args[2] : null;
switch(byteCode.Code) { switch(byteCode.Code) {
#region Arithmetic #region Arithmetic
case ILCode.Add: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); case ILCode.Add: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2);
case ILCode.Add_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); case ILCode.Add_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2);
case ILCode.Add_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2); case ILCode.Add_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Add, arg2);
case ILCode.Div: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2); case ILCode.Div: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2);
case ILCode.Div_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2); case ILCode.Div_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Divide, arg2);
case ILCode.Mul: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2); case ILCode.Mul: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2);
case ILCode.Mul_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2); case ILCode.Mul_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2);
case ILCode.Mul_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2); case ILCode.Mul_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Multiply, arg2);
case ILCode.Rem: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2); case ILCode.Rem: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2);
case ILCode.Rem_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2); case ILCode.Rem_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Modulus, arg2);
case ILCode.Sub: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); case ILCode.Sub: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2);
case ILCode.Sub_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); case ILCode.Sub_Ovf: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2);
case ILCode.Sub_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2); case ILCode.Sub_Ovf_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Subtract, arg2);
case ILCode.And: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseAnd, arg2); case ILCode.And: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseAnd, arg2);
case ILCode.Or: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseOr, arg2); case ILCode.Or: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.BitwiseOr, arg2);
case ILCode.Xor: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ExclusiveOr, arg2); case ILCode.Xor: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ExclusiveOr, arg2);
case ILCode.Shl: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2); case ILCode.Shl: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftLeft, arg2);
case ILCode.Shr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Shr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2);
case ILCode.Shr_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2); case ILCode.Shr_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ShiftRight, arg2);
case ILCode.Neg: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Minus, arg1);
case ILCode.Neg: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Minus, arg1); case ILCode.Not: return new Ast.UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1);
case ILCode.Not: return new Ast.UnaryOperatorExpression(UnaryOperatorType.BitNot, arg1); #endregion
#endregion #region Arrays
#region Arrays
case ILCode.Newarr: case ILCode.Newarr:
case ILCode.InitArray: case ILCode.InitArray: {
{ var ace = new Ast.ArrayCreateExpression();
var ace = new Ast.ArrayCreateExpression(); ace.Type = operandAsTypeRef;
ace.Type = operandAsTypeRef; ComposedType ct = operandAsTypeRef as ComposedType;
ComposedType ct = operandAsTypeRef as ComposedType; if (ct != null) {
if (ct != null) { // change "new (int[,])[10] to new int[10][,]"
// change "new (int[,])[10] to new int[10][,]" ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers);
ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); }
} if (byteCode.Code == ILCode.InitArray) {
if (byteCode.Code == ILCode.InitArray) { ace.Initializer = new ArrayInitializerExpression();
ace.Initializer = new ArrayInitializerExpression(); ace.Initializer.Elements.AddRange(args);
ace.Initializer.Elements.AddRange(args); } else {
} else { ace.Arguments.Add(arg1);
ace.Arguments.Add(arg1);
}
return ace;
} }
case ILCode.Ldlen: return ace;
return arg1.Member("Length"); }
case ILCode.Ldlen: return arg1.Member("Length");
case ILCode.Ldelem_I: case ILCode.Ldelem_I:
case ILCode.Ldelem_I1: case ILCode.Ldelem_I1:
case ILCode.Ldelem_I2: case ILCode.Ldelem_I2:
@ -269,9 +236,7 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Ldelem_Ref: case ILCode.Ldelem_Ref:
case ILCode.Ldelem_Any: case ILCode.Ldelem_Any:
return arg1.Indexer(arg2); return arg1.Indexer(arg2);
case ILCode.Ldelema: case ILCode.Ldelema: return MakeRef(arg1.Indexer(arg2));
return MakeRef(arg1.Indexer(arg2));
case ILCode.Stelem_I: case ILCode.Stelem_I:
case ILCode.Stelem_I1: case ILCode.Stelem_I1:
case ILCode.Stelem_I2: case ILCode.Stelem_I2:
@ -282,33 +247,28 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Stelem_Ref: case ILCode.Stelem_Ref:
case ILCode.Stelem_Any: case ILCode.Stelem_Any:
return new Ast.AssignmentExpression(arg1.Indexer(arg2), arg3); return new Ast.AssignmentExpression(arg1.Indexer(arg2), arg3);
#endregion #endregion
#region Comparison #region Comparison
case ILCode.Ceq: case ILCode.Ceq: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2);
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.Equality, arg2); case ILCode.Cgt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
case ILCode.Cgt: case ILCode.Cgt_Un: {
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
case ILCode.Cgt_Un:
// can also mean Inequality, when used with object references // can also mean Inequality, when used with object references
{ TypeReference arg1Type = byteCode.Arguments[0].InferredType;
TypeReference arg1Type = byteCode.Arguments[0].InferredType; if (arg1Type != null && !arg1Type.IsValueType)
if (arg1Type != null && !arg1Type.IsValueType) return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2);
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.InEquality, arg2); else
else return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2);
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.GreaterThan, arg2); }
} case ILCode.Clt: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
case ILCode.Clt: case ILCode.Clt_Un: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2); #endregion
case ILCode.Clt_Un: #region Logical
return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.LessThan, arg2);
#endregion
#region Logical
case ILCode.LogicNot: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Not, arg1); case ILCode.LogicNot: return new Ast.UnaryOperatorExpression(UnaryOperatorType.Not, arg1);
case ILCode.LogicAnd: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalAnd, arg2); case ILCode.LogicAnd: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalAnd, arg2);
case ILCode.LogicOr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalOr, arg2); case ILCode.LogicOr: return new Ast.BinaryOperatorExpression(arg1, BinaryOperatorType.ConditionalOr, arg2);
case ILCode.TernaryOp: return new Ast.ConditionalExpression() { Condition = arg1, TrueExpression = arg2, FalseExpression = arg3 }; case ILCode.TernaryOp: return new Ast.ConditionalExpression() { Condition = arg1, TrueExpression = arg2, FalseExpression = arg3 };
#endregion #endregion
#region Branch #region Branch
case ILCode.Br: return new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name); case ILCode.Br: return new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name);
case ILCode.Brtrue: case ILCode.Brtrue:
return new Ast.IfElseStatement() { return new Ast.IfElseStatement() {
@ -317,10 +277,10 @@ namespace ICSharpCode.Decompiler.Ast
new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name) new Ast.GotoStatement(((ILLabel)byteCode.Operand).Name)
} }
}; };
case ILCode.LoopBreak: return new Ast.BreakStatement(); case ILCode.LoopOrSwitchBreak: return new Ast.BreakStatement();
case ILCode.LoopContinue: return new Ast.ContinueStatement(); case ILCode.LoopContinue: return new Ast.ContinueStatement();
#endregion #endregion
#region Conversions #region Conversions
case ILCode.Conv_I1: case ILCode.Conv_I1:
case ILCode.Conv_I2: case ILCode.Conv_I2:
case ILCode.Conv_I4: case ILCode.Conv_I4:
@ -330,12 +290,11 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Conv_U4: case ILCode.Conv_U4:
case ILCode.Conv_U8: case ILCode.Conv_U8:
return arg1; // conversion is handled by Convert() function using the info from type analysis return arg1; // conversion is handled by Convert() function using the info from type analysis
case ILCode.Conv_I: return arg1.CastTo(typeof(IntPtr)); // TODO case ILCode.Conv_I: return arg1.CastTo(typeof(IntPtr)); // TODO
case ILCode.Conv_U: return arg1.CastTo(typeof(UIntPtr)); // TODO case ILCode.Conv_U: return arg1.CastTo(typeof(UIntPtr)); // TODO
case ILCode.Conv_R4: return arg1.CastTo(typeof(float)); case ILCode.Conv_R4: return arg1.CastTo(typeof(float));
case ILCode.Conv_R8: return arg1.CastTo(typeof(double)); case ILCode.Conv_R8: return arg1.CastTo(typeof(double));
case ILCode.Conv_R_Un: return arg1.CastTo(typeof(double)); // TODO case ILCode.Conv_R_Un: return arg1.CastTo(typeof(double)); // TODO
case ILCode.Conv_Ovf_I1: case ILCode.Conv_Ovf_I1:
case ILCode.Conv_Ovf_I2: case ILCode.Conv_Ovf_I2:
case ILCode.Conv_Ovf_I4: case ILCode.Conv_Ovf_I4:
@ -353,22 +312,17 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Conv_Ovf_U4_Un: case ILCode.Conv_Ovf_U4_Un:
case ILCode.Conv_Ovf_U8_Un: case ILCode.Conv_Ovf_U8_Un:
return arg1; // conversion was handled by Convert() function using the info from type analysis return arg1; // conversion was handled by Convert() function using the info from type analysis
case ILCode.Conv_Ovf_I: return arg1.CastTo(typeof(IntPtr)); // TODO case ILCode.Conv_Ovf_I: return arg1.CastTo(typeof(IntPtr)); // TODO
case ILCode.Conv_Ovf_U: return arg1.CastTo(typeof(UIntPtr)); case ILCode.Conv_Ovf_U: return arg1.CastTo(typeof(UIntPtr));
case ILCode.Conv_Ovf_I_Un: return arg1.CastTo(typeof(IntPtr)); case ILCode.Conv_Ovf_I_Un: return arg1.CastTo(typeof(IntPtr));
case ILCode.Conv_Ovf_U_Un: return arg1.CastTo(typeof(UIntPtr)); case ILCode.Conv_Ovf_U_Un: return arg1.CastTo(typeof(UIntPtr));
case ILCode.Castclass: return arg1.CastTo(operandAsTypeRef);
case ILCode.Castclass: case ILCode.Unbox_Any: return arg1.CastTo(operandAsTypeRef);
case ILCode.Unbox_Any: case ILCode.Isinst: return arg1.CastAs(operandAsTypeRef);
return arg1.CastTo(operandAsTypeRef); case ILCode.Box: return arg1;
case ILCode.Isinst: case ILCode.Unbox: return InlineAssembly(byteCode, args);
return arg1.CastAs(operandAsTypeRef); #endregion
case ILCode.Box: #region Indirect
return arg1;
case ILCode.Unbox:
return InlineAssembly(byteCode, args);
#endregion
#region Indirect
case ILCode.Ldind_I: case ILCode.Ldind_I:
case ILCode.Ldind_I1: case ILCode.Ldind_I1:
case ILCode.Ldind_I2: case ILCode.Ldind_I2:
@ -385,7 +339,6 @@ namespace ICSharpCode.Decompiler.Ast
return ((DirectionExpression)args[0]).Expression.Detach(); return ((DirectionExpression)args[0]).Expression.Detach();
else else
return InlineAssembly(byteCode, args); return InlineAssembly(byteCode, args);
case ILCode.Stind_I: case ILCode.Stind_I:
case ILCode.Stind_I1: case ILCode.Stind_I1:
case ILCode.Stind_I2: case ILCode.Stind_I2:
@ -399,49 +352,43 @@ namespace ICSharpCode.Decompiler.Ast
return new AssignmentExpression(((DirectionExpression)args[0]).Expression.Detach(), args[1]); return new AssignmentExpression(((DirectionExpression)args[0]).Expression.Detach(), args[1]);
else else
return InlineAssembly(byteCode, args); return InlineAssembly(byteCode, args);
#endregion #endregion
case ILCode.Arglist: return InlineAssembly(byteCode, args); case ILCode.Arglist: return InlineAssembly(byteCode, args);
case ILCode.Break: return InlineAssembly(byteCode, args); case ILCode.Break: return InlineAssembly(byteCode, args);
case ILCode.Call: case ILCode.Call: return TransformCall(false, operand, methodDef, args);
return TransformCall(false, operand, methodDef, args); case ILCode.Callvirt: return TransformCall(true, operand, methodDef, args);
case ILCode.Callvirt: case ILCode.Ldftn: {
return TransformCall(true, operand, methodDef, args); Cecil.MethodReference cecilMethod = ((MethodReference)operand);
case ILCode.Ldftn: var expr = new Ast.IdentifierExpression(cecilMethod.Name);
{ expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod));
Cecil.MethodReference cecilMethod = ((MethodReference)operand); expr.AddAnnotation(cecilMethod);
var expr = new Ast.IdentifierExpression(cecilMethod.Name); return new IdentifierExpression("ldftn").Invoke(expr)
expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod)); .WithAnnotation(new Transforms.DelegateConstruction.Annotation(false));
expr.AddAnnotation(cecilMethod); }
return new IdentifierExpression("ldftn").Invoke(expr) case ILCode.Ldvirtftn: {
.WithAnnotation(new Transforms.DelegateConstruction.Annotation(false)); Cecil.MethodReference cecilMethod = ((MethodReference)operand);
} var expr = new Ast.IdentifierExpression(cecilMethod.Name);
case ILCode.Ldvirtftn: expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod));
{ expr.AddAnnotation(cecilMethod);
Cecil.MethodReference cecilMethod = ((MethodReference)operand); return new IdentifierExpression("ldvirtftn").Invoke(expr)
var expr = new Ast.IdentifierExpression(cecilMethod.Name); .WithAnnotation(new Transforms.DelegateConstruction.Annotation(true));
expr.TypeArguments.AddRange(ConvertTypeArguments(cecilMethod)); }
expr.AddAnnotation(cecilMethod); case ILCode.Calli: return InlineAssembly(byteCode, args);
return new IdentifierExpression("ldvirtftn").Invoke(expr) case ILCode.Ckfinite: return InlineAssembly(byteCode, args);
.WithAnnotation(new Transforms.DelegateConstruction.Annotation(true)); case ILCode.Constrained: return InlineAssembly(byteCode, args);
} case ILCode.Cpblk: return InlineAssembly(byteCode, args);
case ILCode.Cpobj: return InlineAssembly(byteCode, args);
case ILCode.Calli: return InlineAssembly(byteCode, args); case ILCode.Dup: return arg1;
case ILCode.Ckfinite: return InlineAssembly(byteCode, args); case ILCode.Endfilter: return InlineAssembly(byteCode, args);
case ILCode.Constrained: return InlineAssembly(byteCode, args); case ILCode.Endfinally: return null;
case ILCode.Cpblk: return InlineAssembly(byteCode, args); case ILCode.Initblk: return InlineAssembly(byteCode, args);
case ILCode.Cpobj: return InlineAssembly(byteCode, args);
case ILCode.Dup: return arg1;
case ILCode.Endfilter: return InlineAssembly(byteCode, args);
case ILCode.Endfinally: return null;
case ILCode.Initblk: return InlineAssembly(byteCode, args);
case ILCode.Initobj: case ILCode.Initobj:
if (args[0] is DirectionExpression) if (args[0] is DirectionExpression)
return new AssignmentExpression(((DirectionExpression)args[0]).Expression.Detach(), new DefaultValueExpression { Type = operandAsTypeRef }); return new AssignmentExpression(((DirectionExpression)args[0]).Expression.Detach(), new DefaultValueExpression { Type = operandAsTypeRef });
else else
return InlineAssembly(byteCode, args); return InlineAssembly(byteCode, args);
case ILCode.Jmp: case ILCode.Jmp: return InlineAssembly(byteCode, args);
return InlineAssembly(byteCode, args); case ILCode.Ldarg: {
case ILCode.Ldarg:
if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) { if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) {
if (context.CurrentMethod.DeclaringType.IsValueType) if (context.CurrentMethod.DeclaringType.IsValueType)
return MakeRef(new Ast.ThisReferenceExpression()); return MakeRef(new Ast.ThisReferenceExpression());
@ -454,14 +401,14 @@ namespace ICSharpCode.Decompiler.Ast
else else
return expr; return expr;
} }
}
case ILCode.Ldarga: case ILCode.Ldarga:
if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) { if (methodDef.HasThis && ((ParameterDefinition)operand).Index < 0) {
return MakeRef(new Ast.ThisReferenceExpression()); return MakeRef(new Ast.ThisReferenceExpression());
} else { } else {
return MakeRef(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand)); return MakeRef(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand));
} }
case ILCode.Ldc_I4: case ILCode.Ldc_I4: return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType);
return AstBuilder.MakePrimitive((int)operand, byteCode.InferredType);
case ILCode.Ldc_I8: case ILCode.Ldc_I8:
case ILCode.Ldc_R4: case ILCode.Ldc_R4:
case ILCode.Ldc_R8: case ILCode.Ldc_R8:
@ -483,8 +430,7 @@ namespace ICSharpCode.Decompiler.Ast
AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) AstBuilder.ConvertType(((FieldReference)operand).DeclaringType)
.Member(((FieldReference)operand).Name).WithAnnotation(operand), .Member(((FieldReference)operand).Name).WithAnnotation(operand),
arg1); arg1);
case ILCode.Ldflda: case ILCode.Ldflda: return MakeRef(arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand));
return MakeRef(arg1.Member(((FieldReference) operand).Name).WithAnnotation(operand));
case ILCode.Ldsflda: case ILCode.Ldsflda:
return MakeRef( return MakeRef(
AstBuilder.ConvertType(((FieldReference)operand).DeclaringType) AstBuilder.ConvertType(((FieldReference)operand).DeclaringType)
@ -495,72 +441,65 @@ namespace ICSharpCode.Decompiler.Ast
case ILCode.Ldloca: case ILCode.Ldloca:
localVariablesToDefine.Add((ILVariable)operand); localVariablesToDefine.Add((ILVariable)operand);
return MakeRef(new Ast.IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand)); return MakeRef(new Ast.IdentifierExpression(((ILVariable)operand).Name).WithAnnotation(operand));
case ILCode.Ldnull: case ILCode.Ldnull: return new Ast.NullReferenceExpression();
return new Ast.NullReferenceExpression(); case ILCode.Ldstr: return new Ast.PrimitiveExpression(operand);
case ILCode.Ldstr:
return new Ast.PrimitiveExpression(operand);
case ILCode.Ldtoken: case ILCode.Ldtoken:
if (operand is Cecil.TypeReference) { if (operand is Cecil.TypeReference) {
return new Ast.TypeOfExpression { Type = operandAsTypeRef }.Member("TypeHandle"); return new Ast.TypeOfExpression { Type = operandAsTypeRef }.Member("TypeHandle");
} else { } else {
return InlineAssembly(byteCode, args); return InlineAssembly(byteCode, args);
} }
case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name }; case ILCode.Leave: return new GotoStatement() { Label = ((ILLabel)operand).Name };
case ILCode.Localloc: return InlineAssembly(byteCode, args); case ILCode.Localloc: return InlineAssembly(byteCode, args);
case ILCode.Mkrefany: return InlineAssembly(byteCode, args); case ILCode.Mkrefany: return InlineAssembly(byteCode, args);
case ILCode.Newobj: case ILCode.Newobj: {
{ Cecil.TypeReference declaringType = ((MethodReference)operand).DeclaringType;
Cecil.TypeReference declaringType = ((MethodReference)operand).DeclaringType; if (declaringType is ArrayType) {
ComposedType ct = AstBuilder.ConvertType((ArrayType)declaringType) as ComposedType;
if (declaringType is ArrayType) { if (ct != null && ct.ArraySpecifiers.Count >= 1) {
ComposedType ct = AstBuilder.ConvertType((ArrayType)declaringType) as ComposedType; var ace = new Ast.ArrayCreateExpression();
if (ct != null && ct.ArraySpecifiers.Count >= 1) { ct.ArraySpecifiers.First().Remove();
var ace = new Ast.ArrayCreateExpression(); ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers);
ct.ArraySpecifiers.First().Remove(); ace.Type = ct;
ct.ArraySpecifiers.MoveTo(ace.AdditionalArraySpecifiers); ace.Arguments.AddRange(args);
ace.Type = ct; return ace;
ace.Arguments.AddRange(args);
return ace;
}
}
var oce = new Ast.ObjectCreateExpression();
oce.Type = AstBuilder.ConvertType(declaringType);
oce.Arguments.AddRange(args);
return oce.WithAnnotation(operand);
}
case ILCode.No: return InlineAssembly(byteCode, args);
case ILCode.Nop: return null;
case ILCode.Pop: return arg1;
case ILCode.Readonly: return InlineAssembly(byteCode, args);
case ILCode.Refanytype: return InlineAssembly(byteCode, args);
case ILCode.Refanyval: return InlineAssembly(byteCode, args);
case ILCode.Ret: {
if (methodDef.ReturnType.FullName != "System.Void") {
return new Ast.ReturnStatement { Expression = arg1 };
} else {
return new Ast.ReturnStatement();
} }
} }
case ILCode.Rethrow: return new Ast.ThrowStatement(); var oce = new Ast.ObjectCreateExpression();
case ILCode.Sizeof: oce.Type = AstBuilder.ConvertType(declaringType);
return new Ast.SizeOfExpression { Type = operandAsTypeRef }; oce.Arguments.AddRange(args);
case ILCode.Starg: return oce.WithAnnotation(operand);
return new Ast.AssignmentExpression(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand), arg1); }
case ILCode.Stloc: { case ILCode.No: return InlineAssembly(byteCode, args);
ILVariable locVar = (ILVariable)operand; case ILCode.Nop: return null;
localVariablesToDefine.Add(locVar); case ILCode.Pop: return arg1;
return new Ast.AssignmentExpression(new Ast.IdentifierExpression(locVar.Name).WithAnnotation(locVar), arg1); case ILCode.Readonly: return InlineAssembly(byteCode, args);
case ILCode.Refanytype: return InlineAssembly(byteCode, args);
case ILCode.Refanyval: return InlineAssembly(byteCode, args);
case ILCode.Ret:
if (methodDef.ReturnType.FullName != "System.Void") {
return new Ast.ReturnStatement { Expression = arg1 };
} else {
return new Ast.ReturnStatement();
} }
case ILCode.Switch: return InlineAssembly(byteCode, args); case ILCode.Rethrow: return new Ast.ThrowStatement();
case ILCode.Tail: return InlineAssembly(byteCode, args); case ILCode.Sizeof: return new Ast.SizeOfExpression { Type = operandAsTypeRef };
case ILCode.Throw: return new Ast.ThrowStatement { Expression = arg1 }; case ILCode.Starg: return new Ast.AssignmentExpression(new Ast.IdentifierExpression(((ParameterDefinition)operand).Name).WithAnnotation(operand), arg1);
case ILCode.Unaligned: return InlineAssembly(byteCode, args); case ILCode.Stloc: {
case ILCode.Volatile: return InlineAssembly(byteCode, args); ILVariable locVar = (ILVariable)operand;
localVariablesToDefine.Add(locVar);
return new Ast.AssignmentExpression(new Ast.IdentifierExpression(locVar.Name).WithAnnotation(locVar), arg1);
}
case ILCode.Switch: return InlineAssembly(byteCode, args);
case ILCode.Tail: return InlineAssembly(byteCode, args);
case ILCode.Throw: return new Ast.ThrowStatement { Expression = arg1 };
case ILCode.Unaligned: return InlineAssembly(byteCode, args);
case ILCode.Volatile: return InlineAssembly(byteCode, args);
case ILCode.YieldBreak: case ILCode.YieldBreak:
return new Ast.YieldBreakStatement(); return new Ast.YieldBreakStatement();
case ILCode.YieldReturn: case ILCode.YieldReturn:
return new Ast.YieldStatement { Expression = arg1 }; return new Ast.YieldStatement { Expression = arg1 };
default: throw new Exception("Unknown OpCode: " + byteCode.Code); default: throw new Exception("Unknown OpCode: " + byteCode.Code);
} }
} }
@ -712,6 +651,31 @@ namespace ICSharpCode.Decompiler.Ast
return new IdentifierExpression(byteCode.Code.GetName()).Invoke(args); return new IdentifierExpression(byteCode.Code.GetName()).Invoke(args);
} }
static string FormatByteCodeOperand(object operand)
{
if (operand == null) {
return string.Empty;
//} else if (operand is ILExpression) {
// return string.Format("IL_{0:X2}", ((ILExpression)operand).Offset);
} else if (operand is MethodReference) {
return ((MethodReference)operand).Name + "()";
} else if (operand is Cecil.TypeReference) {
return ((Cecil.TypeReference)operand).FullName;
} else if (operand is VariableDefinition) {
return ((VariableDefinition)operand).Name;
} else if (operand is ParameterDefinition) {
return ((ParameterDefinition)operand).Name;
} else if (operand is FieldReference) {
return ((FieldReference)operand).Name;
} else if (operand is string) {
return "\"" + operand + "\"";
} else if (operand is int) {
return operand.ToString();
} else {
return operand.ToString();
}
}
static IEnumerable<AstType> ConvertTypeArguments(MethodReference cecilMethod) static IEnumerable<AstType> ConvertTypeArguments(MethodReference cecilMethod)
{ {
GenericInstanceMethod g = cecilMethod as GenericInstanceMethod; GenericInstanceMethod g = cecilMethod as GenericInstanceMethod;

44
ICSharpCode.Decompiler/ILAst/GotoRemoval.cs

@ -56,6 +56,28 @@ namespace ICSharpCode.Decompiler.ILAst
} }
} }
// Remove redundant break at the end of case
// Remove redundant case blocks altogether
foreach(ILSwitch ilSwitch in method.GetSelfAndChildrenRecursive<ILSwitch>()) {
foreach(ILBlock ilCase in ilSwitch.CaseBlocks) {
Debug.Assert(ilCase.EntryGoto == null);
int count = ilCase.Body.Count;
if (count >= 2) {
if (!ilCase.Body[count - 2].CanFallThough() &&
ilCase.Body[count - 1].Match(ILCode.LoopOrSwitchBreak)) {
ilCase.Body.RemoveAt(count - 1);
}
}
}
var defaultCase = ilSwitch.CaseBlocks.Where(cb => cb.Values == null).SingleOrDefault();
// If there is no default block, remove empty case blocks
if (defaultCase == null || (defaultCase.Body.Count == 1 && defaultCase.Body.Single().Match(ILCode.LoopOrSwitchBreak))) {
ilSwitch.CaseBlocks.RemoveAll(b => b.Body.Count == 1 && b.Body.Single().Match(ILCode.LoopOrSwitchBreak));
}
}
// Remove redundant return // Remove redundant return
if (method.Body.Count > 0 && method.Body.Last().Match(ILCode.Ret) && ((ILExpression)method.Body.Last()).Arguments.Count == 0) { if (method.Body.Count > 0 && method.Body.Last().Match(ILCode.Ret) && ((ILExpression)method.Body.Last()).Arguments.Count == 0) {
method.Body.RemoveAt(method.Body.Count - 1); method.Body.RemoveAt(method.Body.Count - 1);
@ -98,21 +120,15 @@ namespace ICSharpCode.Decompiler.ILAst
return true; return true;
} }
// TODO: Swich also qualifies for break; ILNode breakBlock = GetParents(gotoExpr).Where(n => n is ILWhileLoop || n is ILSwitch).FirstOrDefault();
ILWhileLoop loop = null; if (breakBlock != null && target == Exit(breakBlock, new HashSet<ILNode>() { gotoExpr })) {
ILNode current = gotoExpr; gotoExpr.Code = ILCode.LoopOrSwitchBreak;
while(loop == null && current != null) {
current = parent[current];
loop = current as ILWhileLoop;
}
if (loop != null && target == Exit(loop, new HashSet<ILNode>() { gotoExpr })) {
gotoExpr.Code = ILCode.LoopBreak;
gotoExpr.Operand = null; gotoExpr.Operand = null;
return true; return true;
} }
if (loop != null && target == Enter(loop, new HashSet<ILNode>() { gotoExpr })) { ILNode continueBlock = GetParents(gotoExpr).Where(n => n is ILWhileLoop).FirstOrDefault();
if (continueBlock != null && target == Enter(continueBlock, new HashSet<ILNode>() { gotoExpr })) {
gotoExpr.Code = ILCode.LoopContinue; gotoExpr.Code = ILCode.LoopContinue;
gotoExpr.Operand = null; gotoExpr.Operand = null;
return true; return true;
@ -172,6 +188,12 @@ namespace ICSharpCode.Decompiler.ILAst
} }
} else if (expr.Code == ILCode.Nop) { } else if (expr.Code == ILCode.Nop) {
return Exit(expr, visitedNodes); return Exit(expr, visitedNodes);
} else if (expr.Code == ILCode.LoopOrSwitchBreak) {
ILNode breakBlock = GetParents(expr).Where(n => n is ILWhileLoop || n is ILSwitch).First();
return Exit(breakBlock, new HashSet<ILNode>() { expr });
} else if (expr.Code == ILCode.LoopContinue) {
ILNode continueBlock = GetParents(expr).Where(n => n is ILWhileLoop).First();
return Enter(continueBlock, new HashSet<ILNode>() { expr });
} else { } else {
return expr; return expr;
} }

226
ICSharpCode.Decompiler/ILAst/ILAstOptimizer.cs

@ -105,6 +105,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression expr = block.Body[i] as ILExpression; ILExpression expr = block.Body[i] as ILExpression;
if (expr != null && expr.Prefixes == null) { if (expr != null && expr.Prefixes == null) {
switch(expr.Code) { switch(expr.Code) {
case ILCode.Switch:
case ILCode.Brtrue: case ILCode.Brtrue:
expr.Arguments.Single().ILRanges.AddRange(expr.ILRanges); expr.Arguments.Single().ILRanges.AddRange(expr.ILRanges);
expr.ILRanges.Clear(); expr.ILRanges.Clear();
@ -239,40 +240,26 @@ namespace ICSharpCode.Decompiler.ILAst
} while(modified); } while(modified);
} }
bool IsStloc(ILBasicBlock bb, ref ILVariable locVar, ref ILExpression val, ref ILLabel fallLabel)
{
if (bb.Body.Count == 1) {
ILExpression expr;
if (bb.Body[0].Match(ILCode.Stloc, out expr)) {
locVar = (ILVariable)expr.Operand;
val = expr.Arguments[0];
fallLabel = (ILLabel)bb.FallthoughGoto.Operand;
return true;
}
}
return false;
}
// scope is modified if successful // scope is modified if successful
bool TrySimplifyTernaryOperator(List<ILNode> scope, ILBasicBlock head) bool TrySimplifyTernaryOperator(List<ILNode> scope, ILBasicBlock head)
{ {
Debug.Assert(scope.Contains(head)); Debug.Assert(scope.Contains(head));
ILExpression condExpr = null; ILExpression condExpr;
ILLabel trueLabel = null; ILLabel trueLabel;
ILLabel falseLabel = null; ILLabel falseLabel;
ILVariable trueLocVar = null; ILVariable trueLocVar;
ILExpression trueExpr = null; ILExpression trueExpr;
ILLabel trueFall = null; ILLabel trueFall;
ILVariable falseLocVar = null; ILVariable falseLocVar;
ILExpression falseExpr = null; ILExpression falseExpr;
ILLabel falseFall = null; ILLabel falseFall;
if(head.MatchBrTure(out condExpr, out trueLabel, out falseLabel) && if(head.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel) &&
labelGlobalRefCount[trueLabel] == 1 && labelGlobalRefCount[trueLabel] == 1 &&
labelGlobalRefCount[falseLabel] == 1 && labelGlobalRefCount[falseLabel] == 1 &&
IsStloc(labelToBasicBlock[trueLabel], ref trueLocVar, ref trueExpr, ref trueFall) && labelToBasicBlock[trueLabel].Match(ILCode.Stloc, out trueLocVar, out trueExpr, out trueFall) &&
IsStloc(labelToBasicBlock[falseLabel], ref falseLocVar, ref falseExpr, ref falseFall) && labelToBasicBlock[falseLabel].Match(ILCode.Stloc, out falseLocVar, out falseExpr, out falseFall) &&
trueLocVar == falseLocVar && trueLocVar == falseLocVar &&
trueFall == falseFall) trueFall == falseFall)
{ {
@ -301,7 +288,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condExpr; ILExpression condExpr;
ILLabel trueLabel; ILLabel trueLabel;
ILLabel falseLabel; ILLabel falseLabel;
if(head.MatchBrTure(out condExpr, out trueLabel, out falseLabel)) { if(head.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel)) {
for (int pass = 0; pass < 2; pass++) { for (int pass = 0; pass < 2; pass++) {
// On the second pass, swap labels and negate expression of the first branch // On the second pass, swap labels and negate expression of the first branch
@ -317,7 +304,7 @@ namespace ICSharpCode.Decompiler.ILAst
if (scope.Contains(nextBasicBlock) && if (scope.Contains(nextBasicBlock) &&
nextBasicBlock != head && nextBasicBlock != head &&
labelGlobalRefCount[nextBasicBlock.EntryLabel] == 1 && labelGlobalRefCount[nextBasicBlock.EntryLabel] == 1 &&
nextBasicBlock.MatchBrTure(out nextCondExpr, out nextTrueLablel, out nextFalseLabel) && nextBasicBlock.Match(ILCode.Brtrue, out nextTrueLablel, out nextCondExpr, out nextFalseLabel) &&
(otherLablel == nextFalseLabel || otherLablel == nextTrueLablel)) (otherLablel == nextFalseLabel || otherLablel == nextTrueLablel))
{ {
// Create short cicuit branch // Create short cicuit branch
@ -358,9 +345,7 @@ namespace ICSharpCode.Decompiler.ILAst
foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>()) { foreach(ILBlock block in method.GetSelfAndChildrenRecursive<ILBlock>()) {
for (int i = 0; i < block.Body.Count; i++) { for (int i = 0; i < block.Body.Count; i++) {
ILLabel targetLabel; ILLabel targetLabel;
if (block.Body[i].Match(ILCode.Br, out targetLabel) || if (block.Body[i].Match(ILCode.Br, out targetLabel) || block.Body[i].Match(ILCode.Leave, out targetLabel)) {
block.Body[i].Match(ILCode.Leave, out targetLabel))
{
// Skip extra labels // Skip extra labels
while(nextSibling.ContainsKey(targetLabel) && nextSibling[targetLabel] is ILLabel) { while(nextSibling.ContainsKey(targetLabel) && nextSibling[targetLabel] is ILLabel) {
targetLabel = (ILLabel)nextSibling[targetLabel]; targetLabel = (ILLabel)nextSibling[targetLabel];
@ -368,18 +353,23 @@ namespace ICSharpCode.Decompiler.ILAst
// Inline return statement // Inline return statement
ILNode target; ILNode target;
ILExpression retExpr; List<ILExpression> retArgs;
if (nextSibling.TryGetValue(targetLabel, out target) && if (nextSibling.TryGetValue(targetLabel, out target)) {
target.Match(ILCode.Ret, out retExpr)) if (target.Match(ILCode.Ret, out retArgs)) {
{ ILVariable locVar;
ILVariable locVar; object constValue;
object constValue; if (retArgs.Count == 0) {
if (retExpr.Arguments.Count == 0) { block.Body[i] = new ILExpression(ILCode.Ret, null);
} else if (retArgs.Single().Match(ILCode.Ldloc, out locVar)) {
block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldloc, locVar));
} else if (retArgs.Single().Match(ILCode.Ldc_I4, out constValue)) {
block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldc_I4, constValue));
}
}
} else {
if (method.Body.Count > 0 && method.Body.Last() == targetLabel) {
// It exits the main method - so it is same as return;
block.Body[i] = new ILExpression(ILCode.Ret, null); block.Body[i] = new ILExpression(ILCode.Ret, null);
} else if (retExpr.Arguments.Single().Match(ILCode.Ldloc, out locVar)) {
block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldloc, locVar));
} else if (retExpr.Arguments.Single().Match(ILCode.Ldc_I4, out constValue)) {
block.Body[i] = new ILExpression(ILCode.Ret, null, new ILExpression(ILCode.Ldc_I4, constValue));
} }
} }
} }
@ -470,7 +460,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condExpr; ILExpression condExpr;
ILLabel trueLabel; ILLabel trueLabel;
ILLabel falseLabel; ILLabel falseLabel;
if(basicBlock.MatchBrTure(out condExpr, out trueLabel, out falseLabel)) if(basicBlock.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel))
{ {
ControlFlowNode trueTarget; ControlFlowNode trueTarget;
labelToCfNode.TryGetValue(trueLabel, out trueTarget); labelToCfNode.TryGetValue(trueLabel, out trueTarget);
@ -583,26 +573,32 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condBranch = block.Body[0] as ILExpression; ILExpression condBranch = block.Body[0] as ILExpression;
// Switch // Switch
if (condBranch != null && condBranch.Operand is ILLabel[] && condBranch.Arguments.Count > 0) { ILLabel[] caseLabels;
List<ILExpression> switchArgs;
ILLabel[] caseLabels = (ILLabel[])condBranch.Operand; if (condBranch.Match(ILCode.Switch, out caseLabels, out switchArgs)) {
// The labels will not be used - kill them
condBranch.Operand = null;
ILSwitch ilSwitch = new ILSwitch() { Condition = condBranch }; ILSwitch ilSwitch = new ILSwitch() { Condition = switchArgs.Single() };
result.Add(new ILBasicBlock() { ILBasicBlock newBB = new ILBasicBlock() {
EntryLabel = block.EntryLabel, // Keep the entry label EntryLabel = block.EntryLabel, // Keep the entry label
Body = { ilSwitch }, Body = { ilSwitch },
FallthoughGoto = block.FallthoughGoto FallthoughGoto = block.FallthoughGoto
}); };
result.Add(newBB);
// Remove the item so that it is not picked up as content // Remove the item so that it is not picked up as content
scope.RemoveOrThrow(node); scope.RemoveOrThrow(node);
// Find the switch offset
int addValue = 0;
List<ILExpression> subArgs;
if (ilSwitch.Condition.Match(ILCode.Sub, out subArgs) && subArgs[1].Match(ILCode.Ldc_I4, out addValue)) {
ilSwitch.Condition = subArgs[0];
}
// Pull in code of cases // Pull in code of cases
ILLabel fallLabel = (ILLabel)block.FallthoughGoto.Operand;
ControlFlowNode fallTarget = null; ControlFlowNode fallTarget = null;
labelToCfNode.TryGetValue((ILLabel)block.FallthoughGoto.Operand, out fallTarget); labelToCfNode.TryGetValue(fallLabel, out fallTarget);
HashSet<ControlFlowNode> frontiers = new HashSet<ControlFlowNode>(); HashSet<ControlFlowNode> frontiers = new HashSet<ControlFlowNode>();
if (fallTarget != null) if (fallTarget != null)
@ -615,19 +611,44 @@ namespace ICSharpCode.Decompiler.ILAst
frontiers.UnionWith(condTarget.DominanceFrontier); frontiers.UnionWith(condTarget.DominanceFrontier);
} }
foreach(ILLabel condLabel in caseLabels) { for (int i = 0; i < caseLabels.Length; i++) {
ControlFlowNode condTarget = null; ILLabel condLabel = caseLabels[i];
labelToCfNode.TryGetValue(condLabel, out condTarget);
// Find or create new case block
ILSwitch.CaseBlock caseBlock = ilSwitch.CaseBlocks.Where(b => b.EntryGoto.Operand == condLabel).FirstOrDefault();
if (caseBlock == null) {
caseBlock = new ILSwitch.CaseBlock() {
Values = new List<int>(),
EntryGoto = new ILExpression(ILCode.Br, condLabel)
};
ilSwitch.CaseBlocks.Add(caseBlock);
ControlFlowNode condTarget = null;
labelToCfNode.TryGetValue(condLabel, out condTarget);
if (condTarget != null && !frontiers.Contains(condTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, condTarget);
scope.ExceptWith(content);
caseBlock.Body.AddRange(FindConditions(content, condTarget));
// Add explicit break which should not be used by default, but the goto removal might decide to use it
caseBlock.Body.Add(new ILBasicBlock() { Body = { new ILExpression(ILCode.LoopOrSwitchBreak, null) } });
}
}
caseBlock.Values.Add(i + addValue);
}
// Heuristis to determine if we want to use fallthough as default case
if (fallTarget != null && !frontiers.Contains(fallTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, fallTarget);
if (content.Any()) {
var caseBlock = new ILSwitch.CaseBlock() { EntryGoto = new ILExpression(ILCode.Br, fallLabel) };
ilSwitch.CaseBlocks.Add(caseBlock);
newBB.FallthoughGoto = null;
ILBlock caseBlock = new ILBlock() {
EntryGoto = new ILExpression(ILCode.Br, condLabel)
};
if (condTarget != null && !frontiers.Contains(condTarget)) {
HashSet<ControlFlowNode> content = FindDominatedNodes(scope, condTarget);
scope.ExceptWith(content); scope.ExceptWith(content);
caseBlock.Body.AddRange(FindConditions(content, condTarget)); caseBlock.Body.AddRange(FindConditions(content, fallTarget));
// Add explicit break which should not be used by default, but the goto removal might decide to use it
caseBlock.Body.Add(new ILBasicBlock() { Body = { new ILExpression(ILCode.LoopOrSwitchBreak, null) } });
} }
ilSwitch.CaseBlocks.Add(caseBlock);
} }
} }
@ -635,7 +656,7 @@ namespace ICSharpCode.Decompiler.ILAst
ILExpression condExpr; ILExpression condExpr;
ILLabel trueLabel; ILLabel trueLabel;
ILLabel falseLabel; ILLabel falseLabel;
if(block.MatchBrTure(out condExpr, out trueLabel, out falseLabel)) { if(block.Match(ILCode.Brtrue, out trueLabel, out condExpr, out falseLabel)) {
// Swap bodies since that seems to be the usual C# order // Swap bodies since that seems to be the usual C# order
ILLabel temp = trueLabel; ILLabel temp = trueLabel;
@ -784,8 +805,8 @@ namespace ICSharpCode.Decompiler.ILAst
for (int i = 0; i < block.Body.Count; i++) { for (int i = 0; i < block.Body.Count; i++) {
ILCondition cond = block.Body[i] as ILCondition; ILCondition cond = block.Body[i] as ILCondition;
if (cond != null) { if (cond != null) {
bool trueExits = cond.TrueBlock.Body.Count > 0 && !cond.TrueBlock.Body.Last().CanFallthough(); bool trueExits = cond.TrueBlock.Body.Count > 0 && !cond.TrueBlock.Body.Last().CanFallThough();
bool falseExits = cond.FalseBlock.Body.Count > 0 && !cond.FalseBlock.Body.Last().CanFallthough(); bool falseExits = cond.FalseBlock.Body.Count > 0 && !cond.FalseBlock.Body.Last().CanFallThough();
if (trueExits) { if (trueExits) {
// Move the false block after the condition // Move the false block after the condition
@ -825,53 +846,74 @@ namespace ICSharpCode.Decompiler.ILAst
return expr != null && expr.Prefixes == null && expr.Code == code; return expr != null && expr.Prefixes == null && expr.Code == code;
} }
public static bool Match(this ILNode node, ILCode code, out ILExpression expr) public static bool Match<T>(this ILNode node, ILCode code, out T operand)
{ {
expr = node as ILExpression; ILExpression expr = node as ILExpression;
return expr != null && expr.Prefixes == null && expr.Code == code; if (expr != null && expr.Prefixes == null && expr.Code == code) {
operand = (T)expr.Operand;
Debug.Assert(expr.Arguments.Count == 0);
return true;
}
operand = default(T);
return false;
} }
public static bool Match<T>(this ILNode node, ILCode code, out T operand) public static bool Match(this ILNode node, ILCode code, out List<ILExpression> args)
{
ILExpression expr = node as ILExpression;
if (expr != null && expr.Prefixes == null && expr.Code == code) {
Debug.Assert(expr.Operand == null);
args = expr.Arguments;
return true;
}
args = null;
return false;
}
public static bool Match<T>(this ILNode node, ILCode code, out T operand, out List<ILExpression> args)
{ {
ILExpression expr = node as ILExpression; ILExpression expr = node as ILExpression;
if (expr != null && expr.Prefixes == null && expr.Code == code) { if (expr != null && expr.Prefixes == null && expr.Code == code) {
operand = (T)expr.Operand; operand = (T)expr.Operand;
args = expr.Arguments;
return true; return true;
} }
operand = default(T); operand = default(T);
args = null;
return false;
}
public static bool Match<T>(this ILNode node, ILCode code, out T operand, out ILExpression arg)
{
List<ILExpression> args;
if (node.Match(code, out operand, out args)) {
arg = args.Single();
return true;
}
arg = null;
return false; return false;
} }
public static bool MatchBrTure(this ILBasicBlock bb, out ILExpression condition, out ILLabel trueLabel, out ILLabel falseLabel) public static bool Match<T>(this ILBasicBlock bb, ILCode code, out T operand, out ILExpression arg, out ILLabel fallLabel)
{ {
if (bb.Body.Count == 1) { if (bb.Body.Count == 1) {
if (bb.Body[0].Match(ILCode.Brtrue, out trueLabel)) { if (bb.Body[0].Match(code, out operand, out arg)) {
condition = ((ILExpression)bb.Body[0]).Arguments.Single(); fallLabel = (ILLabel)bb.FallthoughGoto.Operand;
falseLabel = (ILLabel)((ILExpression)bb.FallthoughGoto).Operand;
return true; return true;
} }
} }
condition = null; operand = default(T);
trueLabel = null; arg = null;
falseLabel = null; fallLabel = null;
return false; return false;
} }
public static bool CanFallthough(this ILNode node) public static bool CanFallThough(this ILNode node)
{ {
// TODO: similar to ILCodes.CanFallThough, but handles slightly different cases?? // TODO: similar to ILCodes.CanFallThough, but handles slightly different cases??
ILExpression expr = node as ILExpression; ILExpression expr = node as ILExpression;
if (expr != null) { if (expr != null) {
switch(expr.Code) { return expr.Code.CanFallThough();
case ILCode.Br:
case ILCode.Ret:
case ILCode.Throw:
case ILCode.Rethrow:
case ILCode.LoopContinue:
case ILCode.LoopBreak:
case ILCode.YieldBreak:
return false;
}
} }
return true; return true;
} }

26
ICSharpCode.Decompiler/ILAst/ILAstTypes.cs

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -458,8 +459,24 @@ namespace ICSharpCode.Decompiler.ILAst
public class ILSwitch: ILNode public class ILSwitch: ILNode
{ {
public class CaseBlock: ILBlock
{
public List<int> Values; // null for the default case
public override void WriteTo(ITextOutput output)
{
Debug.Assert(Values.Count > 0);
foreach (int i in this.Values) {
output.WriteLine("case {0}:", i);
}
output.Indent();
base.WriteTo(output);
output.Unindent();
}
}
public ILExpression Condition; public ILExpression Condition;
public List<ILBlock> CaseBlocks = new List<ILBlock>(); public List<CaseBlock> CaseBlocks = new List<CaseBlock>();
public override IEnumerable<ILNode> GetChildren() public override IEnumerable<ILNode> GetChildren()
{ {
@ -476,11 +493,8 @@ namespace ICSharpCode.Decompiler.ILAst
Condition.WriteTo(output); Condition.WriteTo(output);
output.WriteLine(") {"); output.WriteLine(") {");
output.Indent(); output.Indent();
for (int i = 0; i < CaseBlocks.Count; i++) { foreach (CaseBlock caseBlock in this.CaseBlocks) {
output.WriteLine("case {0}:", i); caseBlock.WriteTo(output);
output.Indent();
CaseBlocks[i].WriteTo(output);
output.Unindent();
} }
output.Unindent(); output.Unindent();
output.WriteLine("}"); output.WriteLine("}");

4
ICSharpCode.Decompiler/ILAst/ILCodes.cs

@ -260,7 +260,7 @@ namespace ICSharpCode.Decompiler.ILAst
LogicOr, LogicOr,
InitArray, // Array Initializer InitArray, // Array Initializer
TernaryOp, // ?: TernaryOp, // ?:
LoopBreak, LoopOrSwitchBreak,
LoopContinue, LoopContinue,
Ldc_Decimal, Ldc_Decimal,
YieldBreak, YieldBreak,
@ -288,6 +288,8 @@ namespace ICSharpCode.Decompiler.ILAst
case ILCode.Endfinally: case ILCode.Endfinally:
case ILCode.Throw: case ILCode.Throw:
case ILCode.Rethrow: case ILCode.Rethrow:
case ILCode.LoopContinue:
case ILCode.LoopOrSwitchBreak:
case ILCode.YieldBreak: case ILCode.YieldBreak:
return false; return false;
default: default:

2
ICSharpCode.Decompiler/ILAst/TypeAnalysis.cs

@ -456,6 +456,8 @@ namespace ICSharpCode.Decompiler.ILAst
case ILCode.Switch: case ILCode.Switch:
case ILCode.Throw: case ILCode.Throw:
case ILCode.Rethrow: case ILCode.Rethrow:
case ILCode.LoopOrSwitchBreak:
case ILCode.LoopContinue:
return null; return null;
case ILCode.Ret: case ILCode.Ret:
if (forceInferChildren && expr.Arguments.Count == 1) if (forceInferChildren && expr.Arguments.Count == 1)

18
NRefactory/ICSharpCode.NRefactory/CSharp/OutputVisitor/OutputVisitor.cs

@ -1529,8 +1529,13 @@ namespace ICSharpCode.NRefactory.CSharp
public object VisitSwitchSection(SwitchSection switchSection, object data) public object VisitSwitchSection(SwitchSection switchSection, object data)
{ {
StartNode(switchSection); StartNode(switchSection);
foreach (var label in switchSection.CaseLabels) bool first = true;
foreach (var label in switchSection.CaseLabels) {
if (!first)
NewLine();
label.AcceptVisitor(this, data); label.AcceptVisitor(this, data);
first = false;
}
foreach (var statement in switchSection.Statements) foreach (var statement in switchSection.Statements)
statement.AcceptVisitor(this, data); statement.AcceptVisitor(this, data);
return EndNode(switchSection); return EndNode(switchSection);
@ -1539,11 +1544,14 @@ namespace ICSharpCode.NRefactory.CSharp
public object VisitCaseLabel(CaseLabel caseLabel, object data) public object VisitCaseLabel(CaseLabel caseLabel, object data)
{ {
StartNode(caseLabel); StartNode(caseLabel);
WriteKeyword("case"); if (caseLabel.Expression.IsNull) {
Space(); WriteKeyword("default");
caseLabel.Expression.AcceptVisitor(this, data); } else {
WriteKeyword("case");
Space();
caseLabel.Expression.AcceptVisitor(this, data);
}
WriteToken(":", CaseLabel.Roles.Colon); WriteToken(":", CaseLabel.Roles.Colon);
NewLine();
return EndNode(caseLabel); return EndNode(caseLabel);
} }

Loading…
Cancel
Save