2 * vim: set ts=2 sw=2 tw=99 et:
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
36 #include "../sp_vm_engine.h"
37 #include "../engine2.h"
38 #include "../BaseRuntime.h"
39 #include "../sp_vm_basecontext.h"
41 using namespace Knight;
43 #if defined USE_UNGEN_OPCODES
44 #include "ungen_opcodes.h"
50 KeCodeCache *g_pCodeCache = NULL;
51 ISourcePawnEngine *engine = &g_engine1;
54 LinkCode(AssemblerX86 &masm)
56 if (masm.outOfMemory())
59 void *code = Knight::KE_AllocCode(g_pCodeCache, masm.length());
63 masm.emitToExecutableMemory(code);
67 static inline ConditionCode
68 OpToCondition(OPCODE op)
95 struct array_creation_t
97 const cell_t *dim_list; /* Dimension sizes */
98 cell_t dim_count; /* Number of dimensions */
99 cell_t *data_offs; /* Current offset AFTER the indirection vectors (data) */
100 cell_t *base; /* array base */
104 GenerateInnerArrayIndirectionVectors(array_creation_t *ar, int dim, cell_t cur_offs)
106 cell_t write_offs = cur_offs;
107 cell_t *data_offs = ar->data_offs;
109 cur_offs += ar->dim_list[dim];
111 // Dimension n-x where x > 2 will have sub-vectors.
112 // Otherwise, we just need to reference the data section.
113 if (ar->dim_count > 2 && dim < ar->dim_count - 2) {
114 // For each index at this dimension, write offstes to our sub-vectors.
115 // After we write one sub-vector, we generate its sub-vectors recursively.
116 // At the end, we're given the next offset we can use.
117 for (int i = 0; i < ar->dim_list[dim]; i++) {
118 ar->base[write_offs] = (cur_offs - write_offs) * sizeof(cell_t);
120 cur_offs = GenerateInnerArrayIndirectionVectors(ar, dim + 1, cur_offs);
123 // In this section, there are no sub-vectors, we need to write offsets
124 // to the data. This is separate so the data stays in one big chunk.
125 // The data offset will increment by the size of the last dimension,
126 // because that is where the data is finally computed as.
127 for (int i = 0; i < ar->dim_list[dim]; i++) {
128 ar->base[write_offs] = (*data_offs - write_offs) * sizeof(cell_t);
130 *data_offs = *data_offs + ar->dim_list[dim + 1];
138 calc_indirection(const array_creation_t *ar, cell_t dim)
140 cell_t size = ar->dim_list[dim];
141 if (dim < ar->dim_count - 2)
142 size += ar->dim_list[dim] * calc_indirection(ar, dim + 1);
147 GenerateArrayIndirectionVectors(cell_t *arraybase, cell_t dims[], cell_t _dimcount, bool autozero)
152 /* Reverse the dimensions */
153 cell_t dim_list[sDIMEN_MAX];
155 for (int i = _dimcount - 1; i >= 0; i--)
156 dim_list[cur_dim++] = dims[i];
159 ar.dim_list = dim_list;
160 ar.dim_count = _dimcount;
161 ar.data_offs = &data_offs;
163 data_offs = calc_indirection(&ar, 0);
164 GenerateInnerArrayIndirectionVectors(&ar, 0, 0);
169 PopTrackerAndSetHeap(BaseRuntime *rt)
171 sp_context_t *ctx = rt->GetBaseContext()->GetCtx();
172 tracker_t *trk = (tracker_t *)(ctx->vm[JITVARS_TRACKER]);
173 assert(trk->pCur > trk->pBase);
176 if (trk->pCur < trk->pBase)
177 return SP_ERROR_TRACKER_BOUNDS;
179 ucell_t amt = *trk->pCur;
180 if (amt > (ctx->hp - rt->plugin()->data_size))
181 return SP_ERROR_HEAPMIN;
184 return SP_ERROR_NONE;
188 PushTracker(sp_context_t *ctx, size_t amount)
190 tracker_t *trk = (tracker_t *)(ctx->vm[JITVARS_TRACKER]);
192 if ((size_t)(trk->pCur - trk->pBase) >= trk->size)
193 return SP_ERROR_TRACKER_BOUNDS;
195 if (trk->pCur + 1 - (trk->pBase + trk->size) == 0) {
196 size_t disp = trk->size - 1;
198 trk->pBase = (ucell_t *)realloc(trk->pBase, trk->size * sizeof(cell_t));
201 return SP_ERROR_TRACKER_BOUNDS;
203 trk->pCur = trk->pBase + disp;
206 *trk->pCur++ = amount;
207 return SP_ERROR_NONE;
211 GenerateArray(BaseRuntime *rt, uint32_t argc, cell_t *argv, int autozero)
213 sp_context_t *ctx = rt->GetBaseContext()->GetCtx();
215 // Calculate how many cells are needed.
217 return SP_ERROR_ARRAY_TOO_BIG;
219 uint32_t dim = 1; // second to last dimension
220 uint32_t cells = argv[0];
222 for (uint32_t dim = 1; dim < argc; dim++) {
223 cell_t dimsize = argv[dim];
225 return SP_ERROR_ARRAY_TOO_BIG;
226 if (!ke::IsUint32MultiplySafe(cells, dimsize))
227 return SP_ERROR_ARRAY_TOO_BIG;
228 cells *= uint32_t(dimsize);
229 if (!ke::IsUint32AddSafe(cells, dimsize))
230 return SP_ERROR_ARRAY_TOO_BIG;
231 cells += uint32_t(dimsize);
234 if (!ke::IsUint32MultiplySafe(cells, 4))
235 return SP_ERROR_ARRAY_TOO_BIG;
237 uint32_t bytes = cells * 4;
238 if (!ke::IsUint32AddSafe(ctx->hp, bytes))
239 return SP_ERROR_ARRAY_TOO_BIG;
241 uint32_t new_hp = ctx->hp + bytes;
242 cell_t *dat_hp = reinterpret_cast<cell_t *>(rt->plugin()->memory + new_hp);
244 // argv, coincidentally, is STK.
245 if (dat_hp >= argv - STACK_MARGIN)
246 return SP_ERROR_HEAPLOW;
248 if (int err = PushTracker(rt->GetBaseContext()->GetCtx(), bytes))
251 cell_t *base = reinterpret_cast<cell_t *>(rt->plugin()->memory + ctx->hp);
252 cell_t offs = GenerateArrayIndirectionVectors(base, argv, argc, autozero);
253 assert(size_t(offs) == cells);
255 argv[argc - 1] = ctx->hp;
257 return SP_ERROR_NONE;
262 GetFunctionName(const sp_plugin_t *plugin, uint32_t offs)
264 if (!plugin->debug.unpacked) {
266 sp_fdbg_symbol_t *sym;
267 sp_fdbg_arraydim_t *arr;
268 uint8_t *cursor = (uint8_t *)(plugin->debug.symbols);
270 max = plugin->debug.syms_num;
271 for (iter = 0; iter < max; iter++) {
272 sym = (sp_fdbg_symbol_t *)cursor;
274 if (sym->ident == SP_SYM_FUNCTION && sym->codestart <= offs && sym->codeend > offs)
275 return plugin->debug.stringbase + sym->name;
277 if (sym->dimcount > 0) {
278 cursor += sizeof(sp_fdbg_symbol_t);
279 arr = (sp_fdbg_arraydim_t *)cursor;
280 cursor += sizeof(sp_fdbg_arraydim_t) * sym->dimcount;
284 cursor += sizeof(sp_fdbg_symbol_t);
288 sp_u_fdbg_symbol_t *sym;
289 sp_u_fdbg_arraydim_t *arr;
290 uint8_t *cursor = (uint8_t *)(plugin->debug.symbols);
292 max = plugin->debug.syms_num;
293 for (iter = 0; iter < max; iter++) {
294 sym = (sp_u_fdbg_symbol_t *)cursor;
296 if (sym->ident == SP_SYM_FUNCTION && sym->codestart <= offs && sym->codeend > offs)
297 return plugin->debug.stringbase + sym->name;
299 if (sym->dimcount > 0) {
300 cursor += sizeof(sp_u_fdbg_symbol_t);
301 arr = (sp_u_fdbg_arraydim_t *)cursor;
302 cursor += sizeof(sp_u_fdbg_arraydim_t) * sym->dimcount;
306 cursor += sizeof(sp_u_fdbg_symbol_t);
315 CompileFromThunk(BaseRuntime *runtime, cell_t pcode_offs, void **addrp, char *pc)
317 JitFunction *fn = runtime->GetJittedFunctionByOffset(pcode_offs);
320 fn = g_Jit.CompileFunction(runtime, pcode_offs, &err);
326 g_engine1.GetDebugHook()->OnDebugSpew(
327 "Patching thunk to %s::%s\n",
328 runtime->plugin()->name,
329 GetFunctionName(runtime->plugin(), pcode_offs));
332 *addrp = fn->GetEntryAddress();
334 /* Right now, we always keep the code RWE */
335 *(intptr_t *)(pc - 4) = intptr_t(fn->GetEntryAddress()) - intptr_t(pc);
336 return SP_ERROR_NONE;
340 NativeCallback(sp_context_t *ctx, ucell_t native_idx, cell_t *params)
343 cell_t save_sp = ctx->sp;
344 cell_t save_hp = ctx->hp;
345 sp_plugin_t *pl = (sp_plugin_t *)(ctx->vm[JITVARS_PLUGIN]);
347 ctx->n_idx = native_idx;
349 if (ctx->hp < (cell_t)pl->data_size) {
350 ctx->n_err = SP_ERROR_HEAPMIN;
354 if (ctx->hp + STACK_MARGIN > ctx->sp) {
355 ctx->n_err = SP_ERROR_STACKLOW;
359 if ((uint32_t)ctx->sp >= pl->mem_size) {
360 ctx->n_err = SP_ERROR_STACKMIN;
364 native = &pl->natives[native_idx];
366 if (native->status == SP_NATIVE_UNBOUND) {
367 ctx->n_err = SP_ERROR_INVALID_NATIVE;
371 cell_t result = native->pfn(GET_CONTEXT(ctx), params);
373 if (ctx->n_err != SP_ERROR_NONE)
376 if (save_sp != ctx->sp) {
377 ctx->n_err = SP_ERROR_STACKLEAK;
380 if (save_hp != ctx->hp) {
381 ctx->n_err = SP_ERROR_HEAPLEAK;
388 Compiler::Compiler(BaseRuntime *rt, cell_t pcode_offs)
390 plugin_(rt->plugin()),
391 error_(SP_ERROR_NONE),
392 pcode_start_(pcode_offs),
393 code_start_(reinterpret_cast<cell_t *>(plugin_->pcode + pcode_start_)),
395 code_end_(reinterpret_cast<cell_t *>(plugin_->pcode + plugin_->pcode_size))
397 size_t nmaxops = plugin_->pcode_size / sizeof(cell_t) + 1;
398 jump_map_ = new Label[nmaxops];
401 Compiler::~Compiler()
407 Compiler::emit(int *errp)
409 if (cip_ >= code_end_ || *cip_ != OP_PROC) {
410 *errp = SP_ERROR_INVALID_INSTRUCTION;
415 g_engine1.GetDebugHook()->OnDebugSpew(
416 "Compiling function %s::%s\n",
418 GetFunctionName(plugin_, pcode_start_));
420 SpewOpcode(plugin_, code_start_, cip_);
423 cell_t *codeseg = reinterpret_cast<cell_t *>(plugin_->pcode);
426 if (!emitOp(OP_PROC)) {
427 *errp = (error_ == SP_ERROR_NONE) ? SP_ERROR_OUT_OF_MEMORY : error_;
431 while (cip_ < code_end_) {
432 // If we reach the end of this function, or the beginning of a new
433 // procedure, then stop.
434 if (*cip_ == OP_PROC || *cip_ == OP_ENDPROC)
438 SpewOpcode(plugin_, code_start_, cip_);
441 // We assume every instruction is a jump target, so before emitting
442 // an opcode, we bind its corresponding label.
443 __ bind(&jump_map_[cip_ - codeseg]);
445 OPCODE op = (OPCODE)readCell();
446 if (!emitOp(op) || error_ != SP_ERROR_NONE) {
447 *errp = (error_ == SP_ERROR_NONE) ? SP_ERROR_OUT_OF_MEMORY : error_;
455 void *code = LinkCode(masm);
457 *errp = SP_ERROR_OUT_OF_MEMORY;
461 return new JitFunction(code, pcode_start_);
465 Compiler::emitOp(OPCODE op)
482 cell_t offset = readCell();
483 __ movl(Operand(dat, offset), 0);
489 cell_t offset = readCell();
490 __ movl(Operand(frm, offset), 0);
497 Register reg = (op == OP_PUSH_PRI) ? pri : alt;
498 __ movl(Operand(stk, -4), reg);
510 if (op >= OP_PUSH2_C)
511 n = ((op - OP_PUSH2_C) / 4) + 2;
515 cell_t val = readCell();
516 __ movl(Operand(stk, -(4 * i)), val);
529 if (op >= OP_PUSH2_ADR)
530 n = ((op - OP_PUSH2_ADR) / 4) + 2;
534 // We temporarily relocate FRM to be a local address instead of an
538 cell_t offset = readCell();
539 __ lea(tmp, Operand(frm, offset));
540 __ movl(Operand(stk, -(4 * i)), tmp);
554 if (op >= OP_PUSH2_S)
555 n = ((op - OP_PUSH2_S) / 4) + 2;
559 cell_t offset = readCell();
560 __ movl(tmp, Operand(frm, offset));
561 __ movl(Operand(stk, -(4 * i)), tmp);
575 n = ((op - OP_PUSH2) / 4) + 2;
579 cell_t offset = readCell();
580 __ movl(tmp, Operand(dat, offset));
581 __ movl(Operand(stk, -(4 * i)), tmp);
610 // Push the old frame onto the stack.
611 __ movl(tmp, Operand(frmAddr()));
612 __ movl(Operand(stk, -4), tmp);
613 __ subl(stk, 8); // extra unused slot for non-existant CIP
615 // Get and store the new frame.
619 __ movl(Operand(frmAddr()), tmp);
621 // Align the stack to 16-bytes (each call adds 4 bytes).
627 cell_t val = readCell();
651 Register reg = (op == OP_SHL_C_PRI) ? pri : alt;
652 cell_t val = readCell();
660 Register reg = (op == OP_SHR_C_PRI) ? pri : alt;
661 cell_t val = readCell();
698 cell_t val = readCell();
705 cell_t val = readCell();
706 __ imull(pri, pri, val);
717 ConditionCode cc = OpToCondition(op);
727 Register reg = (op == OP_EQ_C_PRI) ? pri : alt;
728 cell_t val = readCell();
731 __ set(equal, r8_al);
738 Register reg = (OP_INC_PRI) ? pri : alt;
746 Register base = (op == OP_INC) ? dat : frm;
747 cell_t offset = readCell();
748 __ addl(Operand(base, offset), 1);
753 __ addl(Operand(dat, pri, NoScale), 1);
759 Register reg = (op == OP_DEC_PRI) ? pri : alt;
767 Register base = (op == OP_DEC) ? dat : frm;
768 cell_t offset = readCell();
769 __ subl(Operand(base, offset), 1);
774 __ subl(Operand(dat, pri, NoScale), 1);
780 Register reg = (op == OP_LOAD_PRI) ? pri : alt;
781 cell_t offset = readCell();
782 __ movl(reg, Operand(dat, offset));
788 cell_t offs1 = readCell();
789 cell_t offs2 = readCell();
790 __ movl(pri, Operand(dat, offs1));
791 __ movl(alt, Operand(dat, offs2));
798 Register reg = (op == OP_LOAD_S_PRI) ? pri : alt;
799 cell_t offset = readCell();
800 __ movl(reg, Operand(frm, offset));
806 cell_t offs1 = readCell();
807 cell_t offs2 = readCell();
808 __ movl(pri, Operand(frm, offs1));
809 __ movl(alt, Operand(frm, offs2));
816 Register reg = (op == OP_LREF_S_PRI) ? pri : alt;
817 cell_t offset = readCell();
818 __ movl(reg, Operand(frm, offset));
819 __ movl(reg, Operand(dat, reg, NoScale));
826 Register reg = (op == OP_CONST_PRI) ? pri : alt;
827 cell_t val = readCell();
835 Register reg = (op == OP_ADDR_PRI) ? pri : alt;
836 cell_t offset = readCell();
837 __ movl(reg, Operand(frmAddr()));
838 __ addl(reg, offset);
845 Register reg = (op == OP_STOR_PRI) ? pri : alt;
846 cell_t offset = readCell();
847 __ movl(Operand(dat, offset), reg);
854 Register reg = (op == OP_STOR_S_PRI) ? pri : alt;
855 cell_t offset = readCell();
856 __ movl(Operand(frm, offset), reg);
861 __ lea(pri, Operand(alt, pri, ScaleFour));
867 Register reg = (op == OP_SREF_S_PRI) ? pri : alt;
868 cell_t offset = readCell();
869 __ movl(tmp, Operand(frm, offset));
870 __ movl(Operand(dat, tmp, NoScale), reg);
877 Register reg = (op == OP_POP_PRI) ? pri : alt;
878 __ movl(reg, Operand(stk, 0));
886 Register reg = (op == OP_SWAP_PRI) ? pri : alt;
887 __ movl(tmp, Operand(stk, 0));
888 __ movl(Operand(stk, 0), reg);
894 __ lea(pri, Operand(alt, pri, ScaleFour));
895 __ movl(pri, Operand(dat, pri, NoScale));
900 cell_t val = readCell();
901 if (val >= 0 && val <= 3) {
902 __ lea(pri, Operand(alt, pri, Scale(val)));
907 emitCheckAddress(pri);
908 __ movl(pri, Operand(dat, pri, NoScale));
915 Register base = (op == OP_CONST) ? dat : frm;
916 cell_t offset = readCell();
917 cell_t val = readCell();
918 __ movl(Operand(base, offset), val);
923 emitCheckAddress(pri);
924 __ movl(pri, Operand(dat, pri, NoScale));
928 emitCheckAddress(alt);
929 __ movl(Operand(dat, alt, NoScale), pri);
935 Register dividend = (op == OP_SDIV) ? pri : alt;
936 Register divisor = (op == OP_SDIV) ? alt : pri;
938 // Guard against divide-by-zero.
939 __ testl(divisor, divisor);
940 __ j(zero, &error_divide_by_zero_);
942 // A more subtle case; -INT_MIN / -1 yields an overflow exception.
944 __ cmpl(divisor, -1);
945 __ j(not_equal, &ok);
946 __ cmpl(dividend, 0x80000000);
947 __ j(equal, &error_integer_overflow_);
950 // Now we can actually perform the divide.
951 __ movl(tmp, divisor);
953 __ movl(edx, dividend);
955 __ movl(eax, dividend);
963 cell_t val = readCell();
964 emitCheckAddress(pri);
965 __ movl(pri, Operand(dat, pri, NoScale));
969 __ andl(pri, 0xffff);
975 cell_t val = readCell();
976 emitCheckAddress(alt);
978 __ movb(Operand(dat, alt, NoScale), pri);
980 __ movw(Operand(dat, alt, NoScale), pri);
982 __ movl(Operand(dat, alt, NoScale), pri);
988 // Restore the old frame pointer.
989 __ movl(frm, Operand(stk, 4)); // get the old frm
990 __ addl(stk, 8); // pop stack
991 __ movl(Operand(frmAddr()), frm); // store back old frm
992 __ addl(frm, dat); // relocate
994 // Remove parameters.
995 __ movl(tmp, Operand(stk, 0));
996 __ lea(stk, Operand(stk, tmp, ScaleFour, 4));
1004 cell_t val = readCell();
1005 unsigned dwords = val / 4;
1006 unsigned bytes = val % 4;
1011 __ lea(esi, Operand(dat, pri, NoScale));
1012 __ lea(edi, Operand(dat, alt, NoScale));
1014 __ movl(ecx, dwords);
1018 __ movl(ecx, bytes);
1028 // eax/pri is used implicitly.
1029 unsigned dwords = readCell() / 4;
1031 __ lea(edi, Operand(dat, alt, NoScale));
1032 __ movl(ecx, dwords);
1039 case OP_STRADJUST_PRI:
1045 __ movl(pri, Operand(stk, 0));
1046 __ andl(pri, 0x7fffffff);
1051 if (MacroAssemblerX86::Features().sse2) {
1052 __ cvtsi2ss(xmm0, Operand(edi, 0));
1055 __ fild32(Operand(edi, 0));
1057 __ fstp32(Operand(esp, 0));
1067 if (MacroAssemblerX86::Features().sse2) {
1068 __ movss(xmm0, Operand(stk, 0));
1069 if (op == OP_FLOATADD)
1070 __ addss(xmm0, Operand(stk, 4));
1071 else if (op == OP_FLOATSUB)
1072 __ subss(xmm0, Operand(stk, 4));
1073 else if (op == OP_FLOATMUL)
1074 __ mulss(xmm0, Operand(stk, 4));
1075 else if (op == OP_FLOATDIV)
1076 __ divss(xmm0, Operand(stk, 4));
1080 __ fld32(Operand(stk, 0));
1082 if (op == OP_FLOATADD)
1083 __ fadd32(Operand(stk, 4));
1084 else if (op == OP_FLOATSUB)
1085 __ fsub32(Operand(stk, 4));
1086 else if (op == OP_FLOATMUL)
1087 __ fmul32(Operand(stk, 4));
1088 else if (op == OP_FLOATDIV)
1089 __ fdiv32(Operand(stk, 4));
1091 __ fstp32(Operand(esp, 0));
1097 case OP_RND_TO_NEAREST:
1099 if (MacroAssemblerX86::Features().sse) {
1100 // Assume no one is touching MXCSR.
1101 __ cvtss2si(pri, Operand(stk, 0));
1103 static float kRoundToNearest = 0.5f;
1104 // From http://wurstcaptures.untergrund.net/assembler_tricks.html#fastfloorf
1105 __ fld32(Operand(stk, 0));
1106 __ fadd32(st0, st0);
1107 __ fadd32(Operand(ExternalAddress(&kRoundToNearest)));
1109 __ fistp32(Operand(esp, 0));
1117 case OP_RND_TO_CEIL:
1119 static float kRoundToCeil = -0.5f;
1120 // From http://wurstcaptures.untergrund.net/assembler_tricks.html#fastfloorf
1121 __ fld32(Operand(stk, 0));
1122 __ fadd32(st0, st0);
1123 __ fsubr32(Operand(ExternalAddress(&kRoundToCeil)));
1125 __ fistp32(Operand(esp, 0));
1133 case OP_RND_TO_ZERO:
1134 if (MacroAssemblerX86::Features().sse) {
1135 __ cvttss2si(pri, Operand(stk, 0));
1137 __ fld32(Operand(stk, 0));
1139 __ fstcw(Operand(esp, 4));
1140 __ movl(Operand(esp, 0), 0xfff);
1141 __ fldcw(Operand(esp, 0));
1142 __ fistp32(Operand(esp, 0));
1144 __ fldcw(Operand(esp, 0));
1150 case OP_RND_TO_FLOOR:
1151 __ fld32(Operand(stk, 0));
1153 __ fstcw(Operand(esp, 4));
1154 __ movl(Operand(esp, 0), 0x7ff);
1155 __ fldcw(Operand(esp, 0));
1156 __ fistp32(Operand(esp, 0));
1158 __ fldcw(Operand(esp, 0));
1166 if (MacroAssemblerX86::Features().sse) {
1167 __ movss(xmm0, Operand(stk, 4));
1168 __ ucomiss(xmm0, Operand(stk, 0));
1170 __ fld32(Operand(stk, 0));
1171 __ fld32(Operand(stk, 4));
1191 cell_t amount = readCell();
1192 __ addl(stk, amount);
1195 // Check if the stack went beyond the stack top - usually a compiler error.
1196 __ cmpl(stk, intptr_t(plugin_->memory + plugin_->mem_size));
1197 __ j(not_below, &error_stack_min_);
1199 // Check if the stack is going to collide with the heap.
1200 __ movl(tmp, Operand(hpAddr()));
1201 __ lea(tmp, Operand(dat, ecx, NoScale, STACK_MARGIN));
1203 __ j(below, &error_stack_low_);
1210 cell_t amount = readCell();
1211 __ movl(alt, Operand(hpAddr()));
1212 __ addl(Operand(hpAddr()), amount);
1215 __ cmpl(Operand(hpAddr()), plugin_->data_size);
1216 __ j(below, &error_heap_min_);
1218 __ movl(tmp, Operand(hpAddr()));
1219 __ lea(tmp, Operand(dat, ecx, NoScale, STACK_MARGIN));
1221 __ j(above, &error_heap_low_);
1228 Label *target = labelAt(readCell());
1238 ConditionCode cc = (op == OP_JZER) ? zero : not_zero;
1239 Label *target = labelAt(readCell());
1254 Label *target = labelAt(readCell());
1257 ConditionCode cc = OpToCondition(op);
1263 case OP_TRACKER_PUSH_C:
1265 cell_t amount = readCell();
1270 __ push(amount * 4);
1271 __ push(intptr_t(rt_->GetBaseContext()->GetCtx()));
1272 __ call(ExternalAddress((void *)PushTracker));
1275 __ j(not_zero, &extern_error_);
1282 case OP_TRACKER_POP_SETHEAP:
1288 // Get the context pointer and call the sanity checker.
1289 __ push(intptr_t(rt_));
1290 __ call(ExternalAddress((void *)PopTrackerAndSetHeap));
1293 __ j(not_zero, &extern_error_);
1302 cell_t cip = uintptr_t(cip_ - 1) - uintptr_t(plugin_->pcode);
1303 __ movl(Operand(cipAddr()), cip);
1309 __ movl(tmp, intptr_t(rt_->GetBaseContext()->GetCtx()));
1310 __ movl(Operand(tmp, offsetof(sp_context_t, rval)), pri);
1311 __ movl(pri, readCell());
1312 __ jmp(&extern_error_);
1317 cell_t value = readCell();
1318 __ cmpl(eax, value);
1319 __ j(above, &error_bounds_);
1325 emitGenArray(op == OP_GENARRAY_Z);
1335 if (!emitNativeCall(op))
1346 size_t ncases = readCell();
1348 // Two cells per case, and one extra cell for the default address.
1349 cip_ += (ncases * 2) + 1;
1357 error_ = SP_ERROR_INVALID_INSTRUCTION;
1365 Compiler::labelAt(size_t offset)
1367 if (offset % 4 != 0 ||
1368 offset > plugin_->pcode_size ||
1369 offset <= pcode_start_)
1371 // If the jump target is misaligned, or out of pcode bounds, or is an
1372 // address out of the function bounds, we abort. Unfortunately we can't
1373 // test beyond the end of the function since we don't have a precursor
1375 error_ = SP_ERROR_INSTRUCTION_PARAM;
1379 return &jump_map_[offset / sizeof(cell_t)];
1383 Compiler::emitCheckAddress(Register reg)
1385 // Check if we're in memory bounds.
1386 __ cmpl(reg, plugin_->mem_size);
1387 __ j(not_below, &error_memaccess_);
1389 // Check if we're in the invalid region between hp and sp.
1391 __ cmpl(reg, Operand(hpAddr()));
1393 __ lea(tmp, Operand(dat, reg, NoScale));
1395 __ j(below, &error_memaccess_);
1400 Compiler::emitGenArray(bool autozero)
1402 cell_t val = readCell();
1405 // flat array; we can generate this without indirection tables.
1406 // Note that we can overwrite ALT because technically STACK should be destroying ALT
1407 __ movl(alt, Operand(hpAddr()));
1408 __ movl(tmp, Operand(stk, 0));
1409 __ movl(Operand(stk, 0), alt); // store base of the array into the stack.
1410 __ lea(alt, Operand(alt, tmp, ScaleFour));
1411 __ movl(Operand(hpAddr()), alt);
1414 __ j(not_below, &error_heap_low_);
1418 __ push(intptr_t(rt_->GetBaseContext()->GetCtx()));
1419 __ call(ExternalAddress((void *)PushTracker));
1424 __ j(not_zero, &extern_error_);
1427 // Note - tmp is ecx and still intact.
1431 __ movl(edi, Operand(stk, 0));
1441 // int GenerateArray(sp_plugin_t, vars[], uint32_t, cell_t *, int, unsigned *);
1442 __ push(autozero ? 1 : 0);
1445 __ push(intptr_t(rt_));
1446 __ call(ExternalAddress((void *)GenerateArray));
1447 __ addl(esp, 4 * sizeof(void *));
1449 // restore pri to tmp
1453 __ j(not_zero, &extern_error_);
1455 // Move tmp back to pri, remove pushed args.
1457 __ addl(stk, (val - 1) * 4);
1462 Compiler::emitCall()
1464 cell_t offset = readCell();
1466 // If this offset looks crappy, i.e. not aligned or out of bounds, we just
1468 if (offset % 4 != 0 || uint32_t(offset) >= plugin_->pcode_size) {
1469 error_ = SP_ERROR_INSTRUCTION_PARAM;
1475 __ movl(eax, intptr_t(rt_->GetBaseContext()->GetCtx()));
1476 __ movl(ecx, Operand(eax, offsetof(sp_context_t, rp)));
1478 // Check if the return stack is used up.
1479 __ cmpl(ecx, SP_MAX_RETURN_STACK);
1480 __ j(not_below, &error_stack_low_);
1482 // Add to the return stack.
1483 uintptr_t cip = uintptr_t(cip_ - 2) - uintptr_t(plugin_->pcode);
1484 __ movl(Operand(eax, ecx, ScaleFour, offsetof(sp_context_t, rstk_cips)), cip);
1486 // Increment the return stack pointer.
1487 __ addl(Operand(eax, offsetof(sp_context_t, rp)), 1);
1489 // Store the CIP of the function we're about to call.
1490 __ movl(Operand(cipAddr()), offset);
1492 JitFunction *fun = rt_->GetJittedFunctionByOffset(offset);
1494 // Need to emit a delayed thunk.
1495 CallThunk *thunk = new CallThunk(offset);
1496 __ call(&thunk->call);
1497 if (!thunks_.append(thunk))
1500 // Function is already emitted, we can do a direct call.
1501 __ call(ExternalAddress(fun->GetEntryAddress()));
1504 // Restore the last cip.
1505 __ movl(Operand(cipAddr()), cip);
1507 // Mark us as leaving the last frame.
1508 __ movl(tmp, intptr_t(rt_->GetBaseContext()->GetCtx()));
1509 __ subl(Operand(tmp, offsetof(sp_context_t, rp)), 1);
1514 Compiler::emitCallThunks()
1516 for (size_t i = 0; i < thunks_.length(); i++) {
1517 CallThunk *thunk = thunks_[i];
1520 __ bind(&thunk->call);
1521 // Huge hack - get the return address, since that is the call that we
1523 __ movl(eax, Operand(esp, 0));
1525 // Align the stack. Unfortunately this is a pretty careful dance based
1526 // on the number of words we push (4 args, 1 saved esp), and someday
1527 // we should look into automating this.
1529 __ andl(esp, 0xfffffff0);
1536 __ movl(Operand(esp, 0), esp);
1537 __ push(thunk->pcode_offset);
1538 __ push(intptr_t(rt_));
1539 __ call(ExternalAddress((void *)CompileFromThunk));
1540 __ movl(edx, Operand(esp, 8));
1541 __ movl(esp, Operand(esp, 16));
1543 __ j(not_zero, &error);
1548 __ movl(Operand(cipAddr()), thunk->pcode_offset);
1549 __ jmp(g_Jit.GetUniversalReturn());
1554 Compiler::readCell()
1556 if (cip_ >= code_end_) {
1557 error_= SP_ERROR_INVALID_INSTRUCTION;
1564 Compiler::emitNativeCall(OPCODE op)
1566 uint32_t native_index = readCell();
1568 if (native_index >= plugin_->num_natives) {
1569 error_ = SP_ERROR_INSTRUCTION_PARAM;
1573 uint32_t num_params;
1574 if (op == OP_SYSREQ_N) {
1575 num_params = readCell();
1577 // See if we can get a replacement opcode. If we can, then recursively
1578 // call emitOp() to generate it. Note: it's important that we do this
1579 // before generating any code for the SYSREQ.N.
1580 unsigned replacement = rt_->GetNativeReplacement(native_index);
1581 if (replacement != OP_NOP)
1582 return emitOp((OPCODE)replacement);
1584 // Store the number of parameters.
1585 __ movl(Operand(stk, -4), num_params);
1592 // Push the parameters for the C++ function.
1594 __ push(native_index);
1596 // Relocate our absolute stk to be dat-relative, and update the context's
1598 __ movl(eax, intptr_t(rt_->GetBaseContext()->GetCtx()));
1600 __ movl(Operand(eax, offsetof(sp_context_t, sp)), stk);
1602 // Push context and make the call.
1604 __ call(ExternalAddress((void *)NativeCallback));
1606 // Check for errors.
1607 __ movl(ecx, intptr_t(rt_->GetBaseContext()->GetCtx()));
1608 __ movl(ecx, Operand(ecx, offsetof(sp_context_t, n_err)));
1610 __ j(not_zero, &extern_error_);
1612 // Restore local state.
1617 if (op == OP_SYSREQ_N) {
1618 // Pop the stack. Do not check the margins.
1619 __ addl(stk, (num_params + 1) * sizeof(cell_t));
1625 Compiler::emitSwitch()
1627 cell_t offset = readCell();
1628 if (!labelAt(offset))
1631 cell_t *tbl = (cell_t *)((char *)plugin_->pcode + offset + sizeof(cell_t));
1638 size_t ncases = *tbl++;
1640 Label *defaultCase = labelAt(*tbl);
1644 // Degenerate - 0 cases.
1646 __ jmp(defaultCase);
1650 Entry *cases = (Entry *)(tbl + 1);
1652 // Degenerate - 1 case.
1654 Label *maybe = labelAt(cases[0].offset);
1657 __ cmpl(pri, cases[0].val);
1659 __ jmp(defaultCase);
1663 // We have two or more cases, so let's generate a full switch. Decide
1664 // whether we'll make an if chain, or a jump table, based on whether
1665 // the numbers are strictly sequential.
1666 bool sequential = true;
1668 cell_t first = cases[0].val;
1669 cell_t last = first;
1670 for (size_t i = 1; i < ncases; i++) {
1671 if (cases[i].val != ++last) {
1678 // First check whether the bounds are correct: if (a < LOW || a > HIGH);
1679 // this check is valid whether or not we emit a sequential-optimized switch.
1680 cell_t low = cases[0].val;
1682 // negate it so we'll get a lower bound of 0.
1684 __ lea(tmp, Operand(pri, low));
1689 cell_t high = abs(cases[0].val - cases[ncases - 1].val);
1691 __ j(above, defaultCase);
1694 // Optimized table version. The tomfoolery below is because we only have
1695 // one free register... it seems unlikely pri or alt will be used given
1696 // that we're at the end of a control-flow point, but we'll play it safe.
1699 __ movl(eax, &table);
1700 __ movl(ecx, Operand(eax, ecx, ScaleFour));
1705 for (size_t i = 0; i < ncases; i++) {
1706 Label *label = labelAt(cases[i].offset);
1709 __ emit_absolute_address(label);
1712 // Slower version. Go through each case and generate a check.
1713 for (size_t i = 0; i < ncases; i++) {
1714 Label *label = labelAt(cases[i].offset);
1717 __ cmpl(pri, cases[i].val);
1720 __ jmp(defaultCase);
1726 Compiler::emitErrorPath(Label *dest, int code)
1731 __ jmp(g_Jit.GetUniversalReturn());
1736 Compiler::emitErrorPaths()
1738 emitErrorPath(&error_divide_by_zero_, SP_ERROR_DIVIDE_BY_ZERO);
1739 emitErrorPath(&error_stack_low_, SP_ERROR_STACKLOW);
1740 emitErrorPath(&error_stack_min_, SP_ERROR_STACKMIN);
1741 emitErrorPath(&error_bounds_, SP_ERROR_ARRAY_BOUNDS);
1742 emitErrorPath(&error_memaccess_, SP_ERROR_MEMACCESS);
1743 emitErrorPath(&error_heap_low_, SP_ERROR_HEAPLOW);
1744 emitErrorPath(&error_heap_min_, SP_ERROR_HEAPMIN);
1745 emitErrorPath(&error_integer_overflow_, SP_ERROR_INTEGER_OVERFLOW);
1747 if (extern_error_.used()) {
1748 __ bind(&extern_error_);
1749 __ movl(eax, intptr_t(rt_->GetBaseContext()->GetCtx()));
1750 __ movl(eax, Operand(eax, offsetof(sp_context_t, n_err)));
1751 __ jmp(g_Jit.GetUniversalReturn());
1755 typedef int (*JIT_EXECUTE)(sp_context_t *ctx, uint8_t *memory, void *code);
1758 GenerateEntry(void **retp)
1765 __ push(esi); // ebp - 4
1766 __ push(edi); // ebp - 8
1767 __ push(ebx); // ebp - 12
1768 __ push(esp); // ebp - 16
1770 __ movl(ebx, Operand(ebp, 8 + 4 * 0));
1771 __ movl(eax, Operand(ebp, 8 + 4 * 1));
1772 __ movl(ecx, Operand(ebp, 8 + 4 * 2));
1774 // Set up run-time registers.
1775 __ movl(edi, Operand(ebx, offsetof(sp_context_t, sp)));
1781 __ andl(esp, 0xfffffff0);
1783 // Call into plugin (align the stack first).
1786 // Get input context, store rval.
1787 __ movl(ecx, Operand(ebp, 8 + 4 * 0));
1788 __ movl(Operand(ecx, offsetof(sp_context_t, rval)), pri);
1791 __ movl(eax, SP_ERROR_NONE);
1793 // Store latest stk. If we have an error code, we'll jump directly to here,
1794 // so eax will already be set.
1798 __ movl(Operand(ecx, offsetof(sp_context_t, sp)), stk);
1801 __ movl(esp, Operand(ebp, -16));
1803 // Restore registers and gtfo.
1810 // The universal emergency return will jump to here.
1813 __ movl(ecx, Operand(ebp, 8 + 4 * 0)); // ret-path expects ecx = ctx
1816 void *code = LinkCode(masm);
1820 *retp = reinterpret_cast<uint8_t *>(code) + error.offset();
1824 ICompilation *JITX86::ApplyOptions(ICompilation *_IN, ICompilation *_OUT)
1829 CompData *_in = (CompData * )_IN;
1830 CompData *_out = (CompData * )_OUT;
1832 _in->inline_level = _out->inline_level;
1833 _in->profile = _out->profile;
1844 bool JITX86::InitializeJIT()
1846 g_pCodeCache = KE_CreateCodeCache();
1848 m_pJitEntry = GenerateEntry(&m_pJitReturn);
1852 MacroAssemblerX86 masm;
1853 MacroAssemblerX86::GenerateFeatureDetection(masm);
1854 void *code = LinkCode(masm);
1857 MacroAssemblerX86::RunFeatureDetection(code);
1858 KE_FreeCode(g_pCodeCache, code);
1864 JITX86::ShutdownJIT()
1866 KE_DestroyCodeCache(g_pCodeCache);
1870 JITX86::CompileFunction(BaseRuntime *prt, cell_t pcode_offs, int *err)
1872 Compiler cc(prt, pcode_offs);
1873 JitFunction *fun = cc.emit(err);
1876 prt->AddJittedFunction(fun);
1881 JITX86::SetupContextVars(BaseRuntime *runtime, BaseContext *pCtx, sp_context_t *ctx)
1883 tracker_t *trk = new tracker_t;
1885 ctx->vm[JITVARS_TRACKER] = trk;
1886 ctx->vm[JITVARS_BASECTX] = pCtx; /* GetDefaultContext() is not constructed yet */
1887 ctx->vm[JITVARS_PROFILER] = g_engine2.GetProfiler();
1888 ctx->vm[JITVARS_PLUGIN] = const_cast<sp_plugin_t *>(runtime->plugin());
1890 trk->pBase = (ucell_t *)malloc(1024);
1891 trk->pCur = trk->pBase;
1892 trk->size = 1024 / sizeof(cell_t);
1896 JITX86::CreateFakeNative(SPVM_FAKENATIVE_FUNC callback, void *pData)
1903 __ movl(edi, Operand(esp, 16)); // store ctx
1904 __ movl(esi, Operand(esp, 20)); // store params
1906 __ andl(esp, 0xfffffff0);
1909 __ push(intptr_t(pData));
1912 __ call(ExternalAddress((void *)callback));
1919 return (SPVM_NATIVE_FUNC)LinkCode(masm);
1922 void JITX86::DestroyFakeNative(SPVM_NATIVE_FUNC func)
1924 KE_FreeCode(g_pCodeCache, (void *)func);
1927 ICompilation *JITX86::StartCompilation()
1929 return new CompData;
1932 ICompilation *JITX86::StartCompilation(BaseRuntime *runtime)
1934 return new CompData;
1937 void CompData::Abort()
1942 void JITX86::FreeContextVars(sp_context_t *ctx)
1944 free(((tracker_t *)(ctx->vm[JITVARS_TRACKER]))->pBase);
1945 delete (tracker_t *)ctx->vm[JITVARS_TRACKER];
1948 bool CompData::SetOption(const char *key, const char *val)
1950 if (strcmp(key, SP_JITCONF_DEBUG) == 0)
1952 if (strcmp(key, SP_JITCONF_PROFILE) == 0) {
1953 profile = atoi(val);
1955 /** Callbacks must be profiled to profile functions! */
1956 if ((profile & SP_PROF_FUNCTIONS) == SP_PROF_FUNCTIONS)
1957 profile |= SP_PROF_CALLBACKS;
1965 int JITX86::InvokeFunction(BaseRuntime *runtime, JitFunction *fn, cell_t *result)
1967 sp_context_t *ctx = runtime->GetBaseContext()->GetCtx();
1969 // Note that cip, hp, sp are saved and restored by Execute2().
1970 ctx->cip = fn->GetPCodeAddress();
1972 JIT_EXECUTE pfn = (JIT_EXECUTE)m_pJitEntry;
1973 int err = pfn(ctx, runtime->plugin()->memory, fn->GetEntryAddress());
1975 *result = ctx->rval;
1979 void *JITX86::AllocCode(size_t size)
1981 return Knight::KE_AllocCode(g_pCodeCache, size);
1984 void JITX86::FreeCode(void *code)
1986 KE_FreeCode(g_pCodeCache, code);