FFI: Don't touch frame in callbacks with tailcalls to fast functions.
[luajit-2.0.git] / src / lj_vmmath.c
blob8b1772071791c3abfa1c5e4f7b36aaf190ce21a0
1 /*
2 ** Math helper functions for assembler VM.
3 ** Copyright (C) 2005-2011 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #define lj_vmmath_c
7 #define LUA_CORE
9 #include <errno.h>
10 #include <math.h>
12 #include "lj_obj.h"
13 #if LJ_HASJIT
14 #include "lj_ir.h"
15 #endif
16 #include "lj_vm.h"
18 /* -- Helper functions for generated machine code ------------------------- */
20 #if LJ_TARGET_X86ORX64
21 /* Wrapper functions to avoid linker issues on OSX. */
22 LJ_FUNCA double lj_vm_sinh(double x) { return sinh(x); }
23 LJ_FUNCA double lj_vm_cosh(double x) { return cosh(x); }
24 LJ_FUNCA double lj_vm_tanh(double x) { return tanh(x); }
25 #endif
27 #if LJ_HASJIT
29 #ifdef LUAJIT_NO_LOG2
30 double lj_vm_log2(double a)
32 return log(a) * 1.4426950408889634074;
34 #endif
36 #ifdef LUAJIT_NO_EXP2
37 double lj_vm_exp2(double a)
39 return exp(a * 0.6931471805599453);
41 #endif
43 #if !(LJ_TARGET_ARM || LJ_TARGET_PPC)
44 int32_t LJ_FASTCALL lj_vm_modi(int32_t a, int32_t b)
46 uint32_t y, ua, ub;
47 lua_assert(b != 0); /* This must be checked before using this function. */
48 ua = a < 0 ? (uint32_t)-a : (uint32_t)a;
49 ub = b < 0 ? (uint32_t)-b : (uint32_t)b;
50 y = ua % ub;
51 if (y != 0 && (a^b) < 0) y = y - ub;
52 if (((int32_t)y^b) < 0) y = (uint32_t)-(int32_t)y;
53 return (int32_t)y;
55 #endif
57 #if !LJ_TARGET_X86ORX64
58 /* Unsigned x^k. */
59 static double lj_vm_powui(double x, uint32_t k)
61 double y;
62 lua_assert(k != 0);
63 for (; (k & 1) == 0; k >>= 1) x *= x;
64 y = x;
65 if ((k >>= 1) != 0) {
66 for (;;) {
67 x *= x;
68 if (k == 1) break;
69 if (k & 1) y *= x;
70 k >>= 1;
72 y *= x;
74 return y;
77 /* Signed x^k. */
78 double lj_vm_powi(double x, int32_t k)
80 if (k > 1)
81 return lj_vm_powui(x, (uint32_t)k);
82 else if (k == 1)
83 return x;
84 else if (k == 0)
85 return 1.0;
86 else
87 return 1.0 / lj_vm_powui(x, (uint32_t)-k);
90 /* Computes fpm(x) for extended math functions. */
91 double lj_vm_foldfpm(double x, int fpm)
93 switch (fpm) {
94 case IRFPM_FLOOR: return lj_vm_floor(x);
95 case IRFPM_CEIL: return lj_vm_ceil(x);
96 case IRFPM_TRUNC: return lj_vm_trunc(x);
97 case IRFPM_SQRT: return sqrt(x);
98 case IRFPM_EXP: return exp(x);
99 case IRFPM_EXP2: return lj_vm_exp2(x);
100 case IRFPM_LOG: return log(x);
101 case IRFPM_LOG2: return lj_vm_log2(x);
102 case IRFPM_LOG10: return log10(x);
103 case IRFPM_SIN: return sin(x);
104 case IRFPM_COS: return cos(x);
105 case IRFPM_TAN: return tan(x);
106 default: lua_assert(0);
108 return 0;
110 #endif
112 #if LJ_HASFFI
113 int lj_vm_errno(void)
115 return errno;
117 #endif
119 #endif