Skip to content

Commit

Permalink
Use unary negation '-a' instead of '0 - a'.
Browse files Browse the repository at this point in the history
  • Loading branch information
dgrunwald committed Oct 2, 2017
1 parent 8e634bc commit 8533eda
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,22 @@ TranslatedExpression HandleBinaryNumeric(BinaryNumericInstruction inst, BinaryOp
left = PrepareArithmeticArgument(left, inst.LeftInputType, inst.Sign, inst.IsLifted);
right = PrepareArithmeticArgument(right, inst.RightInputType, inst.Sign, inst.IsLifted);

if (op == BinaryOperatorType.Subtract && inst.Left.MatchLdcI(0)) {
IType rightUType = NullableType.GetUnderlyingType(right.Type);
if (rightUType.IsKnownType(KnownTypeCode.Int32) || rightUType.IsKnownType(KnownTypeCode.Int64) || rightUType.IsCSharpSmallIntegerType()) {
// unary minus is supported on signed int and long, and on the small integer types (since they promote to int)
var uoe = new UnaryOperatorExpression(UnaryOperatorType.Minus, right.Expression);
uoe.AddAnnotation(inst.CheckForOverflow ? AddCheckedBlocks.CheckedAnnotation : AddCheckedBlocks.UncheckedAnnotation);
var resultType = rightUType.IsKnownType(KnownTypeCode.Int64) ? rightUType : compilation.FindType(KnownTypeCode.Int32);
if (inst.IsLifted)
resultType = NullableType.Create(compilation, resultType);
return uoe.WithILInstruction(inst).WithRR(new OperatorResolveResult(
resultType,
inst.CheckForOverflow ? ExpressionType.NegateChecked : ExpressionType.Negate,
right.ResolveResult));
}
}

var rr = resolverWithOverflowCheck.ResolveBinaryOperator(op, left.ResolveResult, right.ResolveResult);
if (rr.IsError || NullableType.GetUnderlyingType(rr.Type).GetStackType() != inst.UnderlyingResultType
|| !IsCompatibleWithSign(left.Type, inst.Sign) || !IsCompatibleWithSign(right.Type, inst.Sign))
Expand Down
5 changes: 5 additions & 0 deletions ICSharpCode.Decompiler/IL/Instructions/PatternMatching.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ public bool MatchLdcI(out long val)
return false;
}

public bool MatchLdcI(long val)
{
return MatchLdcI(out long v) && v == val;
}

public bool MatchLdLoc(ILVariable variable)
{
var inst = this as LdLoc;
Expand Down

0 comments on commit 8533eda

Please sign in to comment.