>From 791962ede7fa19f2aa863d48bf1a84dbf592b650 Mon Sep 17 00:00:00 2001
From: Jordan Waughtal <jmwaughtal1@gmail.com>
Date: Sat, 12 Sep 2026 22:37:59 -0500
Subject: [PATCH] Add C99 complex number support
To: tinycc-devel@nongnu.org

Add the C99 float, double and long double _Complex types, including
imaginary constants, initializers, conversions, arithmetic, equality,
function calls and returns, and the __builtin_complex constructor.

tccgen.c, tccpp.c, tcc.h:
- Parse _Complex type specifiers and i/j floating suffixes.
- Represent each complex type as two ABI-compatible real components.
- Handle constants, lvalues, casts, initializers and usual arithmetic
  conversions without losing long-double precision.
- Lower nonconstant multiplication and division to typed runtime helpers.

x86_64-gen.c, tccdbg.c:
- Classify complex parameters and returns for the x86-64 ABI.
- Emit DW_ATE_complex_float debug types.

lib/complex-arith.c:
- Add range-aware multiply and divide helpers for all three precisions,
  including infinity and NaN recovery.

win32/include/complex.h, lib/tcc-complex.c, include/tgmath.h:
- Provide the C99 complex function family for the Windows runtime.
- Add C11 CMPLX macros and complex type-generic dispatch.

tests/tests2/149_complex_runtime.c:
- Exercise runtime multiplication and division in all three precisions.

Tested with the upstream suite on Linux x86-64:

    ./configure
    make -j4
    make test

The wrapper project's controlled complex suites also pass 15/15 on each
of the Windows i386, x86-64 and ARM64 package targets.
---
 include/float.h                         |  16 +-
 include/tccdefs.h                       |   1 -
 include/tgmath.h                        |  62 ++-
 lib/Makefile                            |   5 +-
 lib/complex-arith.c                     | 155 ++++++
 lib/tcc-complex.c                       | 322 +++++++++++++
 tcc.h                                   |  15 +-
 tccdbg.c                                |  40 ++
 tccgen.c                                | 611 +++++++++++++++++++++++-
 tccpp.c                                 |  23 +-
 tcctok.h                                |   5 +
 tests/tests2/149_complex_runtime.c      |  65 +++
 tests/tests2/149_complex_runtime.expect |   1 +
 win32/build-tcc.bat                     |   4 +-
 win32/include/complex.h                 |  96 ++++
 win32/include/tcc/tcc_libm.h            |   8 +
 x86_64-gen.c                            |  36 ++
 17 files changed, 1427 insertions(+), 38 deletions(-)
 create mode 100644 lib/complex-arith.c
 create mode 100644 lib/tcc-complex.c
 create mode 100644 tests/tests2/149_complex_runtime.c
 create mode 100644 tests/tests2/149_complex_runtime.expect
 create mode 100644 win32/include/complex.h

diff --git a/include/float.h b/include/float.h
index 4caa4236..f6913bf8 100644
--- a/include/float.h
+++ b/include/float.h
@@ -26,8 +26,22 @@
 #define DBL_MAX 1.7976931348623157e+308
 #define DBL_MAX_10_EXP 308
 
+/* Windows TinyCC uses the ABI's double-width long double. */
+#if defined _WIN32
+
+#define LDBL_MANT_DIG 53
+#define LDBL_DIG 15
+#define LDBL_EPSILON 2.2204460492503131e-16L
+#define LDBL_MIN_EXP (-1021)
+#define LDBL_MIN 2.2250738585072014e-308L
+#define LDBL_MIN_10_EXP (-307)
+#define LDBL_MAX_EXP 1024
+#define LDBL_MAX 1.7976931348623157e+308L
+#define LDBL_MAX_10_EXP 308
+#define DECIMAL_DIG 17
+
 /* horrible intel long double */
-#if defined __i386__ || defined __x86_64__
+#elif defined __i386__ || defined __x86_64__
 
 #define LDBL_MANT_DIG 64
 #define LDBL_DIG 18
diff --git a/include/tccdefs.h b/include/tccdefs.h
index 2655c1dd..c0eaeed4 100644
--- a/include/tccdefs.h
+++ b/include/tccdefs.h
@@ -70,7 +70,6 @@
 
     #if __STDC_VERSION__ >= 201112L
     # define __STDC_NO_ATOMICS__ 1
-    # define __STDC_NO_COMPLEX__ 1
     # define __STDC_NO_THREADS__ 1
 #if !defined _WIN32
     # define __STDC_UTF_16__ 1
diff --git a/include/tgmath.h b/include/tgmath.h
index 5d3e3578..998cc4a0 100644
--- a/include/tgmath.h
+++ b/include/tgmath.h
@@ -6,8 +6,14 @@
 #define _TGMATH_H
 
 #include <math.h>
+#include <complex.h>
 
 #ifndef __cplusplus
+#define __tgmath_shared(x, F) \
+  _Generic ((x), \
+    float: F##f, long double: F##l, \
+    float complex: c##F##f, double complex: c##F, \
+    long double complex: c##F##l, default: F)(x)
 #define __tgmath_real(x, F) \
   _Generic ((x), float: F##f, long double: F##l, default: F)(x)
 #define __tgmath_real_2_1(x, y, F) \
@@ -18,25 +24,44 @@
   _Generic ((x)+(y), float: F##f, long double: F##l, default: F)(x, y, z)
 #define __tgmath_real_3(x, y, z, F) \
   _Generic ((x)+(y)+(z), float: F##f, long double: F##l, default: F)(x, y, z)
+#define __tgmath_pow(x, y) \
+  _Generic ((x)+(y), \
+    float: powf((x), (y)), long double: powl((x), (y)), \
+    float complex: cpowf(((float complex[]){(x)})[0], \
+                         ((float complex[]){(y)})[0]), \
+    double complex: cpow(((double complex[]){(x)})[0], \
+                         ((double complex[]){(y)})[0]), \
+    long double complex: \
+      cpowl(((long double complex[]){(x)})[0], \
+            ((long double complex[]){(y)})[0]), \
+    default: pow((x), (y)))
+#define __tgmath_abs(x) \
+  _Generic ((x), \
+    float: fabsf, long double: fabsl, \
+    float complex: cabsf, double complex: cabs, \
+    long double complex: cabsl, default: fabs)(x)
+#define __tgmath_cplx_only(x, F) \
+  _Generic ((x), \
+    float complex: F##f, long double complex: F##l, default: F)(x)
 
 /* Functions defined in both <math.h> and <complex.h> (7.22p4) */
-#define acos(z)          __tgmath_real(z, acos)
-#define asin(z)          __tgmath_real(z, asin)
-#define atan(z)          __tgmath_real(z, atan)
-#define acosh(z)         __tgmath_real(z, acosh)
-#define asinh(z)         __tgmath_real(z, asinh)
-#define atanh(z)         __tgmath_real(z, atanh)
-#define cos(z)           __tgmath_real(z, cos)
-#define sin(z)           __tgmath_real(z, sin)
-#define tan(z)           __tgmath_real(z, tan)
-#define cosh(z)          __tgmath_real(z, cosh)
-#define sinh(z)          __tgmath_real(z, sinh)
-#define tanh(z)          __tgmath_real(z, tanh)
-#define exp(z)           __tgmath_real(z, exp)
-#define log(z)           __tgmath_real(z, log)
-#define pow(z1,z2)       __tgmath_real_2(z1, z2, pow)
-#define sqrt(z)          __tgmath_real(z, sqrt)
-#define fabs(z)          __tgmath_real(z, fabs)
+#define acos(z)          __tgmath_shared(z, acos)
+#define asin(z)          __tgmath_shared(z, asin)
+#define atan(z)          __tgmath_shared(z, atan)
+#define acosh(z)         __tgmath_shared(z, acosh)
+#define asinh(z)         __tgmath_shared(z, asinh)
+#define atanh(z)         __tgmath_shared(z, atanh)
+#define cos(z)           __tgmath_shared(z, cos)
+#define sin(z)           __tgmath_shared(z, sin)
+#define tan(z)           __tgmath_shared(z, tan)
+#define cosh(z)          __tgmath_shared(z, cosh)
+#define sinh(z)          __tgmath_shared(z, sinh)
+#define tanh(z)          __tgmath_shared(z, tanh)
+#define exp(z)           __tgmath_shared(z, exp)
+#define log(z)           __tgmath_shared(z, log)
+#define pow(z1,z2)       __tgmath_pow(z1, z2)
+#define sqrt(z)          __tgmath_shared(z, sqrt)
+#define fabs(z)          __tgmath_abs(z)
 
 /* Functions defined in <math.h> only (7.22p5) */
 #define atan2(x,y)       __tgmath_real_2(x, y, atan2)
@@ -78,12 +103,11 @@
 #define tgamma(x)        __tgmath_real(x, tgamma)
 #define trunc(x)         __tgmath_real(x, trunc)
 
-/* Functions defined in <complex.h> only (7.22p6)
+/* Functions defined in <complex.h> only (7.22p6) */
 #define carg(z)          __tgmath_cplx_only(z, carg)
 #define cimag(z)         __tgmath_cplx_only(z, cimag)
 #define conj(z)          __tgmath_cplx_only(z, conj)
 #define cproj(z)         __tgmath_cplx_only(z, cproj)
 #define creal(z)         __tgmath_cplx_only(z, creal)
-*/
 #endif /* __cplusplus */
 #endif /* _TGMATH_H */
diff --git a/lib/Makefile b/lib/Makefile
index 3b166a86..099c9f41 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -40,8 +40,9 @@ X86_64_O = libtcc1.o $(COMMON_O)
 ARM_O = libtcc1.o armeabi.o armflush.o $(COMMON_O)
 ARM64_O = lib-arm64.o $(COMMON_O)
 RISCV64_O = lib-arm64.o $(COMMON_O)
-COMMON_O = stdatomic.o atomic.o builtin.o alloca.o alloca-bt.o
-WIN_O = crt1.o crt1w.o wincrt1.o wincrt1w.o dllcrt1.o dllmain.o winex.o
+COMMON_O = stdatomic.o atomic.o builtin.o complex-arith.o alloca.o alloca-bt.o
+WIN_O = crt1.o crt1w.o wincrt1.o wincrt1w.o dllcrt1.o dllmain.o winex.o \
+	tcc-complex.o
 LIN_O = dsohandle.o
 OSX_O =
 
diff --git a/lib/complex-arith.c b/lib/complex-arith.c
new file mode 100644
index 00000000..a8bd3bf5
--- /dev/null
+++ b/lib/complex-arith.c
@@ -0,0 +1,155 @@
+/*
+ * Recovery helpers for complex multiplication and division.
+ *
+ * Finite operands use power-of-two scaling. Infinite operands follow the
+ * recovery structure used by established compiler runtimes.
+ */
+#include <math.h>
+
+#define DEFINE_COMPLEX_ARITHMETIC(type, suffix, absolute, exponent,     \
+                                  scale_power)                          \
+void __tcc_mul##suffix(type a, type b, type c, type d, type *out)       \
+{                                                                      \
+    type ac = a * c;                                                    \
+    type bd = b * d;                                                    \
+    type ad = a * d;                                                    \
+    type bc = b * c;                                                    \
+    type x = ac - bd;                                                   \
+    type y = ad + bc;                                                   \
+                                                                       \
+    if (isfinite(a) && isfinite(b) && isfinite(c) && isfinite(d)) {     \
+        type left_scale = absolute(a) > absolute(b)                     \
+            ? absolute(a) : absolute(b);                               \
+        type right_scale = absolute(c) > absolute(d)                    \
+            ? absolute(c) : absolute(d);                               \
+        if (left_scale != 0 && right_scale != 0) {                      \
+            int left_exponent = exponent(left_scale);                  \
+            int right_exponent = exponent(right_scale);                \
+            type scaled_a = scale_power(a, -left_exponent);            \
+            type scaled_b = scale_power(b, -left_exponent);            \
+            type scaled_c = scale_power(c, -right_exponent);           \
+            type scaled_d = scale_power(d, -right_exponent);           \
+            type scaled_x = scaled_a * scaled_c                        \
+                - scaled_b * scaled_d;                                 \
+            type scaled_y = scaled_a * scaled_d                        \
+                + scaled_b * scaled_c;                                 \
+            x = scale_power(scaled_x,                                  \
+                            left_exponent + right_exponent);           \
+            y = scale_power(scaled_y,                                  \
+                            left_exponent + right_exponent);           \
+        }                                                              \
+    }                                                                  \
+                                                                       \
+    if (isnan(x) && isnan(y)) {                                        \
+        int recalculate = 0;                                           \
+        if (isinf(a) || isinf(b)) {                                    \
+            a = copysign(isinf(a) ? (type)1 : (type)0, a);             \
+            b = copysign(isinf(b) ? (type)1 : (type)0, b);             \
+            if (isnan(c))                                              \
+                c = copysign((type)0, c);                              \
+            if (isnan(d))                                              \
+                d = copysign((type)0, d);                              \
+            recalculate = 1;                                           \
+        }                                                              \
+        if (isinf(c) || isinf(d)) {                                    \
+            c = copysign(isinf(c) ? (type)1 : (type)0, c);             \
+            d = copysign(isinf(d) ? (type)1 : (type)0, d);             \
+            if (isnan(a))                                              \
+                a = copysign((type)0, a);                              \
+            if (isnan(b))                                              \
+                b = copysign((type)0, b);                              \
+            recalculate = 1;                                           \
+        }                                                              \
+        if (!recalculate                                               \
+            && (isinf(ac) || isinf(bd) || isinf(ad) || isinf(bc))) {   \
+            if (isnan(a))                                              \
+                a = copysign((type)0, a);                              \
+            if (isnan(b))                                              \
+                b = copysign((type)0, b);                              \
+            if (isnan(c))                                              \
+                c = copysign((type)0, c);                              \
+            if (isnan(d))                                              \
+                d = copysign((type)0, d);                              \
+            recalculate = 1;                                           \
+        }                                                              \
+        if (recalculate) {                                             \
+            x = (type)INFINITY * (a * c - b * d);                      \
+            y = (type)INFINITY * (a * d + b * c);                      \
+        }                                                              \
+    }                                                                  \
+    out[0] = x;                                                        \
+    out[1] = y;                                                        \
+}                                                                      \
+                                                                       \
+void __tcc_div##suffix(type a, type b, type c, type d, type *out)       \
+{                                                                      \
+    type ratio;                                                        \
+    type denominator;                                                  \
+    type x;                                                            \
+    type y;                                                            \
+                                                                       \
+    if (isfinite(a) && isfinite(b) && isfinite(c) && isfinite(d)       \
+        && (c != 0 || d != 0)) {                                       \
+        type denominator_scale = absolute(c) > absolute(d)             \
+            ? absolute(c) : absolute(d);                               \
+        type numerator_scale = absolute(a) > absolute(b)               \
+            ? absolute(a) : absolute(b);                               \
+        int denominator_exponent = exponent(denominator_scale);        \
+        type scaled_c = scale_power(c, -denominator_exponent);         \
+        type scaled_d = scale_power(d, -denominator_exponent);         \
+        denominator = scaled_c * scaled_c + scaled_d * scaled_d;       \
+        if (numerator_scale == 0) {                                    \
+            x = scale_power((a * scaled_c + b * scaled_d)              \
+                            / denominator, -denominator_exponent);     \
+            y = scale_power((b * scaled_c - a * scaled_d)              \
+                            / denominator, -denominator_exponent);     \
+        } else {                                                       \
+            int numerator_exponent = exponent(numerator_scale);        \
+            type scaled_a = scale_power(a, -numerator_exponent);       \
+            type scaled_b = scale_power(b, -numerator_exponent);       \
+            int result_exponent = numerator_exponent                   \
+                - denominator_exponent;                               \
+            x = scale_power((scaled_a * scaled_c                       \
+                             + scaled_b * scaled_d) / denominator,     \
+                            result_exponent);                          \
+            y = scale_power((scaled_b * scaled_c                       \
+                             - scaled_a * scaled_d) / denominator,     \
+                            result_exponent);                          \
+        }                                                              \
+    } else if (absolute(c) < absolute(d)) {                            \
+        ratio = c / d;                                                 \
+        denominator = c * ratio + d;                                  \
+        x = (a * ratio + b) / denominator;                             \
+        y = (b * ratio - a) / denominator;                             \
+    } else {                                                           \
+        ratio = d / c;                                                 \
+        denominator = d * ratio + c;                                  \
+        x = (b * ratio + a) / denominator;                             \
+        y = (b - a * ratio) / denominator;                             \
+    }                                                                  \
+                                                                       \
+    if (isnan(x) && isnan(y)) {                                        \
+        if (c == 0 && d == 0 && (!isnan(a) || !isnan(b))) {            \
+            type infinity = copysign((type)INFINITY, c);               \
+            x = infinity * a;                                         \
+            y = infinity * b;                                         \
+        } else if ((isinf(a) || isinf(b))                              \
+                   && isfinite(c) && isfinite(d)) {                    \
+            a = copysign(isinf(a) ? (type)1 : (type)0, a);             \
+            b = copysign(isinf(b) ? (type)1 : (type)0, b);             \
+            x = (type)INFINITY * (a * c + b * d);                      \
+            y = (type)INFINITY * (b * c - a * d);                      \
+        } else if ((isinf(c) || isinf(d))                              \
+                   && isfinite(a) && isfinite(b)) {                    \
+            c = copysign(isinf(c) ? (type)1 : (type)0, c);             \
+            d = copysign(isinf(d) ? (type)1 : (type)0, d);             \
+            x = (type)0 * (a * c + b * d);                            \
+            y = (type)0 * (b * c - a * d);                            \
+        }                                                              \
+    }                                                                  \
+    out[0] = x;                                                        \
+    out[1] = y;                                                        \
+}
+
+DEFINE_COMPLEX_ARITHMETIC(double, dc3, fabs, ilogb, scalbn)
+DEFINE_COMPLEX_ARITHMETIC(long double, xc3, fabsl, ilogbl, scalbnl)
diff --git a/lib/tcc-complex.c b/lib/tcc-complex.c
new file mode 100644
index 00000000..9c351e80
--- /dev/null
+++ b/lib/tcc-complex.c
@@ -0,0 +1,322 @@
+/* C99 complex library support for TinyCC's Windows runtime. */
+#include <complex.h>
+#include <float.h>
+#include <math.h>
+
+#define CX_PI_2 1.57079632679489661923132169163975144
+
+#define DCMPLX(x, y) __builtin_complex((double)(x), (double)(y))
+#define FCMPLX(x, y) __builtin_complex((float)(x), (float)(y))
+#define LCMPLX(x, y) \
+    __builtin_complex((long double)(x), (long double)(y))
+
+#define DEFINE_BASIC_FUNCTIONS(type, suffix, cmplx)                     \
+typedef union {                                                        \
+    type complex value;                                                \
+    type part[2];                                                      \
+} complex_parts##suffix;                                               \
+                                                                       \
+type (creal##suffix)(type complex z)                                   \
+{                                                                      \
+    complex_parts##suffix value;                                       \
+    value.value = z;                                                   \
+    return value.part[0];                                              \
+}                                                                      \
+                                                                       \
+type (cimag##suffix)(type complex z)                                   \
+{                                                                      \
+    complex_parts##suffix value;                                       \
+    value.value = z;                                                   \
+    return value.part[1];                                              \
+}                                                                      \
+                                                                       \
+type cabs##suffix(type complex z)                                      \
+{                                                                      \
+    return hypot##suffix(creal##suffix(z), cimag##suffix(z));           \
+}                                                                      \
+                                                                       \
+type carg##suffix(type complex z)                                      \
+{                                                                      \
+    return atan2##suffix(cimag##suffix(z), creal##suffix(z));            \
+}                                                                      \
+                                                                       \
+type complex conj##suffix(type complex z)                              \
+{                                                                      \
+    return cmplx(creal##suffix(z), -cimag##suffix(z));                   \
+}                                                                      \
+                                                                       \
+type complex cproj##suffix(type complex z)                             \
+{                                                                      \
+    type x = creal##suffix(z);                                         \
+    type y = cimag##suffix(z);                                         \
+    if (isinf(x) || isinf(y))                                          \
+        return cmplx(INFINITY, copysign##suffix((type)0, y));           \
+    return z;                                                         \
+}
+
+DEFINE_BASIC_FUNCTIONS(double, , DCMPLX)
+DEFINE_BASIC_FUNCTIONS(float, f, FCMPLX)
+DEFINE_BASIC_FUNCTIONS(long double, l, LCMPLX)
+
+double complex cexp(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+    double magnitude;
+
+    if (y == 0)
+        return DCMPLX(exp(x), y);
+    if (x == 0)
+        return DCMPLX(cos(y), sin(y));
+    if (!isfinite(y)) {
+        if (isinf(x) && signbit(x))
+            return DCMPLX(0.0, 0.0);
+        if (isinf(x))
+            return DCMPLX(INFINITY, y - y);
+        return DCMPLX(y - y, y - y);
+    }
+    magnitude = exp(x);
+    return DCMPLX(magnitude * cos(y), magnitude * sin(y));
+}
+
+double complex clog(double complex z)
+{
+    return DCMPLX(log(cabs(z)), carg(z));
+}
+
+double complex csqrt(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+    double t;
+    int scale = 0;
+
+    if (x == 0 && y == 0)
+        return DCMPLX(0.0, y);
+    if (isinf(y))
+        return DCMPLX(INFINITY, y);
+    if (isnan(x)) {
+        t = (y - y) / (y - y);
+        return DCMPLX(x, t);
+    }
+    if (isinf(x)) {
+        if (signbit(x))
+            return DCMPLX(fabs(y - y), copysign(INFINITY, y));
+        return DCMPLX(x, copysign(y - y, y));
+    }
+
+    if (fabs(x) >= DBL_MAX / 4 || fabs(y) >= DBL_MAX / 4) {
+        x *= 0.25;
+        y *= 0.25;
+        scale = 1;
+    } else if (fabs(x) < DBL_MIN * 4 && fabs(y) < DBL_MIN * 4) {
+        x *= 0x1p54;
+        y *= 0x1p54;
+        scale = -27;
+    }
+
+    if (x >= 0) {
+        double real = sqrt((x + hypot(x, y)) * 0.5);
+        z = DCMPLX(real, y / (2 * real));
+    } else {
+        double imaginary = sqrt((-x + hypot(x, y)) * 0.5);
+        z = DCMPLX(fabs(y) / (2 * imaginary),
+                   copysign(imaginary, y));
+    }
+    if (scale == 1)
+        return z * 2.0;
+    if (scale == -27)
+        return z * 0x1p-27;
+    return z;
+}
+
+double complex ccosh(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+
+    if (y == 0)
+        return DCMPLX(cosh(x), x * y);
+    if (x == 0 && !isfinite(y))
+        return DCMPLX(y - y, copysign(0.0, x * (y - y)));
+    if (!isfinite(y) && isfinite(x))
+        return DCMPLX(y - y, x * (y - y));
+    if (isinf(x)) {
+        if (!isfinite(y))
+            return DCMPLX(INFINITY, x * (y - y));
+        return DCMPLX(INFINITY * cos(y), x * sin(y));
+    }
+    if (isnan(x))
+        return DCMPLX((x * x) * (y - y), (x + x) * (y - y));
+    return DCMPLX(cosh(x) * cos(y), sinh(x) * sin(y));
+}
+
+double complex csinh(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+
+    if (y == 0)
+        return DCMPLX(sinh(x), y);
+    if (x == 0 && !isfinite(y))
+        return DCMPLX(copysign(0.0, x * (y - y)), y - y);
+    if (!isfinite(y) && isfinite(x))
+        return DCMPLX(y - y, x * (y - y));
+    if (isinf(x)) {
+        if (!isfinite(y))
+            return DCMPLX(INFINITY, x * (y - y));
+        return DCMPLX(x * cos(y), INFINITY * sin(y));
+    }
+    if (isnan(x))
+        return DCMPLX((x * x) * (y - y), (x + x) * (y - y));
+    return DCMPLX(sinh(x) * cos(y), cosh(x) * sin(y));
+}
+
+double complex ctanh(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+    double tangent;
+    double beta;
+    double sine;
+    double denominator;
+
+    if (!isfinite(x)) {
+        if (isnan(x))
+            return DCMPLX(x, y == 0 ? y : x * y);
+        return DCMPLX(copysign(1.0, x),
+                      copysign(0.0, isinf(y) ? y : sin(y) * cos(y)));
+    }
+    if (!isfinite(y))
+        return DCMPLX(x ? y - y : x, y - y);
+    if (fabs(x) >= 22) {
+        double small = exp(-fabs(x));
+        return DCMPLX(copysign(1.0, x),
+                      4 * sin(y) * cos(y) * small * small);
+    }
+    tangent = tan(y);
+    beta = 1 + tangent * tangent;
+    sine = sinh(x);
+    denominator = 1 + beta * sine * sine;
+    return DCMPLX(beta * sqrt(1 + sine * sine) * sine / denominator,
+                  tangent / denominator);
+}
+
+double complex ccos(double complex z)
+{
+    return ccosh(DCMPLX(-cimag(z), creal(z)));
+}
+
+double complex csin(double complex z)
+{
+    double complex value = csinh(DCMPLX(-cimag(z), creal(z)));
+    return DCMPLX(cimag(value), -creal(value));
+}
+
+double complex ctan(double complex z)
+{
+    double complex value = ctanh(DCMPLX(-cimag(z), creal(z)));
+    return DCMPLX(cimag(value), -creal(value));
+}
+
+double complex catan(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+    double x2 = x * x;
+    double real = 0.5 * atan2(2 * x, 1 - x2 - y * y);
+    double lower = x2 + (y - 1) * (y - 1);
+    double upper = x2 + (y + 1) * (y + 1);
+    return DCMPLX(real, 0.25 * log(upper / lower));
+}
+
+double complex casin(double complex z)
+{
+    double x = creal(z);
+    double y = cimag(z);
+    double complex root = csqrt(DCMPLX(1 - (x - y) * (x + y),
+                                        -2 * x * y));
+    double complex value = clog(DCMPLX(-y + creal(root),
+                                       x + cimag(root)));
+    return DCMPLX(cimag(value), -creal(value));
+}
+
+double complex cacos(double complex z)
+{
+    double complex value = casin(z);
+    return DCMPLX(CX_PI_2 - creal(value), -cimag(value));
+}
+
+double complex casinh(double complex z)
+{
+    double complex value = casin(DCMPLX(-cimag(z), creal(z)));
+    return DCMPLX(cimag(value), -creal(value));
+}
+
+double complex cacosh(double complex z)
+{
+    int negative_imaginary = signbit(cimag(z));
+    double complex value = cacos(z);
+    if (negative_imaginary)
+        return DCMPLX(cimag(value), -creal(value));
+    return DCMPLX(-cimag(value), creal(value));
+}
+
+double complex catanh(double complex z)
+{
+    double complex value = catan(DCMPLX(-cimag(z), creal(z)));
+    return DCMPLX(cimag(value), -creal(value));
+}
+
+double complex cpow(double complex base, double complex exponent)
+{
+    double complex logarithm = clog(base);
+    double a = creal(exponent);
+    double b = cimag(exponent);
+    double c = creal(logarithm);
+    double d = cimag(logarithm);
+    return cexp(DCMPLX(a * c - b * d, a * d + b * c));
+}
+
+#define DEFINE_UNARY_WRAPPERS(name)                                    \
+float complex name##f(float complex z)                                 \
+{                                                                      \
+    double complex value = name(DCMPLX(crealf(z), cimagf(z)));         \
+    return FCMPLX(creal(value), cimag(value));                          \
+}                                                                      \
+long double complex name##l(long double complex z)                     \
+{                                                                      \
+    double complex value = name(DCMPLX(creall(z), cimagl(z)));         \
+    return LCMPLX(creal(value), cimag(value));                          \
+}
+
+DEFINE_UNARY_WRAPPERS(cacos)
+DEFINE_UNARY_WRAPPERS(casin)
+DEFINE_UNARY_WRAPPERS(catan)
+DEFINE_UNARY_WRAPPERS(ccos)
+DEFINE_UNARY_WRAPPERS(csin)
+DEFINE_UNARY_WRAPPERS(ctan)
+DEFINE_UNARY_WRAPPERS(cacosh)
+DEFINE_UNARY_WRAPPERS(casinh)
+DEFINE_UNARY_WRAPPERS(catanh)
+DEFINE_UNARY_WRAPPERS(ccosh)
+DEFINE_UNARY_WRAPPERS(csinh)
+DEFINE_UNARY_WRAPPERS(ctanh)
+DEFINE_UNARY_WRAPPERS(cexp)
+DEFINE_UNARY_WRAPPERS(clog)
+DEFINE_UNARY_WRAPPERS(csqrt)
+
+float complex cpowf(float complex base, float complex exponent)
+{
+    double complex value = cpow(DCMPLX(crealf(base), cimagf(base)),
+                                DCMPLX(crealf(exponent), cimagf(exponent)));
+    return FCMPLX(creal(value), cimag(value));
+}
+
+long double complex cpowl(long double complex base,
+                          long double complex exponent)
+{
+    double complex value = cpow(DCMPLX(creall(base), cimagl(base)),
+                                DCMPLX(creall(exponent), cimagl(exponent)));
+    return LCMPLX(creal(value), cimag(value));
+}
diff --git a/tcc.h b/tcc.h
index ce9b5189..6b20f5e8 100644
--- a/tcc.h
+++ b/tcc.h
@@ -471,6 +471,10 @@ typedef union CValue {
     double d;
     float f;
     uint64_t i;
+    struct {
+        long double real;
+        long double imaginary;
+    } complex;
     struct {
         char *data;
         int size;
@@ -1036,6 +1040,7 @@ struct filespec {
                                 char/short stored in integer registers) */
 #define VT_NONCONST  0x1000  /* VT_CONST, but not an (C standard) integer
                                 constant expression */
+#define VT_COMPLEX_RVALUE 0x2000 /* addressable internal complex temporary */
 #define VT_MUSTBOUND 0x4000  /* bound checking must be done before
                                 dereferencing value */
 #define VT_BOUNDED   0x8000  /* value is bounded. The address of the
@@ -1072,7 +1077,8 @@ struct filespec {
 #define VT_TYPEDEF 0x00004000  /* typedef definition */
 #define VT_INLINE  0x00008000  /* inline definition */
 #define VT_TLS     0x00010000  /* thread-local storage */
-/* currently unused: 0x000[248]0000  */
+#define VT_COMPLEX 0x00020000  /* complex scalar represented by a struct */
+/* currently unused: 0x000[48]0000  */
 
 #define VT_STRUCT_SHIFT 20     /* shift for bitfield shift values (32 - 2*6) */
 #define VT_STRUCT_MASK (((1U << (6+6)) - 1) << VT_STRUCT_SHIFT | VT_BITFIELD)
@@ -1185,8 +1191,11 @@ struct filespec {
 #define TOK_PPNUM   0xcd /* preprocessor number */
 #define TOK_PPSTR   0xce /* preprocessor string */
 #define TOK_LINENUM 0xcf /* line number info */
+#define TOK_CFLOAT_I 0xd0 /* imaginary float constant */
+#define TOK_CDOUBLE_I 0xd1 /* imaginary double constant */
+#define TOK_CLDOUBLE_I 0xd2 /* imaginary long double constant */
 
-#define TOK_HAS_VALUE(t) (t >= TOK_CCHAR && t <= TOK_LINENUM)
+#define TOK_HAS_VALUE(t) ((t) >= TOK_CCHAR && (t) <= TOK_CLDOUBLE_I)
 
 #define TOK_EOF       (-1)  /* end of file */
 #define TOK_LINEFEED  10    /* line feed */
@@ -1692,6 +1701,8 @@ ST_FUNC void gen_increment_tcov (SValue *sv);
 ST_FUNC void gen_opl(int op);
 #ifdef TCC_TARGET_PE
 ST_FUNC void gen_vla_result(int addr);
+#else
+ST_FUNC void arch_transfer_ret_regs(int aftercall);
 #endif
 ST_FUNC void gen_cvt_sxtw(void);
 ST_FUNC void gen_cvt_csti(int t);
diff --git a/tccdbg.c b/tccdbg.c
index 67e85643..5e1b0ad0 100644
--- a/tccdbg.c
+++ b/tccdbg.c
@@ -77,6 +77,31 @@ static const struct {
     {   VT_LONG | VT_INT | VT_UNSIGNED, 8, DW_ATE_unsigned, "long unsigned int:t28=r28;0;01777777777777777777777;" },
     {   VT_VOID, 1, DW_ATE_unsigned_char, "void:t29=29" },
 #endif
+#if LONG_SIZE == 4
+    {   VT_FLOAT | VT_COMPLEX, 8, DW_ATE_complex_float,
+        "float _Complex:t28=r1;8;0;" },
+    {   VT_DOUBLE | VT_COMPLEX, 16, DW_ATE_complex_float,
+        "double _Complex:t29=r1;16;0;" },
+# ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
+    {   VT_DOUBLE | VT_LONG | VT_COMPLEX, 16, DW_ATE_complex_float,
+        "long double _Complex:t30=r1;16;0;" },
+# else
+    {   VT_LDOUBLE | VT_COMPLEX, 2 * LDOUBLE_SIZE,
+        DW_ATE_complex_float, "long double _Complex:t30=r1;32;0;" },
+# endif
+#else
+    {   VT_FLOAT | VT_COMPLEX, 8, DW_ATE_complex_float,
+        "float _Complex:t30=r1;8;0;" },
+    {   VT_DOUBLE | VT_COMPLEX, 16, DW_ATE_complex_float,
+        "double _Complex:t31=r1;16;0;" },
+# ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
+    {   VT_DOUBLE | VT_LONG | VT_COMPLEX, 16, DW_ATE_complex_float,
+        "long double _Complex:t32=r1;16;0;" },
+# else
+    {   VT_LDOUBLE | VT_COMPLEX, 2 * LDOUBLE_SIZE,
+        DW_ATE_complex_float, "long double _Complex:t32=r1;32;0;" },
+# endif
+#endif
 };
 
 #define	N_DEFAULT_DEBUG	(sizeof (default_debug) / sizeof (default_debug[0]))
@@ -1795,6 +1820,19 @@ static int remove_type_info(int type)
 	return type;
 }
 
+static int complex_debug_type(Sym *sym, int type)
+{
+    Sym *field;
+
+    if (!(type & VT_COMPLEX))
+        return type;
+    field = sym->type.ref ? sym->type.ref->next : NULL;
+    if (!field)
+        return type;
+    return VT_COMPLEX
+        | (remove_type_info(field->type.t) & (VT_BTYPE | VT_LONG));
+}
+
 static void tcc_get_debug_info(TCCState *s1, Sym *s, CString *result)
 {
     int type;
@@ -1810,6 +1848,7 @@ static void tcc_get_debug_info(TCCState *s1, Sym *s, CString *result)
         else
             break;
     }
+    type = complex_debug_type(t, type);
     if ((type & VT_BTYPE) == VT_STRUCT) {
         t = t->type.ref;
         if (stabs_struct_find(s1, t, &debug_type)) {
@@ -1927,6 +1966,7 @@ static int tcc_get_dwarf_info(TCCState *s1, Sym *s)
         else
             break;
     }
+    type = complex_debug_type(t, type);
     if ((type & VT_BTYPE) == VT_STRUCT) {
         t = t->type.ref;
 	debug_type = tcc_debug_find(s1, t, 1);
diff --git a/tccgen.c b/tccgen.c
index 8f4cd13a..173d600a 100644
--- a/tccgen.c
+++ b/tccgen.c
@@ -75,6 +75,8 @@ ST_DATA int func_ind; /* function start address */
 static int func_old;
 ST_DATA const char *funcname;
 ST_DATA CType int_type, func_old_type, char_type, char_pointer_type;
+static CType complex_types[3];
+static CType complex_helper_types[2];
 static CString initstr;
 
 #if PTR_SIZE == 4
@@ -135,6 +137,9 @@ static void block(int flags);
 
 static void gen_cast(CType *type);
 static void gen_cast_s(int t);
+static void vsetc(CType *type, int r, CValue *vc);
+static void vdup(void);
+static void incr_offset(int offset);
 static inline CType *pointed_type(CType *type);
 static int is_compatible_types(CType *type1, CType *type2);
 static int parse_btype(CType *type, AttributeDef *ad, int ignore_label);
@@ -211,6 +216,212 @@ ST_INLN int is_float(int t)
         || bt == VT_QFLOAT;
 }
 
+static inline int long_double_type(void)
+{
+#ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
+    return VT_DOUBLE | VT_LONG;
+#else
+    return VT_LDOUBLE;
+#endif
+}
+
+static inline int is_long_double_type(int t)
+{
+    return (t & (VT_BTYPE | VT_LONG)) == long_double_type();
+}
+
+static inline int is_complex(int t)
+{
+    return (t & (VT_BTYPE | VT_COMPLEX)) == (VT_STRUCT | VT_COMPLEX);
+}
+
+static void init_complex_type(CType *type, int real_type)
+{
+    CType field_type, struct_type;
+    Sym *field, *imaginary, *tag;
+    int align, size;
+
+    struct_type.t = VT_STRUCT;
+    struct_type.ref = NULL;
+    field_type.t = real_type;
+    field_type.ref = NULL;
+    size = type_size(&field_type, &align);
+
+    tag = sym_push(SYM_FIRST_ANOM | SYM_STRUCT, &struct_type, 0, size * 2);
+    tag->r = align;
+    field = sym_push(SYM_FIRST_ANOM | SYM_FIELD, &field_type, 0, 0);
+    imaginary = sym_push(SYM_FIRST_ANOM | SYM_FIELD, &field_type, 0, size);
+    tag->next = field;
+    field->next = imaginary;
+
+    type->t = VT_STRUCT | VT_COMPLEX;
+    type->ref = tag;
+}
+
+static void init_complex_helper_type(CType *type, CType *real_type)
+{
+    CType output_type = *real_type;
+    CType return_type;
+    Sym *function;
+    Sym **next;
+    int i;
+
+    return_type.t = VT_VOID;
+    return_type.ref = NULL;
+    mk_pointer(&output_type);
+
+    function = sym_push(SYM_FIELD, &return_type, 0, 0);
+    function->f.func_call = FUNC_CDECL;
+    function->f.func_type = FUNC_NEW;
+    next = &function->next;
+    for (i = 0; i < 4; ++i) {
+        *next = sym_push(SYM_FIELD, real_type, 0, 0);
+        next = &(*next)->next;
+    }
+    *next = sym_push(SYM_FIELD, &output_type, 0, 0);
+
+    type->t = VT_FUNC;
+    type->ref = function;
+}
+
+static CType *complex_type_for_real(int real_type)
+{
+    int bt = real_type & (VT_BTYPE | VT_LONG);
+
+    if (bt == VT_FLOAT)
+        return &complex_types[0];
+    if (bt == VT_DOUBLE)
+        return &complex_types[1];
+    if (is_long_double_type(bt))
+        return &complex_types[2];
+    return NULL;
+}
+
+static CType *complex_real_type(CType *type)
+{
+    return &type->ref->next->type;
+}
+
+static long double scalar_constant_value(SValue *value)
+{
+    int bt = value->type.t & VT_BTYPE;
+
+    if (bt == VT_FLOAT)
+        return value->c.f;
+    if (bt == VT_DOUBLE)
+        return value->c.d;
+    return value->c.ld;
+}
+
+static int is_pure_constant(SValue *value)
+{
+    return (value->r & (VT_VALMASK | VT_LVAL | VT_SYM)) == VT_CONST;
+}
+
+static void make_complex_value(CType *type)
+{
+    CType real_type = *complex_real_type(type);
+    CValue value;
+    int align, part_size, size, address;
+
+    if (is_pure_constant(vtop - 1) && is_pure_constant(vtop)) {
+        memset(&value, 0, sizeof value);
+        value.complex.real = scalar_constant_value(vtop - 1);
+        value.complex.imaginary = scalar_constant_value(vtop);
+        vtop -= 2;
+        vsetc(type, VT_CONST, &value);
+        return;
+    }
+
+    size = type_size(type, &align);
+    part_size = type_size(&real_type, &align);
+    loc = (loc - size) & -align;
+    address = loc;
+
+    vset(&real_type, VT_LOCAL | VT_LVAL, address + part_size);
+    vswap();
+    vstore();
+    vpop();
+
+    vset(&real_type, VT_LOCAL | VT_LVAL, address);
+    vswap();
+    vstore();
+    vpop();
+
+    vset(type, VT_LOCAL | VT_LVAL | VT_COMPLEX_RVALUE, address);
+}
+
+static void vpush_real_constant(CType *type, long double number)
+{
+    CValue value;
+
+    memset(&value, 0, sizeof value);
+    if ((type->t & VT_BTYPE) == VT_FLOAT)
+        value.f = number;
+    else if ((type->t & VT_BTYPE) == VT_DOUBLE)
+        value.d = number;
+    else
+        value.ld = number;
+    vsetc(type, VT_CONST, &value);
+}
+
+static void complex_components(void)
+{
+    CType real_type;
+    long double real, imaginary;
+    int align, part_size;
+
+    if (!is_complex(vtop->type.t))
+        tcc_internal_error("complex value expected");
+    real_type = *complex_real_type(&vtop->type);
+    if (is_pure_constant(vtop)) {
+        real = vtop->c.complex.real;
+        imaginary = vtop->c.complex.imaginary;
+        vtop--;
+        vpush_real_constant(&real_type, real);
+        vpush_real_constant(&real_type, imaginary);
+        return;
+    }
+    if (!(vtop->r & VT_LVAL))
+        tcc_internal_error("complex value is not addressable");
+
+    part_size = type_size(&real_type, &align);
+    vdup();
+    vtop[-1].type = real_type;
+    vtop[-1].r &= ~VT_COMPLEX_RVALUE;
+    vtop->type = real_type;
+    vtop->r &= ~VT_COMPLEX_RVALUE;
+    incr_offset(part_size);
+}
+
+static int complex_real_rank(CType *type)
+{
+    int real_type;
+
+    if (is_complex(type->t))
+        type = complex_real_type(type);
+    real_type = type->t & (VT_BTYPE | VT_LONG);
+    if (is_long_double_type(real_type))
+        return 3;
+    if (real_type == VT_DOUBLE)
+        return 2;
+    if (real_type == VT_FLOAT)
+        return 1;
+    return 0;
+}
+
+static CType *common_complex_type(CType *left, CType *right)
+{
+    int rank = complex_real_rank(left);
+    int right_rank = complex_real_rank(right);
+
+    if (right_rank > rank)
+        rank = right_rank;
+    if (rank < 1)
+        tcc_internal_error("complex arithmetic without a complex type");
+    return &complex_types[rank - 1];
+}
+
 static inline int is_integer_btype(int bt)
 {
     return bt == VT_BYTE
@@ -325,7 +536,7 @@ ST_FUNC int ieee_finite(double d)
 
 ST_FUNC void test_lvalue(void)
 {
-    if (!(vtop->r & VT_LVAL))
+    if (!(vtop->r & VT_LVAL) || (vtop->r & VT_COMPLEX_RVALUE))
         expect("lvalue");
 }
 
@@ -381,6 +592,14 @@ ST_FUNC void tccgen_init(TCCState *s1)
     /* define some often used types */
     int_type.t = VT_INT;
 
+    init_complex_type(&complex_types[0], VT_FLOAT);
+    init_complex_type(&complex_types[1], VT_DOUBLE);
+    init_complex_type(&complex_types[2], long_double_type());
+    init_complex_helper_type(&complex_helper_types[0],
+                             complex_real_type(&complex_types[1]));
+    init_complex_helper_type(&complex_helper_types[1],
+                             complex_real_type(&complex_types[2]));
+
     char_type.t = VT_BYTE;
     if (s1->char_is_unsigned)
         char_type.t |= VT_UNSIGNED;
@@ -1057,6 +1276,8 @@ static void gvtst_set(int inv, int t)
 {
     int *p;
 
+    if (is_complex(vtop->type.t))
+        gen_cast_s(VT_BOOL);
     if (vtop->r != VT_CMP) {
         vpushi(0);
         gen_op(TOK_NE);
@@ -1096,6 +1317,8 @@ static int gvtst(int inv, int t)
 /* generate a zero or nozero test */
 static void gen_test_zero(int op)
 {
+    if (is_complex(vtop->type.t))
+        gen_cast_s(VT_BOOL);
     if (vtop->r == VT_CMP) {
         int j;
         if (op == TOK_EQ) {
@@ -2690,6 +2913,13 @@ static void type_to_str(char *buf, int buf_size,
     buf_size -= strlen(buf);
     buf += strlen(buf);
 
+    if (is_complex(t)) {
+        type_to_str(buf1, sizeof(buf1), &type->ref->next->type, NULL);
+        pstrcat(buf, buf_size, buf1);
+        pstrcat(buf, buf_size, " _Complex");
+        goto add_var;
+    }
+
     switch(bt) {
     case VT_VOID:
         tstr = "void";
@@ -2782,6 +3012,7 @@ static void type_to_str(char *buf, int buf_size,
         type_to_str(buf, buf_size, &s->type, buf1);
         goto no_var;
     }
+add_var:
     if (varstr) {
         pstrcat(buf, buf_size, " ");
         pstrcat(buf, buf_size, varstr);
@@ -3000,13 +3231,17 @@ static int combine_types(CType *dest, SValue *op1, SValue *op2, int op)
         }
         if (op == CMP_OP)
           type.t = VT_SIZE_T;
+    } else if (is_complex(t1) || is_complex(t2)) {
+        type = *common_complex_type(type1, type2);
+        if (op == CMP_OP)
+            type.t = VT_INT;
     } else if (bt1 == VT_STRUCT || bt2 == VT_STRUCT) {
         if (op != '?' || !compare_types(type1, type2, 1))
           ret = 0;
         type = *type1;
     } else if (is_float(bt1) || is_float(bt2)) {
-        if (bt1 == VT_LDOUBLE || bt2 == VT_LDOUBLE) {
-            type.t = VT_LDOUBLE;
+        if (is_long_double_type(t1) || is_long_double_type(t2)) {
+            type.t = long_double_type();
         } else if (bt1 == VT_DOUBLE || bt2 == VT_DOUBLE) {
             type.t = VT_DOUBLE;
         } else {
@@ -3038,6 +3273,166 @@ static int combine_types(CType *dest, SValue *op1, SValue *op2, int op)
     return ret;
 }
 
+static void prepare_complex_operands(CType *type)
+{
+    int i, align, size;
+
+    for (i = 0; i < 2; ++i) {
+        if (is_complex(vtop->type.t) && !is_pure_constant(vtop)
+            && !(vtop->r & VT_COMPLEX_RVALUE)) {
+            CType source_type = vtop->type;
+
+            size = type_size(&source_type, &align);
+            loc = (loc - size) & -align;
+            vset(&source_type, VT_LOCAL | VT_LVAL, loc);
+            vswap();
+            vstore();
+            vtop->r |= VT_COMPLEX_RVALUE;
+        }
+        vswap();
+    }
+
+    vswap();
+    gen_cast(type);
+    vswap();
+    gen_cast(type);
+
+    vswap();
+    complex_components();
+    vrotb(3);
+    complex_components();
+}
+
+static void push_scalar_operation(SValue *left, SValue *right, int op)
+{
+    vpushv(left);
+    vpushv(right);
+    gen_op(op);
+}
+
+static void finish_complex_operation(SValue *base, CType *type)
+{
+    SValue real = vtop[-1];
+    SValue imaginary = vtop[0];
+
+    vtop = base - 1;
+    vpushv(&real);
+    vpushv(&imaginary);
+    make_complex_value(type);
+}
+
+static void gen_complex_runtime_arithmetic(int op, CType *type,
+                                           SValue *base)
+{
+    SValue components[4];
+    CType runtime_real;
+    CType runtime_complex;
+    CType *runtime_helper_type;
+    int helper;
+    int align;
+    int address;
+    int size;
+    int i;
+
+    memcpy(components, base, sizeof components);
+    runtime_real = *complex_real_type(type);
+    if ((runtime_real.t & VT_BTYPE) == VT_FLOAT)
+        runtime_real.t = VT_DOUBLE;
+    runtime_complex = *complex_type_for_real(runtime_real.t);
+
+    if (complex_real_rank(type) == 3) {
+        helper = op == '*' ? TOK___tcc_mulxc3 : TOK___tcc_divxc3;
+        runtime_helper_type = &complex_helper_types[1];
+    } else {
+        helper = op == '*' ? TOK___tcc_muldc3 : TOK___tcc_divdc3;
+        runtime_helper_type = &complex_helper_types[0];
+    }
+
+    size = type_size(&runtime_complex, &align);
+    loc = (loc - size) & -align;
+    address = loc;
+
+    vtop = base - 1;
+    for (i = 0; i < 4; ++i) {
+        vpushv(&components[i]);
+        gen_cast(&runtime_real);
+    }
+    vseti(VT_LOCAL, address);
+    vpushsym(runtime_helper_type, external_helper_sym(helper));
+    vrott(6);
+    gfunc_call(5);
+
+    vtop = base - 1;
+    vset(&runtime_complex,
+         VT_LOCAL | VT_LVAL | VT_COMPLEX_RVALUE, address);
+    if (complex_real_rank(&runtime_complex) != complex_real_rank(type))
+        gen_cast(type);
+}
+
+static void gen_complex_arithmetic(int op, CType *type)
+{
+    SValue *base;
+
+    prepare_complex_operands(type);
+    base = vtop - 3;
+
+    if ((op == '*' || op == '/')
+        && (!is_pure_constant(&base[0])
+            || !is_pure_constant(&base[1])
+            || !is_pure_constant(&base[2])
+            || !is_pure_constant(&base[3]))) {
+        gen_complex_runtime_arithmetic(op, type, base);
+        return;
+    }
+
+    if (op == '+' || op == '-') {
+        push_scalar_operation(&base[0], &base[2], op);
+        push_scalar_operation(&base[1], &base[3], op);
+    } else if (op == '*') {
+        push_scalar_operation(&base[0], &base[2], '*');
+        push_scalar_operation(&base[1], &base[3], '*');
+        gen_op('-');
+
+        push_scalar_operation(&base[0], &base[3], '*');
+        push_scalar_operation(&base[1], &base[2], '*');
+        gen_op('+');
+    } else if (op == '/') {
+        push_scalar_operation(&base[2], &base[2], '*');
+        push_scalar_operation(&base[3], &base[3], '*');
+        gen_op('+');
+
+        push_scalar_operation(&base[0], &base[2], '*');
+        push_scalar_operation(&base[1], &base[3], '*');
+        gen_op('+');
+        vpushv(&base[4]);
+        gen_op('/');
+
+        push_scalar_operation(&base[1], &base[2], '*');
+        push_scalar_operation(&base[0], &base[3], '*');
+        gen_op('-');
+        vpushv(&base[4]);
+        gen_op('/');
+    } else {
+        tcc_internal_error("invalid complex arithmetic operator");
+    }
+    finish_complex_operation(base, type);
+}
+
+static void gen_complex_equality(int op, CType *type)
+{
+    prepare_complex_operands(type);
+    vrotb(3);
+    vswap();
+    gen_op(TOK_EQ);
+    vrott(3);
+    gen_op(TOK_EQ);
+    gen_op('&');
+    if (op == TOK_NE)
+        gen_test_zero(TOK_EQ);
+    vtop->type.t = VT_INT;
+    vtop->type.ref = NULL;
+}
+
 /* generic gen_op: handles types problems */
 ST_FUNC void gen_op(int op)
 {
@@ -3071,6 +3466,16 @@ redo:
     } else if (!combine_types(&combtype, vtop - 1, vtop, op_class)) {
 op_err:
         tcc_error("invalid operand types for binary operation");
+    } else if (is_complex(t1) || is_complex(t2)) {
+        CType *complex_type = common_complex_type(&vtop[-1].type,
+                                                  &vtop->type);
+
+        if (op == TOK_EQ || op == TOK_NE)
+            gen_complex_equality(op, complex_type);
+        else if (op == '+' || op == '-' || op == '*' || op == '/')
+            gen_complex_arithmetic(op, complex_type);
+        else
+            goto op_err;
     } else if (bt1 == VT_PTR || bt2 == VT_PTR) {
         /* at least one operand is a pointer */
         /* relational op: must be both pointers */
@@ -3268,6 +3673,71 @@ static void gen_cast(CType *type)
     if (IS_ENUM(type->t) && type->ref->c < 0)
         tcc_error("cast to incomplete type");
 
+    if (is_complex(type->t) || is_complex(vtop->type.t)) {
+        int destination_type = type->t & VT_BTYPE;
+        int source_type = vtop->type.t & VT_BTYPE;
+
+        if (is_complex(type->t)) {
+            CType result_type = *type;
+            CType real_type = *complex_real_type(type);
+
+            result_type.t &= ~(VT_CONSTANT | VT_VOLATILE | VT_STORAGE);
+            if (is_complex(vtop->type.t)) {
+                if (type->ref == vtop->type.ref) {
+                    vtop->type = result_type;
+                    return;
+                }
+                complex_components();
+                {
+                    SValue components[2];
+
+                    components[0] = vtop[-1];
+                    components[1] = vtop[0];
+                    vtop -= 2;
+                    vpushv(&components[0]);
+                    gen_cast(&real_type);
+                    if (!is_pure_constant(vtop))
+                        save_reg(vtop->r);
+                    vpushv(&components[1]);
+                }
+                gen_cast(&real_type);
+            } else {
+                if (!is_float(source_type)
+                    && !is_integer_btype(source_type))
+                    cast_error(&vtop->type, type);
+                gen_cast(&real_type);
+                vpush_real_constant(&real_type, 0.0L);
+            }
+            make_complex_value(&result_type);
+            return;
+        }
+
+        if (destination_type == VT_VOID) {
+            vpop();
+            vpushi(0);
+            vtop->type = *type;
+            return;
+        }
+        if (!is_float(destination_type)
+            && !is_integer_btype(destination_type))
+            cast_error(&vtop->type, type);
+
+        if (destination_type == VT_BOOL) {
+            CType source_type = vtop->type;
+            CType real_type = *complex_real_type(&source_type);
+
+            vpush_real_constant(&real_type, 0.0L);
+            gen_cast(&source_type);
+            gen_complex_equality(TOK_NE, &source_type);
+            vtop->type = *type;
+        } else {
+            complex_components();
+            vpop();
+            gen_cast(type);
+        }
+        return;
+    }
+
     dbt = type->t & (VT_BTYPE | VT_UNSIGNED);
     sbt = vtop->type.t & (VT_BTYPE | VT_UNSIGNED);
     if (sbt == VT_FUNC)
@@ -3605,6 +4075,14 @@ static void verify_assign_cast(CType *dt)
     sbt = st->t & VT_BTYPE;
     if (dt->t & VT_CONSTANT)
         tcc_warning("assignment of read-only location");
+    if (is_complex(dt->t) || is_complex(st->t)) {
+        if ((is_complex(dt->t) || is_float(dbt)
+             || is_integer_btype(dbt))
+            && (is_complex(st->t) || is_float(sbt)
+                || is_integer_btype(sbt)))
+            return;
+        goto error;
+    }
     switch(dbt) {
     case VT_VOID:
         if (sbt != dbt)
@@ -3696,6 +4174,26 @@ ST_FUNC void vstore(void)
     dbt = ft & VT_BTYPE;
     verify_assign_cast(&vtop[-1].type);
 
+    if (is_complex(ft) || is_complex(vtop->type.t)) {
+        gen_cast(&vtop[-1].type);
+        sbt = vtop->type.t & VT_BTYPE;
+        dbt = vtop[-1].type.t & VT_BTYPE;
+    }
+
+    if (is_complex(vtop->type.t) && is_pure_constant(vtop)) {
+        init_params p = { rodata_section };
+        unsigned long offset;
+
+        size = type_size(&vtop->type, &align);
+        if (NODATA_WANTED)
+            size = 0, align = 1;
+        offset = section_add(p.sec, size, align);
+        vpush_ref(&vtop->type, p.sec, offset, size);
+        vswap();
+        init_putv(&p, &vtop->type, offset);
+        vtop->r |= VT_LVAL;
+    }
+
     if (sbt == VT_STRUCT) {
         /* if structure, only generate pointer */
         /* structure assignment : generate memcpy */
@@ -3863,6 +4361,8 @@ ST_FUNC void vstore(void)
 ST_FUNC void inc(int post, int c)
 {
     test_lvalue();
+    if (is_complex(vtop->type.t))
+        tcc_error("invalid operand types for increment or decrement");
     vdup(); /* save lvalue */
     if (post) {
         gv_dup(); /* duplicate value */
@@ -4722,13 +5222,14 @@ static void parse_btype_qualify(CType *type, int qualifiers)
  */
 static int parse_btype(CType *type, AttributeDef *ad, int ignore_label)
 {
-    int t, u, bt, st, type_found, typespec_found, g, n;
+    int t, u, bt, st, type_found, typespec_found, complex_found, g, n;
     Sym *s;
     CType type1;
 
     memset(ad, 0, sizeof(AttributeDef));
     type_found = 0;
     typespec_found = 0;
+    complex_found = 0;
     t = VT_INT;
     bt = st = -1;
     type->ref = NULL;
@@ -4806,7 +5307,12 @@ static int parse_btype(CType *type, AttributeDef *ad, int ignore_label)
             u = VT_BOOL;
             goto basic_type;
         case TOK_COMPLEX:
-            tcc_error("_Complex is not yet supported");
+            if (complex_found)
+                goto tmbt;
+            complex_found = 1;
+            typespec_found = 1;
+            next();
+            break;
         case TOK_FLOAT:
             u = VT_FLOAT;
             goto basic_type;
@@ -4983,10 +5489,27 @@ the_end:
     bt = t & (VT_BTYPE|VT_LONG);
     if (bt == VT_LONG)
         t |= LONG_SIZE == 8 ? VT_LLONG : VT_INT;
+    if (complex_found) {
+        bt = t & (VT_BTYPE | VT_LONG);
+        if (t & (VT_DEFSIGN | VT_UNSIGNED))
+            goto tmbt;
+        if (bt == VT_FLOAT) {
+            u = 0;
+        } else if (bt == VT_DOUBLE) {
+            u = 1;
+        } else if (bt == VT_LDOUBLE) {
+            u = 2;
+        } else {
+            goto tmbt;
+        }
+        t = (t & ~(VT_BTYPE | VT_LONG)) | complex_types[u].t;
+        type->ref = complex_types[u].ref;
+    } else {
 #ifdef TCC_USING_DOUBLE_FOR_LDOUBLE
-    if (bt == VT_LDOUBLE)
-        t = (t & ~(VT_BTYPE|VT_LONG)) | (VT_DOUBLE|VT_LONG);
+        if (bt == VT_LDOUBLE)
+            t = (t & ~(VT_BTYPE|VT_LONG)) | (VT_DOUBLE|VT_LONG);
 #endif
+    }
     type->t = t;
     return type_found;
 }
@@ -5596,6 +6119,7 @@ ST_FUNC void unary(void)
 {
     int n, t, align, size, r;
     CType type;
+    CValue value;
     Sym *s;
     AttributeDef ad;
 
@@ -5633,6 +6157,24 @@ ST_FUNC void unary(void)
     case TOK_CULLONG:
         t = VT_LLONG | VT_UNSIGNED;
 	goto push_tokc;
+    case TOK_CFLOAT_I:
+        type = complex_types[0];
+        memset(&value, 0, sizeof value);
+        value.complex.imaginary = tokc.f;
+        goto push_imaginary;
+    case TOK_CDOUBLE_I:
+        type = complex_types[1];
+        memset(&value, 0, sizeof value);
+        value.complex.imaginary = tokc.d;
+        goto push_imaginary;
+    case TOK_CLDOUBLE_I:
+        type = complex_types[2];
+        memset(&value, 0, sizeof value);
+        value.complex.imaginary = tokc.ld;
+    push_imaginary:
+        vsetc(&type, VT_CONST, &value);
+        next();
+        break;
     case TOK_CFLOAT:
         t = VT_FLOAT;
 	goto push_tokc;
@@ -5821,6 +6363,25 @@ ST_FUNC void unary(void)
 	vtop -= 2;
 	vpushi(n);
         break;
+    case TOK_builtin_complex:
+        {
+            CType *complex_type;
+
+            next();
+            skip('(');
+            expr_eq();
+            skip(',');
+            expr_eq();
+            skip(')');
+            complex_type = complex_type_for_real(vtop[-1].type.t);
+            if (!complex_type
+                || !is_compatible_unqualified_types(&vtop[-1].type,
+                                                     &vtop->type))
+                tcc_error("__builtin_complex arguments must have the same "
+                          "real floating type");
+            make_complex_value(complex_type);
+        }
+        break;
     case TOK_builtin_choose_expr:
 	{
 	    int64_t c;
@@ -6319,7 +6880,8 @@ special_math_val:
 
             if (ret_nregs < 0) {
                 vsetc(&ret.type, ret.r, &ret.c);
-#ifdef TCC_TARGET_RISCV64
+#if defined(TCC_TARGET_RISCV64) || \
+    (defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_PE))
                 arch_transfer_ret_regs(1);
 #endif
             } else {
@@ -6818,7 +7380,21 @@ static void gfunc_return(CType *func_type)
         ret_nregs = gfunc_sret(func_type, func_var, &ret_type,
                                &ret_align, &regsize);
         if (ret_nregs < 0) {
-#ifdef TCC_TARGET_RISCV64
+#if defined(TCC_TARGET_RISCV64) || \
+    (defined(TCC_TARGET_X86_64) && !defined(TCC_TARGET_PE))
+            if (is_complex(func_type->t) && !(vtop->r & VT_LVAL)) {
+                int align, size, addr;
+
+                size = type_size(func_type, &align);
+                loc = (loc - size) & -align;
+                addr = loc;
+                type = *func_type;
+                vset(&type, VT_LOCAL | VT_LVAL, addr);
+                vswap();
+                vstore();
+                vpop();
+                vset(&type, VT_LOCAL | VT_LVAL, addr);
+            }
             arch_transfer_ret_regs(0);
 #endif
         } else if (0 == ret_nregs) {
@@ -6835,7 +7411,8 @@ static void gfunc_return(CType *func_type)
             /* returning structure packed into registers */
             int size, addr, align, rc, n;
             size = type_size(func_type,&align);
-            if (ret_nregs * regsize > size ||
+            if ((is_complex(func_type->t) && is_pure_constant(vtop)) ||
+                ret_nregs * regsize > size ||
 		((align & (ret_align - 1))
                  && ((vtop->r & VT_VALMASK) < VT_CONST /* pointer to struct */
                      || (vtop->c.i & (ret_align - 1))
@@ -7897,6 +8474,17 @@ static void init_putv(init_params *p, CType *type, unsigned long c)
         ptr = sec->data + c;
         val = vtop->c.i;
 
+        if (is_complex(type->t) && is_pure_constant(vtop)) {
+            CType *real_type = complex_real_type(type);
+            int part_size = type_size(real_type, &align);
+
+            complex_components();
+            vswap();
+            init_putv(p, real_type, c);
+            init_putv(p, real_type, c + part_size);
+            return;
+        }
+
 	if ((vtop->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST)
             && vtop->sym->v >= SYM_FIRST_ANOM
             && ((vtop->r & VT_LVAL) /* compound literal */
@@ -8181,7 +8769,8 @@ static void decl_initializer(init_params *p, CType *type, unsigned long c, int f
             && is_compatible_unqualified_types(type, &vtop->type)) {
         goto one_elem;
 
-    } else if ((type->t & VT_BTYPE) == VT_STRUCT) {
+    } else if ((type->t & VT_BTYPE) == VT_STRUCT
+               && !is_complex(type->t)) {
         no_oblock = 1;
         if ((flags & DIF_FIRST) || tok == '{') {
             skip('{');
diff --git a/tccpp.c b/tccpp.c
index 214e9cd4..f3544420 100644
--- a/tccpp.c
+++ b/tccpp.c
@@ -574,10 +574,16 @@ ST_FUNC const char *get_tok_str(int v, CValue *cv)
 
     case TOK_CFLOAT:
         return strcpy(p, "<float>");
+    case TOK_CFLOAT_I:
+        return strcpy(p, "<imaginary float>");
     case TOK_CDOUBLE:
         return strcpy(p, "<double>");
+    case TOK_CDOUBLE_I:
+        return strcpy(p, "<imaginary double>");
     case TOK_CLDOUBLE:
         return strcpy(p, "<long double>");
+    case TOK_CLDOUBLE_I:
+        return strcpy(p, "<imaginary long double>");
     case TOK_LINENUM:
         return strcpy(p, "<linenumber>");
 
@@ -972,6 +978,7 @@ static inline int tok_size(const int *p)
     case TOK_CCHAR:
     case TOK_LCHAR:
     case TOK_CFLOAT:
+    case TOK_CFLOAT_I:
     case TOK_LINENUM:
         return 1 + 1;
     case TOK_STR:
@@ -983,10 +990,12 @@ static inline int tok_size(const int *p)
     case TOK_CULONG:
 	return 1 + LONG_SIZE / 4;
     case TOK_CDOUBLE:
+    case TOK_CDOUBLE_I:
     case TOK_CLLONG:
     case TOK_CULLONG:
         return 1 + 2;
     case TOK_CLDOUBLE:
+    case TOK_CLDOUBLE_I:
         return 1 + LDOUBLE_WORDS;
     default:
         return 1 + 0;
@@ -1093,6 +1102,7 @@ static void tok_str_add2(TokenString *s, int t, CValue *cv)
     case TOK_CCHAR:
     case TOK_LCHAR:
     case TOK_CFLOAT:
+    case TOK_CFLOAT_I:
     case TOK_LINENUM:
 #if LONG_SIZE == 4
     case TOK_CLONG:
@@ -1116,6 +1126,7 @@ static void tok_str_add2(TokenString *s, int t, CValue *cv)
         }
         break;
     case TOK_CDOUBLE:
+    case TOK_CDOUBLE_I:
     case TOK_CLLONG:
     case TOK_CULLONG:
 #if LONG_SIZE == 8
@@ -1126,6 +1137,7 @@ static void tok_str_add2(TokenString *s, int t, CValue *cv)
         str[len++] = cv->tab[1];
         break;
     case TOK_CLDOUBLE:
+    case TOK_CLDOUBLE_I:
         str[len++] = cv->tab[0];
         str[len++] = cv->tab[1];
         if (LDOUBLE_WORDS >= 3)
@@ -1185,6 +1197,7 @@ static inline void tok_get(int *t, const int **pp, CValue *cv)
         cv->i = (unsigned)*p++;
         break;
     case TOK_CFLOAT:
+    case TOK_CFLOAT_I:
 	tab[0] = *p++;
 	break;
     case TOK_STR:
@@ -1196,6 +1209,7 @@ static inline void tok_get(int *t, const int **pp, CValue *cv)
         p += (cv->str.size + sizeof(int) - 1) / sizeof(int);
         break;
     case TOK_CDOUBLE:
+    case TOK_CDOUBLE_I:
     case TOK_CLLONG:
     case TOK_CULLONG:
 #if LONG_SIZE == 8
@@ -1205,6 +1219,7 @@ static inline void tok_get(int *t, const int **pp, CValue *cv)
         n = 2;
         goto copy;
     case TOK_CLDOUBLE:
+    case TOK_CLDOUBLE_I:
         n = LDOUBLE_WORDS;
     copy:
         do
@@ -1446,7 +1461,8 @@ static int expr_preprocess(TCCState *s1)
         if (tok < TOK_IDENT) {
             if (tok == TOK_LINEFEED || tok == TOK_EOF)
                 break;
-            if (tok >= TOK_STR && tok <= TOK_CLDOUBLE)
+            if ((tok >= TOK_STR && tok <= TOK_CLDOUBLE)
+                || (tok >= TOK_CFLOAT_I && tok <= TOK_CLDOUBLE_I))
                 tcc_error("invalid constant in preprocessor expression");
 
         } else if (tok == TOK_DEFINED) {
@@ -2430,6 +2446,11 @@ static void parse_number(const char *p)
                 tokc.d = strtod(token_buf, NULL);
             }
         }
+        t = toup(ch);
+        if (t == 'I' || t == 'J') {
+            ch = *p++;
+            tok += TOK_CFLOAT_I - TOK_CFLOAT;
+        }
     } else {
         unsigned long long n, n1;
         int lcount, ucount, ov = 0;
diff --git a/tcctok.h b/tcctok.h
index d8e7b445..f25edcbf 100644
--- a/tcctok.h
+++ b/tcctok.h
@@ -166,6 +166,7 @@
      DEF(TOK_VISIBILITY2, "__visibility__")
 
      DEF(TOK_builtin_types_compatible_p, "__builtin_types_compatible_p")
+     DEF(TOK_builtin_complex, "__builtin_complex")
      DEF(TOK_builtin_choose_expr, "__builtin_choose_expr")
      DEF(TOK_builtin_constant_p, "__builtin_constant_p")
      DEF(TOK_builtin_frame_address, "__builtin_frame_address")
@@ -220,6 +221,10 @@
      DEF(TOK_option, "option")
 
 /* builtin functions or variables */
+     DEF(TOK___tcc_muldc3, "__tcc_muldc3")
+     DEF(TOK___tcc_divdc3, "__tcc_divdc3")
+     DEF(TOK___tcc_mulxc3, "__tcc_mulxc3")
+     DEF(TOK___tcc_divxc3, "__tcc_divxc3")
 #ifndef TCC_ARM_EABI
      DEF(TOK_memcpy, "memcpy")
      DEF(TOK_memmove, "memmove")
diff --git a/tests/tests2/149_complex_runtime.c b/tests/tests2/149_complex_runtime.c
new file mode 100644
index 00000000..9ffbb1a9
--- /dev/null
+++ b/tests/tests2/149_complex_runtime.c
@@ -0,0 +1,65 @@
+#include <stdio.h>
+
+typedef float _Complex complex_float;
+typedef double _Complex complex_double;
+typedef long double _Complex complex_long_double;
+
+static volatile double left_real = 3.0;
+static volatile double left_imaginary = 4.0;
+static volatile double right_real = 1.0;
+static volatile double right_imaginary = -2.0;
+
+static int check_float(void)
+{
+    union { complex_float value; float part[2]; } product, quotient;
+
+    product.value = __builtin_complex((float)left_real,
+                                      (float)left_imaginary)
+        * __builtin_complex((float)right_real, (float)right_imaginary);
+    quotient.value = __builtin_complex((float)left_real,
+                                       (float)left_imaginary)
+        / __builtin_complex((float)right_real, (float)right_imaginary);
+    return product.part[0] == 11.0f && product.part[1] == -2.0f
+        && quotient.part[0] == -1.0f && quotient.part[1] == 2.0f;
+}
+
+static int check_double(void)
+{
+    union { complex_double value; double part[2]; } product, quotient;
+
+    product.value = __builtin_complex(left_real, left_imaginary)
+        * __builtin_complex(right_real, right_imaginary);
+    quotient.value = __builtin_complex(left_real, left_imaginary)
+        / __builtin_complex(right_real, right_imaginary);
+    return product.part[0] == 11.0 && product.part[1] == -2.0
+        && quotient.part[0] == -1.0 && quotient.part[1] == 2.0;
+}
+
+static int check_long_double(void)
+{
+    union {
+        complex_long_double value;
+        long double part[2];
+    } product, quotient;
+
+    product.value = __builtin_complex((long double)left_real,
+                                      (long double)left_imaginary)
+        * __builtin_complex((long double)right_real,
+                            (long double)right_imaginary);
+    quotient.value = __builtin_complex((long double)left_real,
+                                       (long double)left_imaginary)
+        / __builtin_complex((long double)right_real,
+                            (long double)right_imaginary);
+    return product.part[0] == 11.0L && product.part[1] == -2.0L
+        && quotient.part[0] == -1.0L && quotient.part[1] == 2.0L;
+}
+
+int main(void)
+{
+    if (!check_float() || !check_double() || !check_long_double()) {
+        printf("complex runtime helpers: failed\n");
+        return 1;
+    }
+    printf("complex runtime helpers: ok\n");
+    return 0;
+}
diff --git a/tests/tests2/149_complex_runtime.expect b/tests/tests2/149_complex_runtime.expect
new file mode 100644
index 00000000..ebad9ce8
--- /dev/null
+++ b/tests/tests2/149_complex_runtime.expect
@@ -0,0 +1 @@
+complex runtime helpers: ok
diff --git a/win32/build-tcc.bat b/win32/build-tcc.bat
index 83b5636e..b0595a1a 100644
--- a/win32/build-tcc.bat
+++ b/win32/build-tcc.bat
@@ -199,7 +199,9 @@ exit /B %ERRORLEVEL%
 .\%1tcc -B. -c ../lib/stdatomic.c
 .\%1tcc -B. -c ../lib/atomic.S
 .\%1tcc -B. -c ../lib/builtin.c
-.\%1tcc -ar lib/%1libtcc1.a %LIBTCC1%.o crt1.o crt1w.o wincrt1.o wincrt1w.o dllcrt1.o dllmain.o winex.o chkstk.o alloca.o alloca-bt.o stdatomic.o atomic.o builtin.o
+.\%1tcc -B. -c ../lib/complex-arith.c
+.\%1tcc -B. -c ../lib/tcc-complex.c
+.\%1tcc -ar lib/%1libtcc1.a %LIBTCC1%.o crt1.o crt1w.o wincrt1.o wincrt1w.o dllcrt1.o dllmain.o winex.o chkstk.o alloca.o alloca-bt.o stdatomic.o atomic.o builtin.o complex-arith.o tcc-complex.o
 .\%1tcc -B. -c ../lib/bcheck.c -o lib/%1bcheck.o -bt -I..
 .\%1tcc -B. -c ../lib/bcheck.c -o lib/%1bcheck_run.o -bt -I.. -DBCHECK_RUN
 .\%1tcc -B. -c ../lib/bt-exe.c -o lib/%1bt-exe.o
diff --git a/win32/include/complex.h b/win32/include/complex.h
new file mode 100644
index 00000000..f82d90ae
--- /dev/null
+++ b/win32/include/complex.h
@@ -0,0 +1,96 @@
+/* ISO C complex arithmetic for TinyCC's Windows runtime. */
+#ifndef _COMPLEX_H
+#define _COMPLEX_H
+
+#include <_mingw.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define complex _Complex
+#define _Complex_I (__builtin_complex(0.0f, 1.0f))
+#define I _Complex_I
+
+double complex __cdecl cacos(double complex);
+float complex __cdecl cacosf(float complex);
+long double complex __cdecl cacosl(long double complex);
+double complex __cdecl casin(double complex);
+float complex __cdecl casinf(float complex);
+long double complex __cdecl casinl(long double complex);
+double complex __cdecl catan(double complex);
+float complex __cdecl catanf(float complex);
+long double complex __cdecl catanl(long double complex);
+double complex __cdecl ccos(double complex);
+float complex __cdecl ccosf(float complex);
+long double complex __cdecl ccosl(long double complex);
+double complex __cdecl csin(double complex);
+float complex __cdecl csinf(float complex);
+long double complex __cdecl csinl(long double complex);
+double complex __cdecl ctan(double complex);
+float complex __cdecl ctanf(float complex);
+long double complex __cdecl ctanl(long double complex);
+
+double complex __cdecl cacosh(double complex);
+float complex __cdecl cacoshf(float complex);
+long double complex __cdecl cacoshl(long double complex);
+double complex __cdecl casinh(double complex);
+float complex __cdecl casinhf(float complex);
+long double complex __cdecl casinhl(long double complex);
+double complex __cdecl catanh(double complex);
+float complex __cdecl catanhf(float complex);
+long double complex __cdecl catanhl(long double complex);
+double complex __cdecl ccosh(double complex);
+float complex __cdecl ccoshf(float complex);
+long double complex __cdecl ccoshl(long double complex);
+double complex __cdecl csinh(double complex);
+float complex __cdecl csinhf(float complex);
+long double complex __cdecl csinhl(long double complex);
+double complex __cdecl ctanh(double complex);
+float complex __cdecl ctanhf(float complex);
+long double complex __cdecl ctanhl(long double complex);
+
+double complex __cdecl cexp(double complex);
+float complex __cdecl cexpf(float complex);
+long double complex __cdecl cexpl(long double complex);
+double complex __cdecl clog(double complex);
+float complex __cdecl clogf(float complex);
+long double complex __cdecl clogl(long double complex);
+double __cdecl cabs(double complex);
+float __cdecl cabsf(float complex);
+long double __cdecl cabsl(long double complex);
+double complex __cdecl cpow(double complex, double complex);
+float complex __cdecl cpowf(float complex, float complex);
+long double complex __cdecl cpowl(long double complex,
+                                  long double complex);
+double complex __cdecl csqrt(double complex);
+float complex __cdecl csqrtf(float complex);
+long double complex __cdecl csqrtl(long double complex);
+
+double __cdecl carg(double complex);
+float __cdecl cargf(float complex);
+long double __cdecl cargl(long double complex);
+double __cdecl cimag(double complex);
+float __cdecl cimagf(float complex);
+long double __cdecl cimagl(long double complex);
+double complex __cdecl conj(double complex);
+float complex __cdecl conjf(float complex);
+long double complex __cdecl conjl(long double complex);
+double complex __cdecl cproj(double complex);
+float complex __cdecl cprojf(float complex);
+long double complex __cdecl cprojl(long double complex);
+double __cdecl creal(double complex);
+float __cdecl crealf(float complex);
+long double __cdecl creall(long double complex);
+
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+#define CMPLX(x, y) __builtin_complex((double)(x), (double)(y))
+#define CMPLXF(x, y) __builtin_complex((float)(x), (float)(y))
+#define CMPLXL(x, y) \
+    __builtin_complex((long double)(x), (long double)(y))
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/win32/include/tcc/tcc_libm.h b/win32/include/tcc/tcc_libm.h
index ba26ee00..88fbc1a3 100644
--- a/win32/include/tcc/tcc_libm.h
+++ b/win32/include/tcc/tcc_libm.h
@@ -437,6 +437,7 @@ __CRT_INLINE long double __cdecl fabsl(long double x) {
   __CRT_INLINE float expf(float x) { return exp(x); }
   __CRT_INLINE float floorf(float x) { return floor(x); }
   __CRT_INLINE float fmodf(float x, float y) { return fmod(x, y); }
+  __CRT_INLINE float hypotf(float x, float y) { return hypot(x, y); }
   __CRT_INLINE float logf(float x) { return log(x); }
   __CRT_INLINE float logbf(float x) { return logb(x); }
   __CRT_INLINE float log10f(float x) { return log10(x); }
@@ -447,6 +448,7 @@ __CRT_INLINE long double __cdecl fabsl(long double x) {
   __CRT_INLINE float sqrtf(float x) { return sqrt(x); }
   __CRT_INLINE float tanf(float x) { return tan(x); }
   __CRT_INLINE float tanhf(float x) { return tanh(x); }
+  __CRT_INLINE float copysignf(float x, float y) { return copysign(x, y); }
 #endif
 __CRT_INLINE float __cdecl asinhf(float x) { return asinh(x); }
 __CRT_INLINE float __cdecl acoshf(float x) { return acosh(x); }
@@ -458,6 +460,9 @@ __CRT_INLINE long double __cdecl atanhl(long double x) { return atanh(x); }
 __CRT_INLINE long double __cdecl asinl(long double x) { return asin(x); }
 __CRT_INLINE long double __cdecl acosl(long double x) { return acos(x); }
 __CRT_INLINE long double __cdecl atanl(long double x) { return atan(x); }
+__CRT_INLINE long double __cdecl atan2l(long double x, long double y) {
+  return atan2(x, y);
+}
 __CRT_INLINE long double __cdecl ceill(long double x) { return ceil(x); }
 __CRT_INLINE long double __cdecl coshl(long double x) { return cosh(x); }
 __CRT_INLINE long double __cdecl cosl(long double x) { return cos(x); }
@@ -475,6 +480,9 @@ __CRT_INLINE long double __cdecl sinl(long double x) { return sin(x); }
 __CRT_INLINE long double __cdecl sqrtl(long double x) { return sqrt(x); }
 __CRT_INLINE long double __cdecl tanhl(long double x) { return tanh(x); }
 __CRT_INLINE long double __cdecl tanl(long double x) { return tan(x); }
+__CRT_INLINE long double __cdecl copysignl(long double x, long double y) {
+  return copysign(x, y);
+}
 
 /* Following are accurate, but much shorter implementations than MUSL lib. */
 
diff --git a/x86_64-gen.c b/x86_64-gen.c
index ffa4cbc8..605bcf9d 100644
--- a/x86_64-gen.c
+++ b/x86_64-gen.c
@@ -1194,6 +1194,14 @@ ST_FUNC int classify_x86_64_va_arg(CType *ty)
 ST_FUNC int gfunc_sret(CType *vt, int variadic, CType *ret, int *ret_align, int *regsize)
 {
     int size, align, reg_count;
+    if ((vt->t & VT_COMPLEX)
+        && ((vt->ref->next->type.t & VT_BTYPE) == VT_LDOUBLE)) {
+        ret->ref = NULL;
+        ret->t = VT_LDOUBLE;
+        *ret_align = 1;
+        *regsize = 16;
+        return -1;
+    }
     if (classify_x86_64_arg(vt, ret, &size, &align, &reg_count) == x86_64_mode_memory)
         return 0;
     *ret_align = 1; // Never have to re-align return values for x86-64
@@ -1201,6 +1209,34 @@ ST_FUNC int gfunc_sret(CType *vt, int variadic, CType *ret, int *ret_align, int
     return 1;
 }
 
+ST_FUNC void arch_transfer_ret_regs(int aftercall)
+{
+    CType component_type;
+    SValue real, imaginary;
+    int align, component_size;
+
+    assert(vtop->type.t & VT_COMPLEX);
+    assert((vtop->r & (VT_VALMASK | VT_LVAL)) == (VT_LOCAL | VT_LVAL));
+    component_type = vtop->type.ref->next->type;
+    assert((component_type.t & VT_BTYPE) == VT_LDOUBLE);
+    component_size = type_size(&component_type, &align);
+    real = imaginary = *vtop;
+    real.type = component_type;
+    imaginary.type = component_type;
+    imaginary.c.i += component_size;
+
+    if (aftercall) {
+        store(TREG_ST0, &real);
+        o(0xd8dd); /* fstp %st(0) */
+        store(TREG_ST0, &imaginary);
+        o(0xd8dd); /* fstp %st(0) */
+    } else {
+        /* The SysV ABI returns the real part in st(0), imaginary in st(1). */
+        load(TREG_ST0, &imaginary);
+        load(TREG_ST0, &real);
+    }
+}
+
 #define REGN 6
 static const uint8_t arg_regs[REGN] = {
     TREG_RDI, TREG_RSI, TREG_RDX, TREG_RCX, TREG_R8, TREG_R9
-- 
2.53.0.windows.3

