From 3e40b08ba005643bd0190fe45437a82404519c16 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Wed, 28 Oct 2020 00:49:13 +0100 Subject: [PATCH] compiler: implement negate for complex numbers --- compiler/compiler.go | 10 ++++++++++ testdata/float.go | 4 +++- testdata/float.txt | 2 ++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/compiler/compiler.go b/compiler/compiler.go index 4a42bc69..1992fee6 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -2581,6 +2581,16 @@ func (b *builder) createUnOp(unop *ssa.UnOp) (llvm.Value, error) { return b.CreateSub(llvm.ConstInt(x.Type(), 0, false), x, ""), nil } else if typ.Info()&types.IsFloat != 0 { return b.CreateFNeg(x, ""), nil + } else if typ.Info()&types.IsComplex != 0 { + // Negate both components of the complex number. + r := b.CreateExtractValue(x, 0, "r") + i := b.CreateExtractValue(x, 1, "i") + r = b.CreateFNeg(r, "") + i = b.CreateFNeg(i, "") + cplx := llvm.Undef(x.Type()) + cplx = b.CreateInsertValue(cplx, r, 0, "") + cplx = b.CreateInsertValue(cplx, i, 1, "") + return cplx, nil } else { return llvm.Value{}, b.makeError(unop.Pos(), "todo: unknown basic type for negate: "+typ.String()) } diff --git a/testdata/float.go b/testdata/float.go index f2b7c52e..8c33cf11 100644 --- a/testdata/float.go +++ b/testdata/float.go @@ -57,15 +57,17 @@ func main() { println(complex64(c128)) println(complex128(c64)) - // binops on complex numbers + // binops and negate on complex numbers c64 = 5 + 2i println("complex64 add: ", c64+-3+8i) println("complex64 sub: ", c64 - -3 + 8i) println("complex64 mul: ", c64*-3+8i) println("complex64 div: ", c64/-3+8i) + println("complex64 neg: ", -c64) c128 = -5 + 2i println("complex128 add:", c128+2+6i) println("complex128 sub:", c128-2+6i) println("complex128 mul:", c128*2+6i) println("complex128 div:", c128/2+6i) + println("complex128 neg:", -c128) } diff --git a/testdata/float.txt b/testdata/float.txt index 4b7e3357..dbc36fb8 100644 --- a/testdata/float.txt +++ b/testdata/float.txt @@ -27,7 +27,9 @@ complex64 add: (+2.000000e+000+1.000000e+001i) complex64 sub: (+8.000000e+000+1.000000e+001i) complex64 mul: (-1.500000e+001+2.000000e+000i) complex64 div: (-1.666667e+000+7.333333e+000i) +complex64 neg: (-5.000000e+000-2.000000e+000i) complex128 add: (-3.000000e+000+8.000000e+000i) complex128 sub: (-7.000000e+000+8.000000e+000i) complex128 mul: (-1.000000e+001+1.000000e+001i) complex128 div: (-2.500000e+000+7.000000e+000i) +complex128 neg: (+5.000000e+000-2.000000e+000i)