From 940e02ea928f36e90c8cb4cc2665ea5f31d9217d Mon Sep 17 00:00:00 2001 From: Martin Kinkelin Date: Sat, 5 Aug 2023 13:38:39 +0200 Subject: [PATCH] Make size_t/ptrdiff_t match pointer size on 8/16 bit architectures --- dmd/mtype.d | 28 ++++++++++++++++++++++++++++ dmd/typesem.d | 12 ++++++++++++ tests/compilable/size_t_16bit.d | 13 +++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 tests/compilable/size_t_16bit.d diff --git a/dmd/mtype.d b/dmd/mtype.d index 9b210528f7d..cf1e58fde29 100644 --- a/dmd/mtype.d +++ b/dmd/mtype.d @@ -892,10 +892,38 @@ version (IN_LLVM) twstring = twchar.immutableOf().arrayOf(); tdstring = tdchar.immutableOf().arrayOf(); +version (IN_LLVM) +{ + switch (target.ptrsize) + { + case 1: + tsize_t = basic[Tuns8]; + tptrdiff_t = basic[Tint8]; + break; + case 2: + tsize_t = basic[Tuns16]; + tptrdiff_t = basic[Tint16]; + break; + case 4: + tsize_t = basic[Tuns32]; + tptrdiff_t = basic[Tint32]; + break; + case 8: + tsize_t = basic[Tuns64]; + tptrdiff_t = basic[Tint64]; + break; + default: + assert(0, "Unsupported target pointer size"); + } +} +else +{ const isLP64 = target.isLP64; tsize_t = basic[isLP64 ? Tuns64 : Tuns32]; tptrdiff_t = basic[isLP64 ? Tint64 : Tint32]; +} + thash_t = tsize_t; } diff --git a/dmd/typesem.d b/dmd/typesem.d index f0decf2a48d..456c08ec84f 100644 --- a/dmd/typesem.d +++ b/dmd/typesem.d @@ -1071,6 +1071,18 @@ extern(C++) Type typeSemantic(Type type, const ref Loc loc, Scope* sc) } else { +version (IN_LLVM) +{ + // Kludge for 8/16 bit targets and `__LINE__` default arguments of type int: + // insert hidden cast if the parameter type is size_t. + // Without this, importing object.d fails (Exception constructors taking size_t line numbers). + if (e.isLineInitExp() && target.ptrsize < 4 && fparam.type.equivalent(Type.tsize_t)) + { + if (!e.type) + e.type = Type.tint32; + e = e.castTo(sc, fparam.type); + } +} e = inferType(e, fparam.type); Initializer iz = new ExpInitializer(e.loc, e); iz = iz.initializerSemantic(sc, fparam.type, INITnointerpret); diff --git a/tests/compilable/size_t_16bit.d b/tests/compilable/size_t_16bit.d new file mode 100644 index 00000000000..53e8681e63f --- /dev/null +++ b/tests/compilable/size_t_16bit.d @@ -0,0 +1,13 @@ +// A minimal test wrt. size_t on a 16-bit architecture. + +// REQUIRES: target_AVR +// RUN: %ldc -mtriple=avr -betterC -c %s + +static assert(size_t.sizeof == 2); +static assert(ptrdiff_t.sizeof == 2); + +// test bounds checks +int foo(int[] arr) +{ + return arr[1]; +}