Skip to content

Commit

Permalink
compiler: optimize expressions such as x-x to 0 if possible and the -…
Browse files Browse the repository at this point in the history
…-opt-math flag passed
  • Loading branch information
mertcandav committed Oct 13, 2024
1 parent f3fd07a commit af24c3a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/julec/opt/expr.jule
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,16 @@ impl exprOptimizer {
m.Op.Kind = token::Kind.Shl
m.Right.Model = constant::Const.NewU64(1)
ret
| token::Id.Minus:
// If type is integer and expressions is like "x-x", then we can simplfy to "0" which is cheaper.
// Floating-point types is exceptional because we cannot predict the result because of NaN or similar values.
if !types::IsInt(lp.Kind) || !equalModels(m.Left.Model, m.Right.Model) {
break
}
mut c := constant::Const.NewU64(0)
c.Kind = lp.Kind
*self.model = c
ret
}

// Check whether the right operand is constant for safety.
Expand Down
3 changes: 3 additions & 0 deletions src/julec/opt/scope.jule
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,9 @@ impl scopeOptimizer {
| token::Id.PlusEq:
assign.Op.Id = token::Id.Plus
assign.Op.Kind = token::Kind.Plus
| token::Id.MinusEq:
assign.Op.Id = token::Id.Minus
assign.Op.Kind = token::Kind.Minus
| token::Id.SolidusEq:
assign.Op.Id = token::Id.Solidus
assign.Op.Kind = token::Kind.Solidus
Expand Down

0 comments on commit af24c3a

Please sign in to comment.