Merge pull request #642 from Ventero/CleanCopyLocal
[mono.git] / mono / mini / tramp-amd64.c
1 /*
2  * tramp-amd64.c: JIT trampoline code for amd64
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2001 Ximian, Inc.
9  * Copyright 2003-2011 Novell, Inc (http://www.novell.com)
10  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11  */
12
13 #include <config.h>
14 #include <glib.h>
15
16 #include <mono/metadata/appdomain.h>
17 #include <mono/metadata/marshal.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/mono-debug-debugger.h>
20 #include <mono/metadata/monitor.h>
21 #include <mono/metadata/monitor.h>
22 #include <mono/metadata/gc-internal.h>
23 #include <mono/arch/amd64/amd64-codegen.h>
24
25 #include <mono/utils/memcheck.h>
26
27 #include "mini.h"
28 #include "mini-amd64.h"
29
30 #if defined(__native_client_codegen__) && defined(__native_client__)
31 #include <malloc.h>
32 #include <sys/nacl_syscalls.h>
33 #endif
34
35 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
36
37 static guint8* nullified_class_init_trampoline;
38
39 /*
40  * mono_arch_get_unbox_trampoline:
41  * @m: method pointer
42  * @addr: pointer to native code for @m
43  *
44  * when value type methods are called through the vtable we need to unbox the
45  * this argument. This method returns a pointer to a trampoline which does
46  * unboxing before calling the method
47  */
48 gpointer
49 mono_arch_get_unbox_trampoline (MonoMethod *m, gpointer addr)
50 {
51         guint8 *code, *start;
52         int this_reg, size = NACL_SIZE (20, 32);
53
54         MonoDomain *domain = mono_domain_get ();
55
56         this_reg = mono_arch_get_this_arg_reg (NULL);
57
58         start = code = mono_domain_code_reserve (domain, size);
59
60         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
61         /* FIXME: Optimize this */
62         amd64_mov_reg_imm (code, AMD64_RAX, addr);
63         amd64_jump_reg (code, AMD64_RAX);
64         g_assert ((code - start) < size);
65
66         nacl_domain_code_validate (domain, &start, size, &code);
67
68         mono_arch_flush_icache (start, code - start);
69
70         return start;
71 }
72
73 /*
74  * mono_arch_get_static_rgctx_trampoline:
75  *
76  *   Create a trampoline which sets RGCTX_REG to MRGCTX, then jumps to ADDR.
77  */
78 gpointer
79 mono_arch_get_static_rgctx_trampoline (MonoMethod *m, MonoMethodRuntimeGenericContext *mrgctx, gpointer addr)
80 {
81         guint8 *code, *start;
82         int buf_len;
83
84         MonoDomain *domain = mono_domain_get ();
85
86 #ifdef MONO_ARCH_NOMAP32BIT
87         buf_len = 32;
88 #else
89         /* AOTed code could still have a non-32 bit address */
90         if ((((guint64)addr) >> 32) == 0)
91                 buf_len = NACL_SIZE (16, 32);
92         else
93                 buf_len = NACL_SIZE (30, 32);
94 #endif
95
96         start = code = mono_domain_code_reserve (domain, buf_len);
97
98         amd64_mov_reg_imm (code, MONO_ARCH_RGCTX_REG, mrgctx);
99         amd64_jump_code (code, addr);
100         g_assert ((code - start) < buf_len);
101
102         nacl_domain_code_validate (domain, &start, buf_len, &code);
103         mono_arch_flush_icache (start, code - start);
104
105         return start;
106 }
107
108 gpointer
109 mono_arch_get_llvm_imt_trampoline (MonoDomain *domain, MonoMethod *m, int vt_offset)
110 {
111         guint8 *code, *start;
112         int buf_len;
113         int this_reg;
114
115         buf_len = 32;
116
117         start = code = mono_domain_code_reserve (domain, buf_len);
118
119         this_reg = mono_arch_get_this_arg_reg (NULL);
120
121         /* Set imt arg */
122         amd64_mov_reg_imm (code, MONO_ARCH_IMT_REG, m);
123         /* Load vtable address */
124         amd64_mov_reg_membase (code, AMD64_RAX, this_reg, 0, 8);
125         amd64_jump_membase (code, AMD64_RAX, vt_offset);
126         amd64_ret (code);
127
128         g_assert ((code - start) < buf_len);
129
130         nacl_domain_code_validate (domain, &start, buf_len, &code);
131
132         mono_arch_flush_icache (start, code - start);
133
134         return start;
135 }
136
137 /*
138  * mono_arch_patch_callsite:
139  *
140  *   Patch the callsite whose address is given by ORIG_CODE so it calls ADDR. ORIG_CODE
141  * points to the pc right after the call.
142  */
143 void
144 mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
145 {
146 #if defined(__default_codegen__)
147         guint8 *code;
148         guint8 buf [16];
149         gboolean can_write = mono_breakpoint_clean_code (method_start, orig_code, 14, buf, sizeof (buf));
150
151         code = buf + 14;
152
153         /* mov 64-bit imm into r11 (followed by call reg?)  or direct call*/
154         if (((code [-13] == 0x49) && (code [-12] == 0xbb)) || (code [-5] == 0xe8)) {
155                 if (code [-5] != 0xe8) {
156                         if (can_write) {
157                                 InterlockedExchangePointer ((gpointer*)(orig_code - 11), addr);
158                                 VALGRIND_DISCARD_TRANSLATIONS (orig_code - 11, sizeof (gpointer));
159                         }
160                 } else {
161                         gboolean disp_32bit = ((((gint64)addr - (gint64)orig_code)) < (1 << 30)) && ((((gint64)addr - (gint64)orig_code)) > -(1 << 30));
162
163                         if ((((guint64)(addr)) >> 32) != 0 && !disp_32bit) {
164 #ifdef MONO_ARCH_NOMAP32BIT
165                                 /* Print some diagnostics */
166                                 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), (char*)orig_code);
167                                 if (ji)
168                                         fprintf (stderr, "At %s, offset 0x%zx\n", mono_method_full_name (ji->method, TRUE), (guint8*)orig_code - (guint8*)ji->code_start);
169                                 fprintf (stderr, "Addr: %p\n", addr);
170                                 ji = mono_jit_info_table_find (mono_domain_get (), (char*)addr);
171                                 if (ji)
172                                         fprintf (stderr, "Callee: %s\n", mono_method_full_name (ji->method, TRUE));
173                                 g_assert_not_reached ();
174 #else
175                                 /* 
176                                  * This might happen when calling AOTed code. Create a thunk.
177                                  */
178                                 guint8 *thunk_start, *thunk_code;
179
180                                 thunk_start = thunk_code = mono_domain_code_reserve (mono_domain_get (), 32);
181                                 amd64_jump_membase (thunk_code, AMD64_RIP, 0);
182                                 *(guint64*)thunk_code = (guint64)addr;
183                                 addr = thunk_start;
184                                 g_assert ((((guint64)(addr)) >> 32) == 0);
185                                 mono_arch_flush_icache (thunk_start, thunk_code - thunk_start);
186 #endif
187                         }
188                         if (can_write) {
189                                 InterlockedExchange ((gint32*)(orig_code - 4), ((gint64)addr - (gint64)orig_code));
190                                 VALGRIND_DISCARD_TRANSLATIONS (orig_code - 5, 4);
191                         }
192                 }
193         }
194         else if ((code [-7] == 0x41) && (code [-6] == 0xff) && (code [-5] == 0x15)) {
195                 /* call *<OFFSET>(%rip) */
196                 gpointer *got_entry = (gpointer*)((guint8*)orig_code + (*(guint32*)(orig_code - 4)));
197                 if (can_write) {
198                         InterlockedExchangePointer (got_entry, addr);
199                         VALGRIND_DISCARD_TRANSLATIONS (orig_code - 5, sizeof (gpointer));
200                 }
201         }
202 #elif defined(__native_client__)
203         /* These are essentially the same 2 cases as above, modified for NaCl*/
204
205         /* Target must be bundle-aligned */
206         g_assert (((guint32)addr & kNaClAlignmentMask) == 0);
207         /* Return target must be bundle-aligned */
208         g_assert (((guint32)orig_code & kNaClAlignmentMask) == 0);
209
210         if (orig_code[-5] == 0xe8) {
211                 /* Direct call */
212                 int ret;
213                 gint32 offset = (gint32)addr - (gint32)orig_code;
214                 guint8 buf[sizeof(gint32)];
215                 *((gint32*)(buf)) = offset;
216                 ret = nacl_dyncode_modify (orig_code - sizeof(gint32), buf, sizeof(gint32));
217                 g_assert (ret == 0);
218         }
219
220         else if (is_nacl_call_reg_sequence (orig_code - 10) && orig_code[-16] == 0x41 && orig_code[-15] == 0xbb) {
221                 int ret;
222                 guint8 buf[sizeof(gint32)];
223                 *((gint32 *)(buf)) = addr;
224                 /* orig_code[-14] is the start of the immediate. */
225                 ret = nacl_dyncode_modify (orig_code - 14, buf, sizeof(gint32));
226                 g_assert (ret == 0);
227         }
228         else {
229                 g_assert_not_reached ();
230         }
231
232         return;
233 #endif
234 }
235
236 guint8*
237 mono_arch_create_llvm_native_thunk (MonoDomain *domain, guint8 *addr)
238 {
239         /*
240          * The caller is LLVM code and the call displacement might exceed 32 bits. We can't determine the caller address, so
241          * we add a thunk every time.
242          * Since the caller is also allocated using the domain code manager, hopefully the displacement will fit into 32 bits.
243          * FIXME: Avoid this if possible if !MONO_ARCH_NOMAP32BIT and ADDR is 32 bits.
244          */
245         guint8 *thunk_start, *thunk_code;
246
247         thunk_start = thunk_code = mono_domain_code_reserve (mono_domain_get (), 32);
248         amd64_jump_membase (thunk_code, AMD64_RIP, 0);
249         *(guint64*)thunk_code = (guint64)addr;
250         addr = thunk_start;
251         mono_arch_flush_icache (thunk_start, thunk_code - thunk_start);
252         return addr;
253 }
254
255 void
256 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
257 {
258         gint32 disp;
259         gpointer *plt_jump_table_entry;
260
261 #if defined(__default_codegen__)
262         /* A PLT entry: jmp *<DISP>(%rip) */
263         g_assert (code [0] == 0xff);
264         g_assert (code [1] == 0x25);
265
266         disp = *(gint32*)(code + 2);
267
268         plt_jump_table_entry = (gpointer*)(code + 6 + disp);
269 #elif defined(__native_client_codegen__)
270         /* A PLT entry:            */
271         /* mov <DISP>(%rip), %r11d */
272         /* nacljmp *%r11           */
273
274         /* Verify the 'mov' */
275         g_assert (code [0] == 0x45);
276         g_assert (code [1] == 0x8b);
277         g_assert (code [2] == 0x1d);
278
279         disp = *(gint32*)(code + 3);
280
281         /* 7 = 3 (mov opcode) + 4 (disp) */
282         /* This needs to resolve to the target of the RIP-relative offset */
283         plt_jump_table_entry = (gpointer*)(code + 7 + disp);
284
285 #endif /* __native_client_codegen__ */
286
287
288         InterlockedExchangePointer (plt_jump_table_entry, addr);
289 }
290
291 static gpointer
292 get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
293 {
294         guint8 buf [10];
295         gint32 disp;
296         MonoJitInfo *ji = NULL;
297
298 #ifdef ENABLE_LLVM
299         /* code - 9 might be before the start of the method */
300         /* FIXME: Avoid this expensive call somehow */
301         ji = mono_jit_info_table_find (mono_domain_get (), (char*)code);
302 #endif
303
304         mono_breakpoint_clean_code (ji ? ji->code_start : NULL, code, 9, buf, sizeof (buf));
305         code = buf + 9;
306
307         *displacement = 0;
308
309         code -= 7;
310
311         if ((code [0] == 0x41) && (code [1] == 0xff) && (code [2] == 0x15)) {
312                 /* call OFFSET(%rip) */
313                 g_assert_not_reached ();
314                 *displacement = *(guint32*)(code + 3);
315                 return (gpointer*)(code + disp + 7);
316         } else {
317                 g_assert_not_reached ();
318                 return NULL;
319         }
320 }
321
322 static gpointer*
323 get_vcall_slot_addr (guint8* code, mgreg_t *regs)
324 {
325         gpointer vt;
326         int displacement;
327         vt = get_vcall_slot (code, regs, &displacement);
328         if (!vt)
329                 return NULL;
330         return (gpointer*)((char*)vt + displacement);
331 }
332
333 void
334 mono_arch_nullify_class_init_trampoline (guint8 *code, mgreg_t *regs)
335 {
336         guint8 buf [16];
337         MonoJitInfo *ji = NULL;
338         gboolean can_write;
339
340         if (mono_use_llvm) {
341                 /* code - 7 might be before the start of the method */
342                 /* FIXME: Avoid this expensive call somehow */
343                 ji = mono_jit_info_table_find (mono_domain_get (), (char*)code);
344         }
345
346         can_write = mono_breakpoint_clean_code (ji ? ji->code_start : NULL, code, 7, buf, sizeof (buf));
347
348         if (!can_write)
349                 return;
350
351         /* 
352          * A given byte sequence can match more than case here, so we have to be
353          * really careful about the ordering of the cases. Longer sequences
354          * come first.
355          */
356         if ((buf [0] == 0x41) && (buf [1] == 0xff) && (buf [2] == 0x15)) {
357                 gpointer *vtable_slot;
358
359                 /* call *<OFFSET>(%rip) */
360                 vtable_slot = get_vcall_slot_addr (code, regs);
361                 g_assert (vtable_slot);
362
363                 *vtable_slot = nullified_class_init_trampoline;
364         } else if (buf [2] == 0xe8) {
365                 /* call <TARGET> */
366                 //guint8 *buf = code - 2;
367
368                 /* 
369                  * It would be better to replace the call with nops, but that doesn't seem
370                  * to work on SMP machines even when the whole call is inside a cache line.
371                  * Patching the call address seems to work.
372                  */
373                 /*
374                 buf [0] = 0x66;
375                 buf [1] = 0x66;
376                 buf [2] = 0x90;
377                 buf [3] = 0x66;
378                 buf [4] = 0x90;
379                 */
380
381                 mono_arch_patch_callsite (code - 5, code, nullified_class_init_trampoline);
382         } else if ((buf [5] == 0xff) && x86_modrm_mod (buf [6]) == 3 && x86_modrm_reg (buf [6]) == 2) {
383                 /* call *<reg> */
384                 /* Generated by the LLVM JIT or on platforms without MAP_32BIT set */
385                 mono_arch_patch_callsite (code - 13, code, nullified_class_init_trampoline);
386         } else if (buf [4] == 0x90 || buf [5] == 0xeb || buf [6] == 0x66) {
387                 /* Already changed by another thread */
388                 ;
389         } else {
390                 printf ("Invalid trampoline sequence: %x %x %x %x %x %x %x\n", buf [0], buf [1], buf [2], buf [3],
391                         buf [4], buf [5], buf [6]);
392                 g_assert_not_reached ();
393         }
394 }
395
396 void
397 mono_arch_nullify_plt_entry (guint8 *code, mgreg_t *regs)
398 {
399         if (mono_aot_only && !nullified_class_init_trampoline)
400                 nullified_class_init_trampoline = mono_aot_get_trampoline ("nullified_class_init_trampoline");
401
402         mono_arch_patch_plt_entry (code, NULL, regs, nullified_class_init_trampoline);
403 }
404
405 static void
406 stack_unaligned (MonoTrampolineType tramp_type)
407 {
408         printf ("%d\n", tramp_type);
409         g_assert_not_reached ();
410 }
411
412 guchar*
413 mono_arch_create_generic_trampoline (MonoTrampolineType tramp_type, MonoTrampInfo **info, gboolean aot)
414 {
415         guint8 *buf, *code, *tramp, *br [2], *r11_save_code, *after_r11_save_code;
416         int i, lmf_offset, offset, res_offset, arg_offset, rax_offset, tramp_offset, saved_regs_offset;
417         int saved_fpregs_offset, rbp_offset, framesize, orig_rsp_to_rbp_offset, cfa_offset;
418         gboolean has_caller;
419         GSList *unwind_ops = NULL;
420         MonoJumpInfo *ji = NULL;
421         const guint kMaxCodeSize = NACL_SIZE (600, 600*2);
422
423 #if defined(__native_client_codegen__)
424         const guint kNaClTrampOffset = 17;
425 #endif
426
427         if (tramp_type == MONO_TRAMPOLINE_JUMP || tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
428                 has_caller = FALSE;
429         else
430                 has_caller = TRUE;
431
432         code = buf = mono_global_codeman_reserve (kMaxCodeSize);
433
434         framesize = kMaxCodeSize + sizeof (MonoLMF);
435         framesize = (framesize + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
436
437         orig_rsp_to_rbp_offset = 0;
438         r11_save_code = code;
439         /* Reserve 5 bytes for the mov_membase_reg to save R11 */
440         code += 5;
441         after_r11_save_code = code;
442
443         // CFA = sp + 16 (the trampoline address is on the stack)
444         cfa_offset = 16;
445         mono_add_unwind_op_def_cfa (unwind_ops, code, buf, AMD64_RSP, 16);
446         // IP saved at CFA - 8
447         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RIP, -8);
448
449         /* Pop the return address off the stack */
450         amd64_pop_reg (code, AMD64_R11);
451         orig_rsp_to_rbp_offset += sizeof(mgreg_t);
452
453         cfa_offset -= sizeof(mgreg_t);
454         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
455
456         /* 
457          * Allocate a new stack frame
458          */
459         amd64_push_reg (code, AMD64_RBP);
460         cfa_offset += sizeof(mgreg_t);
461         mono_add_unwind_op_def_cfa_offset (unwind_ops, code, buf, cfa_offset);
462         mono_add_unwind_op_offset (unwind_ops, code, buf, AMD64_RBP, - cfa_offset);
463
464         orig_rsp_to_rbp_offset -= sizeof(mgreg_t);
465         amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
466         mono_add_unwind_op_def_cfa_reg (unwind_ops, code, buf, AMD64_RBP);
467         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, framesize);
468
469         offset = 0;
470         rbp_offset = - offset;
471
472         offset += sizeof(mgreg_t);
473         rax_offset = - offset;
474
475         offset += sizeof(mgreg_t);
476         tramp_offset = - offset;
477
478         offset += sizeof(gpointer);
479         arg_offset = - offset;
480
481         /* Compute the trampoline address from the return address */
482         if (aot) {
483 #if defined(__default_codegen__)
484                 /* 7 = length of call *<offset>(rip) */
485                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 7);
486 #elif defined(__native_client_codegen__)
487                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, kNaClTrampOffset);
488 #endif
489         } else {
490                 /* 5 = length of amd64_call_membase () */
491                 amd64_alu_reg_imm (code, X86_SUB, AMD64_R11, 5);
492         }
493         amd64_mov_membase_reg (code, AMD64_RBP, tramp_offset, AMD64_R11, sizeof(gpointer));
494
495         offset += sizeof(mgreg_t);
496         res_offset = - offset;
497
498         /* Save all registers */
499
500         offset += AMD64_NREG * sizeof(mgreg_t);
501         saved_regs_offset = - offset;
502         for (i = 0; i < AMD64_NREG; ++i) {
503                 if (i == AMD64_RBP) {
504                         /* RAX is already saved */
505                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, rbp_offset, sizeof(mgreg_t));
506                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), AMD64_RAX, sizeof(mgreg_t));
507                 } else if (i != AMD64_R11) {
508                         amd64_mov_membase_reg (code, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
509                 } else {
510                         /* We have to save R11 right at the start of
511                            the trampoline code because it's used as a
512                            scratch register */
513                         amd64_mov_membase_reg (r11_save_code, AMD64_RSP, saved_regs_offset + orig_rsp_to_rbp_offset + (i * sizeof(mgreg_t)), i, sizeof(mgreg_t));
514                         g_assert (r11_save_code == after_r11_save_code);
515                 }
516         }
517         offset += 8 * sizeof(mgreg_t);
518         saved_fpregs_offset = - offset;
519         for (i = 0; i < 8; ++i)
520                 amd64_movsd_membase_reg (code, AMD64_RBP, saved_fpregs_offset + (i * sizeof(mgreg_t)), i);
521
522         /* Check that the stack is aligned */
523 #if defined(__default_codegen__)
524         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RSP, sizeof (mgreg_t));
525         amd64_alu_reg_imm (code, X86_AND, AMD64_R11, 15);
526         amd64_alu_reg_imm (code, X86_CMP, AMD64_R11, 0);
527         br [0] = code;
528         amd64_branch_disp (code, X86_CC_Z, 0, FALSE);
529         if (aot) {
530                 amd64_mov_reg_imm (code, AMD64_R11, 0);
531                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
532         } else {
533                 amd64_mov_reg_imm (code, AMD64_RDI, tramp_type);
534                 amd64_mov_reg_imm (code, AMD64_R11, stack_unaligned);
535                 amd64_call_reg (code, AMD64_R11);
536         }
537         mono_amd64_patch (br [0], code);
538         //amd64_breakpoint (code);
539 #endif
540
541         if (tramp_type != MONO_TRAMPOLINE_GENERIC_CLASS_INIT &&
542                 tramp_type != MONO_TRAMPOLINE_MONITOR_ENTER &&
543                 tramp_type != MONO_TRAMPOLINE_MONITOR_EXIT &&
544                 tramp_type != MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD) {
545                 /* Obtain the trampoline argument which is encoded in the instruction stream */
546                 if (aot) {
547                         /* Load the GOT offset */
548                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, sizeof(gpointer));
549 #if defined(__default_codegen__)
550                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 7, 4);
551 #elif defined(__native_client_codegen__)
552                         /* The arg is hidden in a "push imm32" instruction, */
553                         /* add one to skip the opcode.                      */
554                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, kNaClTrampOffset+1, 4);
555 #endif
556                         /* Compute the address of the GOT slot */
557                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_R11, AMD64_RAX, sizeof(gpointer));
558                         /* Load the value */
559                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, sizeof(gpointer));
560                 } else {                        
561                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, tramp_offset, sizeof(gpointer));
562 #if defined(__default_codegen__)
563                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_R11, 5, 1);
564                         amd64_widen_reg (code, AMD64_RAX, AMD64_RAX, TRUE, FALSE);
565                         amd64_alu_reg_imm_size (code, X86_CMP, AMD64_RAX, 4, 1);
566                         br [0] = code;
567                         x86_branch8 (code, X86_CC_NE, 6, FALSE);
568                         /* 32 bit immediate */
569                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
570                         br [1] = code;
571                         x86_jump8 (code, 10);
572                         /* 64 bit immediate */
573                         mono_amd64_patch (br [0], code);
574                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 8);
575                         mono_amd64_patch (br [1], code);
576 #elif defined(__native_client_codegen__)
577                         /* All args are 32-bit pointers in NaCl */
578                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 6, 4);
579 #endif
580                 }
581                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, sizeof(gpointer));
582         } else {
583                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, saved_regs_offset + (MONO_AMD64_ARG_REG1 * sizeof(mgreg_t)), sizeof(mgreg_t));
584                 amd64_mov_membase_reg (code, AMD64_RBP, arg_offset, AMD64_R11, sizeof(gpointer));
585         }
586
587         /* Save LMF begin */
588
589         offset += sizeof (MonoLMF);
590         lmf_offset = - offset;
591
592         /* Save ip */
593         if (has_caller)
594                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, 8, sizeof(gpointer));
595         else
596                 amd64_mov_reg_imm (code, AMD64_R11, 0);
597         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), AMD64_R11, sizeof(mgreg_t));
598         /* Save fp */
599         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RSP, framesize, sizeof(mgreg_t));
600         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), AMD64_R11, sizeof(mgreg_t));
601         /* Save sp */
602         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RSP, sizeof(mgreg_t));
603         amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, framesize + 16);
604         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_R11, sizeof(mgreg_t));
605         /* Save method */
606         if (tramp_type == MONO_TRAMPOLINE_JIT || tramp_type == MONO_TRAMPOLINE_JUMP) {
607                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, arg_offset, sizeof(gpointer));
608                 amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), AMD64_R11, sizeof(gpointer));
609         } else {
610                 amd64_mov_membase_imm (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), 0, sizeof(gpointer));
611         }
612         /* Save callee saved regs */
613 #ifdef TARGET_WIN32
614         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), AMD64_RDI, sizeof(mgreg_t));
615         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), AMD64_RSI, sizeof(mgreg_t));
616 #endif
617         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), AMD64_RBX, sizeof(mgreg_t));
618         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), AMD64_R12, sizeof(mgreg_t));
619         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), AMD64_R13, sizeof(mgreg_t));
620         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), AMD64_R14, sizeof(mgreg_t));
621         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), AMD64_R15, sizeof(mgreg_t));
622
623         if (aot) {
624                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_get_lmf_addr");
625         } else {
626                 amd64_mov_reg_imm (code, AMD64_R11, mono_get_lmf_addr);
627         }
628         amd64_call_reg (code, AMD64_R11);
629
630         /* Save lmf_addr */
631         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, sizeof(gpointer));
632         /* Save previous_lmf */
633         /* Set the lowest bit to 1 to signal that this LMF has the ip field set */
634         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
635         amd64_alu_reg_imm_size (code, X86_ADD, AMD64_R11, 1, sizeof(gpointer));
636         amd64_mov_membase_reg (code, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
637         /* Set new lmf */
638         amd64_lea_membase (code, AMD64_R11, AMD64_RBP, lmf_offset);
639         amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
640
641         /* Save LMF end */
642
643         /* Arg1 is the pointer to the saved registers */
644         amd64_lea_membase (code, AMD64_ARG_REG1, AMD64_RBP, saved_regs_offset);
645
646         /* Arg2 is the address of the calling code */
647         if (has_caller)
648                 amd64_mov_reg_membase (code, AMD64_ARG_REG2, AMD64_RBP, 8, sizeof(gpointer));
649         else
650                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
651
652         /* Arg3 is the method/vtable ptr */
653         amd64_mov_reg_membase (code, AMD64_ARG_REG3, AMD64_RBP, arg_offset, sizeof(gpointer));
654
655         /* Arg4 is the trampoline address */
656         amd64_mov_reg_membase (code, AMD64_ARG_REG4, AMD64_RBP, tramp_offset, sizeof(gpointer));
657
658         if (aot) {
659                 char *icall_name = g_strdup_printf ("trampoline_func_%d", tramp_type);
660                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, icall_name);
661         } else {
662                 tramp = (guint8*)mono_get_trampoline_func (tramp_type);
663                 amd64_mov_reg_imm (code, AMD64_R11, tramp);
664         }
665         amd64_call_reg (code, AMD64_R11);
666
667         /* Check for thread interruption */
668         /* This is not perf critical code so no need to check the interrupt flag */
669         /* 
670          * Have to call the _force_ variant, since there could be a protected wrapper on the top of the stack.
671          */
672         amd64_mov_membase_reg (code, AMD64_RBP, res_offset, AMD64_RAX, sizeof(mgreg_t));
673         if (aot) {
674                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "mono_thread_force_interruption_checkpoint");
675         } else {
676                 amd64_mov_reg_imm (code, AMD64_R11, (guint8*)mono_thread_force_interruption_checkpoint);
677         }
678         amd64_call_reg (code, AMD64_R11);
679
680         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RBP, res_offset, sizeof(mgreg_t));        
681
682         /* Restore LMF */
683
684         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
685         amd64_alu_reg_imm_size (code, X86_SUB, AMD64_RCX, 1, sizeof(gpointer));
686         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RBP, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof(gpointer));
687         amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, sizeof(gpointer));
688
689         /* 
690          * Save rax to the stack, after the leave instruction, this will become part of
691          * the red zone.
692          */
693         amd64_mov_membase_reg (code, AMD64_RBP, rax_offset, AMD64_RAX, sizeof(mgreg_t));
694
695         /* Restore argument registers, r10 (imt method/rgxtx)
696            and rax (needed for direct calls to C vararg functions). */
697         for (i = 0; i < AMD64_NREG; ++i)
698                 if (AMD64_IS_ARGUMENT_REG (i) || i == AMD64_R10 || i == AMD64_RAX)
699                         amd64_mov_reg_membase (code, i, AMD64_RBP, saved_regs_offset + (i * sizeof(mgreg_t)), sizeof(mgreg_t));
700
701         for (i = 0; i < 8; ++i)
702                 amd64_movsd_reg_membase (code, i, AMD64_RBP, saved_fpregs_offset + (i * sizeof(mgreg_t)));
703
704         /* Restore stack */
705         amd64_leave (code);
706
707         if (MONO_TRAMPOLINE_TYPE_MUST_RETURN (tramp_type)) {
708                 /* Load result */
709                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, rax_offset - sizeof(mgreg_t), sizeof(mgreg_t));
710                 amd64_ret (code);
711         } else {
712                 /* call the compiled method using the saved rax */
713                 amd64_jump_membase (code, AMD64_RSP, rax_offset - sizeof(mgreg_t));
714         }
715
716         g_assert ((code - buf) <= kMaxCodeSize);
717
718         nacl_global_codeman_validate (&buf, kMaxCodeSize, &code);
719
720         mono_arch_flush_icache (buf, code - buf);
721
722         if (tramp_type == MONO_TRAMPOLINE_CLASS_INIT) {
723                 /* Initialize the nullified class init trampoline used in the AOT case */
724                 nullified_class_init_trampoline = mono_arch_get_nullified_class_init_trampoline (NULL);
725         }
726
727         if (info)
728                 *info = mono_tramp_info_create (mono_get_generic_trampoline_name (tramp_type), buf, code - buf, ji, unwind_ops);
729
730         return buf;
731 }
732
733 gpointer
734 mono_arch_get_nullified_class_init_trampoline (MonoTrampInfo **info)
735 {
736         guint8 *code, *buf;
737         int size = NACL_SIZE (16, 32);
738
739         code = buf = mono_global_codeman_reserve (size);
740         amd64_ret (code);
741
742         nacl_global_codeman_validate(&buf, size, &code);
743
744         mono_arch_flush_icache (buf, code - buf);
745
746         if (info)
747                 *info = mono_tramp_info_create ("nullified_class_init_trampoline", buf, code - buf, NULL, NULL);
748
749         if (mono_jit_map_is_enabled ())
750                 mono_emit_jit_tramp (buf, code - buf, "nullified_class_init_trampoline");
751
752         return buf;
753 }
754
755 gpointer
756 mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len)
757 {
758         guint8 *code, *buf, *tramp;
759         int size;
760         gboolean far_addr = FALSE;
761
762         tramp = mono_get_trampoline_code (tramp_type);
763
764 #if defined(__default_codegen__)
765         if ((((guint64)arg1) >> 32) == 0)
766                 size = 5 + 1 + 4;
767         else
768                 size = 5 + 1 + 8;
769
770         code = buf = mono_domain_code_reserve_align (domain, size, 1);
771
772         if (((gint64)tramp - (gint64)code) >> 31 != 0 && ((gint64)tramp - (gint64)code) >> 31 != -1) {
773 #ifndef MONO_ARCH_NOMAP32BIT
774                 g_assert_not_reached ();
775 #endif
776                 far_addr = TRUE;
777                 size += 16;
778                 code = buf = mono_domain_code_reserve_align (domain, size, 1);
779         }
780 #elif defined(__native_client_codegen__)
781         size = 5 + 1 + 4;
782         /* Aligning the call site below could */
783         /* add up to kNaClAlignment-1 bytes   */
784         size += (kNaClAlignment-1);
785         size = NACL_BUNDLE_ALIGN_UP (size);
786         buf = mono_domain_code_reserve_align (domain, size, kNaClAlignment);
787         code = buf;
788 #endif
789
790         if (far_addr) {
791                 amd64_mov_reg_imm (code, AMD64_R11, tramp);
792                 amd64_call_reg (code, AMD64_R11);
793         } else {
794                 amd64_call_code (code, tramp);
795         }
796         /* The trampoline code will obtain the argument from the instruction stream */
797 #if defined(__default_codegen__)
798         if ((((guint64)arg1) >> 32) == 0) {
799                 *code = 0x4;
800                 *(guint32*)(code + 1) = (gint64)arg1;
801                 code += 5;
802         } else {
803                 *code = 0x8;
804                 *(guint64*)(code + 1) = (gint64)arg1;
805                 code += 9;
806         }
807 #elif defined(__native_client_codegen__)
808         /* For NaCl, all tramp args are 32-bit because they're pointers */
809         *code = 0x68; /* push imm32 */
810         *(guint32*)(code + 1) = (gint32)arg1;
811         code += 5;
812 #endif
813
814         g_assert ((code - buf) <= size);
815
816         if (code_len)
817                 *code_len = size;
818
819         nacl_domain_code_validate(domain, &buf, size, &code);
820
821         mono_arch_flush_icache (buf, size);
822
823         return buf;
824 }       
825
826 gpointer
827 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 slot, MonoTrampInfo **info, gboolean aot)
828 {
829         guint8 *tramp;
830         guint8 *code, *buf;
831         guint8 **rgctx_null_jumps;
832         int tramp_size;
833         int depth, index;
834         int i;
835         gboolean mrgctx;
836         MonoJumpInfo *ji = NULL;
837         GSList *unwind_ops = NULL;
838
839         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
840         index = MONO_RGCTX_SLOT_INDEX (slot);
841         if (mrgctx)
842                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
843         for (depth = 0; ; ++depth) {
844                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
845
846                 if (index < size - 1)
847                         break;
848                 index -= size - 1;
849         }
850
851         tramp_size = NACL_SIZE (64 + 8 * depth, 128 + 8 * depth);
852
853         code = buf = mono_global_codeman_reserve (tramp_size);
854
855         unwind_ops = mono_arch_get_cie_program ();
856
857         rgctx_null_jumps = g_malloc (sizeof (guint8*) * (depth + 2));
858
859         if (mrgctx) {
860                 /* get mrgctx ptr */
861                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
862         } else {
863                 /* load rgctx ptr from vtable */
864                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context), sizeof(gpointer));
865                 /* is the rgctx ptr null? */
866                 amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
867                 /* if yes, jump to actual trampoline */
868                 rgctx_null_jumps [0] = code;
869                 amd64_branch8 (code, X86_CC_Z, -1, 1);
870         }
871
872         for (i = 0; i < depth; ++i) {
873                 /* load ptr to next array */
874                 if (mrgctx && i == 0)
875                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT, sizeof(gpointer));
876                 else
877                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, 0, sizeof(gpointer));
878                 /* is the ptr null? */
879                 amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
880                 /* if yes, jump to actual trampoline */
881                 rgctx_null_jumps [i + 1] = code;
882                 amd64_branch8 (code, X86_CC_Z, -1, 1);
883         }
884
885         /* fetch slot */
886         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RAX, sizeof (gpointer) * (index + 1), sizeof(gpointer));
887         /* is the slot null? */
888         amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
889         /* if yes, jump to actual trampoline */
890         rgctx_null_jumps [depth + 1] = code;
891         amd64_branch8 (code, X86_CC_Z, -1, 1);
892         /* otherwise return */
893         amd64_ret (code);
894
895         for (i = mrgctx ? 1 : 0; i <= depth + 1; ++i)
896                 mono_amd64_patch (rgctx_null_jumps [i], code);
897
898         g_free (rgctx_null_jumps);
899
900         /* move the rgctx pointer to the VTABLE register */
901         amd64_mov_reg_reg (code, MONO_ARCH_VTABLE_REG, AMD64_ARG_REG1, sizeof(gpointer));
902
903         if (aot) {
904                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, g_strdup_printf ("specific_trampoline_lazy_fetch_%u", slot));
905                 amd64_jump_reg (code, AMD64_R11);
906         } else {
907                 tramp = mono_arch_create_specific_trampoline (GUINT_TO_POINTER (slot), MONO_TRAMPOLINE_RGCTX_LAZY_FETCH, mono_get_root_domain (), NULL);
908
909                 /* jump to the actual trampoline */
910                 amd64_jump_code (code, tramp);
911         }
912
913         nacl_global_codeman_validate (&buf, tramp_size, &code);
914         mono_arch_flush_icache (buf, code - buf);
915
916         g_assert (code - buf <= tramp_size);
917
918         if (info) {
919                 char *name = mono_get_rgctx_fetch_trampoline_name (slot);
920                 *info = mono_tramp_info_create (name, buf, code - buf, ji, unwind_ops);
921                 g_free (name);
922         }
923
924         return buf;
925 }
926
927 gpointer
928 mono_arch_create_generic_class_init_trampoline (MonoTrampInfo **info, gboolean aot)
929 {
930         guint8 *tramp;
931         guint8 *code, *buf;
932         static int byte_offset = -1;
933         static guint8 bitmask;
934         guint8 *jump;
935         int tramp_size;
936         GSList *unwind_ops = NULL;
937         MonoJumpInfo *ji = NULL;
938
939         tramp_size = 64;
940
941         code = buf = mono_global_codeman_reserve (tramp_size);
942
943         if (byte_offset < 0)
944                 mono_marshal_find_bitfield_offset (MonoVTable, initialized, &byte_offset, &bitmask);
945
946         amd64_test_membase_imm_size (code, MONO_AMD64_ARG_REG1, byte_offset, bitmask, 1);
947         jump = code;
948         amd64_branch8 (code, X86_CC_Z, -1, 1);
949
950         amd64_ret (code);
951
952         x86_patch (jump, code);
953
954         if (aot) {
955                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_generic_class_init");
956                 amd64_jump_reg (code, AMD64_R11);
957         } else {
958                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_GENERIC_CLASS_INIT, mono_get_root_domain (), NULL);
959
960                 /* jump to the actual trampoline */
961                 amd64_jump_code (code, tramp);
962         }
963
964         nacl_global_codeman_validate (&buf, tramp_size, &code);
965
966         mono_arch_flush_icache (buf, code - buf);
967
968         g_assert (code - buf <= tramp_size);
969
970         if (info)
971                 *info = mono_tramp_info_create ("generic_class_init_trampoline", buf, code - buf, ji, unwind_ops);
972
973         return buf;
974 }
975
976 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
977
978 gpointer
979 mono_arch_create_monitor_enter_trampoline (MonoTrampInfo **info, gboolean aot)
980 {
981         guint8 *tramp;
982         guint8 *code, *buf;
983         guint8 *jump_obj_null, *jump_sync_null, *jump_cmpxchg_failed, *jump_other_owner, *jump_tid, *jump_sync_thin_hash = NULL;
984         int tramp_size;
985         int owner_offset, nest_offset, dummy;
986         MonoJumpInfo *ji = NULL;
987         GSList *unwind_ops = NULL;
988
989         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == AMD64_RDI);
990
991         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &dummy);
992         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
993         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
994         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
995         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
996
997         tramp_size = 96;
998
999         code = buf = mono_global_codeman_reserve (tramp_size);
1000
1001         unwind_ops = mono_arch_get_cie_program ();
1002
1003         if (mono_thread_get_tls_offset () != -1) {
1004                 /* MonoObject* obj is in RDI */
1005                 /* is obj null? */
1006                 amd64_test_reg_reg (code, AMD64_RDI, AMD64_RDI);
1007                 /* if yes, jump to actual trampoline */
1008                 jump_obj_null = code;
1009                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1010
1011                 /* load obj->synchronization to RCX */
1012                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RDI, G_STRUCT_OFFSET (MonoObject, synchronisation), 8);
1013
1014                 if (mono_gc_is_moving ()) {
1015                         /*if bit zero is set it's a thin hash*/
1016                         /*FIXME use testb encoding*/
1017                         amd64_test_reg_imm (code, AMD64_RCX, 0x01);
1018                         jump_sync_thin_hash = code;
1019                         amd64_branch8 (code, X86_CC_NE, -1, 1);
1020
1021                         /*clear bits used by the gc*/
1022                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, ~0x3);
1023                 }
1024
1025                 /* is synchronization null? */
1026                 amd64_test_reg_reg (code, AMD64_RCX, AMD64_RCX);
1027                 /* if yes, jump to actual trampoline */
1028                 jump_sync_null = code;
1029                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1030
1031                 /* load MonoInternalThread* into RDX */
1032                 code = mono_amd64_emit_tls_get (code, AMD64_RDX, mono_thread_get_tls_offset ());
1033                 /* load TID into RDX */
1034                 amd64_mov_reg_membase (code, AMD64_RDX, AMD64_RDX, G_STRUCT_OFFSET (MonoInternalThread, tid), 8);
1035
1036                 /* is synchronization->owner null? */
1037                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_RCX, owner_offset, 0, 8);
1038                 /* if not, jump to next case */
1039                 jump_tid = code;
1040                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1041
1042                 /* if yes, try a compare-exchange with the TID */
1043                 /* zero RAX */
1044                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
1045                 /* compare and exchange */
1046                 amd64_prefix (code, X86_LOCK_PREFIX);
1047                 amd64_cmpxchg_membase_reg_size (code, AMD64_RCX, owner_offset, AMD64_RDX, 8);
1048                 /* if not successful, jump to actual trampoline */
1049                 jump_cmpxchg_failed = code;
1050                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1051                 /* if successful, return */
1052                 amd64_ret (code);
1053
1054                 /* next case: synchronization->owner is not null */
1055                 x86_patch (jump_tid, code);
1056                 /* is synchronization->owner == TID? */
1057                 amd64_alu_membase_reg_size (code, X86_CMP, AMD64_RCX, owner_offset, AMD64_RDX, 8);
1058                 /* if not, jump to actual trampoline */
1059                 jump_other_owner = code;
1060                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1061                 /* if yes, increment nest */
1062                 amd64_inc_membase_size (code, AMD64_RCX, nest_offset, 4);
1063                 /* return */
1064                 amd64_ret (code);
1065
1066                 x86_patch (jump_obj_null, code);
1067                 if (jump_sync_thin_hash)
1068                         x86_patch (jump_sync_thin_hash, code);
1069                 x86_patch (jump_sync_null, code);
1070                 x86_patch (jump_cmpxchg_failed, code);
1071                 x86_patch (jump_other_owner, code);
1072         }
1073
1074         /* jump to the actual trampoline */
1075 #if MONO_AMD64_ARG_REG1 != AMD64_RDI
1076         amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, AMD64_RDI);
1077 #endif
1078
1079         if (aot) {
1080                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_enter");
1081                 amd64_jump_reg (code, AMD64_R11);
1082         } else {
1083                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_ENTER, mono_get_root_domain (), NULL);
1084
1085                 /* jump to the actual trampoline */
1086                 amd64_jump_code (code, tramp);
1087         }
1088
1089         nacl_global_codeman_validate (&buf, tramp_size, &code);
1090
1091         mono_arch_flush_icache (code, code - buf);
1092         g_assert (code - buf <= tramp_size);
1093
1094         if (info)
1095                 *info = mono_tramp_info_create ("monitor_enter_trampoline", buf, code - buf, ji, unwind_ops);
1096
1097         return buf;
1098 }
1099
1100 gpointer
1101 mono_arch_create_monitor_exit_trampoline (MonoTrampInfo **info, gboolean aot)
1102 {
1103         guint8 *tramp;
1104         guint8 *code, *buf;
1105         guint8 *jump_obj_null, *jump_have_waiters, *jump_sync_null, *jump_not_owned, *jump_sync_thin_hash = NULL;
1106         guint8 *jump_next;
1107         int tramp_size;
1108         int owner_offset, nest_offset, entry_count_offset;
1109         MonoJumpInfo *ji = NULL;
1110         GSList *unwind_ops = NULL;
1111
1112         g_assert (MONO_ARCH_MONITOR_OBJECT_REG == AMD64_RDI);
1113
1114         mono_monitor_threads_sync_members_offset (&owner_offset, &nest_offset, &entry_count_offset);
1115         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (owner_offset) == sizeof (gpointer));
1116         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (nest_offset) == sizeof (guint32));
1117         g_assert (MONO_THREADS_SYNC_MEMBER_SIZE (entry_count_offset) == sizeof (gint32));
1118         owner_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (owner_offset);
1119         nest_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (nest_offset);
1120         entry_count_offset = MONO_THREADS_SYNC_MEMBER_OFFSET (entry_count_offset);
1121
1122         tramp_size = 112;
1123
1124         code = buf = mono_global_codeman_reserve (tramp_size);
1125
1126         unwind_ops = mono_arch_get_cie_program ();
1127
1128         if (mono_thread_get_tls_offset () != -1) {
1129                 /* MonoObject* obj is in RDI */
1130                 /* is obj null? */
1131                 amd64_test_reg_reg (code, AMD64_RDI, AMD64_RDI);
1132                 /* if yes, jump to actual trampoline */
1133                 jump_obj_null = code;
1134                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1135
1136                 /* load obj->synchronization to RCX */
1137                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RDI, G_STRUCT_OFFSET (MonoObject, synchronisation), 8);
1138
1139                 if (mono_gc_is_moving ()) {
1140                         /*if bit zero is set it's a thin hash*/
1141                         /*FIXME use testb encoding*/
1142                         amd64_test_reg_imm (code, AMD64_RCX, 0x01);
1143                         jump_sync_thin_hash = code;
1144                         amd64_branch8 (code, X86_CC_NE, -1, 1);
1145
1146                         /*clear bits used by the gc*/
1147                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, ~0x3);
1148                 }
1149
1150                 /* is synchronization null? */
1151                 amd64_test_reg_reg (code, AMD64_RCX, AMD64_RCX);
1152                 /* if yes, jump to actual trampoline */
1153                 jump_sync_null = code;
1154                 amd64_branch8 (code, X86_CC_Z, -1, 1);
1155
1156                 /* next case: synchronization is not null */
1157                 /* load MonoInternalThread* into RDX */
1158                 code = mono_amd64_emit_tls_get (code, AMD64_RDX, mono_thread_get_tls_offset ());
1159                 /* load TID into RDX */
1160                 amd64_mov_reg_membase (code, AMD64_RDX, AMD64_RDX, G_STRUCT_OFFSET (MonoInternalThread, tid), 8);
1161                 /* is synchronization->owner == TID */
1162                 amd64_alu_membase_reg_size (code, X86_CMP, AMD64_RCX, owner_offset, AMD64_RDX, 8);
1163                 /* if no, jump to actual trampoline */
1164                 jump_not_owned = code;
1165                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1166
1167                 /* next case: synchronization->owner == TID */
1168                 /* is synchronization->nest == 1 */
1169                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_RCX, nest_offset, 1, 4);
1170                 /* if not, jump to next case */
1171                 jump_next = code;
1172                 amd64_branch8 (code, X86_CC_NZ, -1, 1);
1173                 /* if yes, is synchronization->entry_count zero? */
1174                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_RCX, entry_count_offset, 0, 4);
1175                 /* if not, jump to actual trampoline */
1176                 jump_have_waiters = code;
1177                 amd64_branch8 (code, X86_CC_NZ, -1 , 1);
1178                 /* if yes, set synchronization->owner to null and return */
1179                 amd64_mov_membase_imm (code, AMD64_RCX, owner_offset, 0, 8);
1180                 amd64_ret (code);
1181
1182                 /* next case: synchronization->nest is not 1 */
1183                 x86_patch (jump_next, code);
1184                 /* decrease synchronization->nest and return */
1185                 amd64_dec_membase_size (code, AMD64_RCX, nest_offset, 4);
1186                 amd64_ret (code);
1187
1188                 x86_patch (jump_obj_null, code);
1189                 x86_patch (jump_have_waiters, code);
1190                 x86_patch (jump_not_owned, code);
1191                 x86_patch (jump_sync_null, code);
1192         }
1193
1194         /* jump to the actual trampoline */
1195 #if MONO_AMD64_ARG_REG1 != AMD64_RDI
1196         amd64_mov_reg_reg (code, MONO_AMD64_ARG_REG1, AMD64_RDI);
1197 #endif
1198
1199         if (aot) {
1200                 code = mono_arch_emit_load_aotconst (buf, code, &ji, MONO_PATCH_INFO_JIT_ICALL_ADDR, "specific_trampoline_monitor_exit");
1201                 amd64_jump_reg (code, AMD64_R11);
1202         } else {
1203                 tramp = mono_arch_create_specific_trampoline (NULL, MONO_TRAMPOLINE_MONITOR_EXIT, mono_get_root_domain (), NULL);
1204                 amd64_jump_code (code, tramp);
1205         }
1206
1207         nacl_global_codeman_validate (&buf, tramp_size, &code);
1208
1209         mono_arch_flush_icache (code, code - buf);
1210         g_assert (code - buf <= tramp_size);
1211
1212         if (info)
1213                 *info = mono_tramp_info_create ("monitor_exit_trampoline", buf, code - buf, ji, unwind_ops);
1214
1215         return buf;
1216 }
1217 #endif
1218
1219 void
1220 mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
1221 {
1222         /* FIXME: This is not thread safe */
1223         guint8 *code = ji->code_start;
1224
1225         amd64_mov_reg_imm (code, AMD64_ARG_REG1, func_arg);
1226         amd64_mov_reg_imm (code, AMD64_R11, func);
1227
1228         x86_push_imm (code, (guint64)func_arg);
1229         amd64_call_reg (code, AMD64_R11);
1230 }
1231
1232
1233 static void
1234 handler_block_trampoline_helper (gpointer *ptr)
1235 {
1236         MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
1237         *ptr = jit_tls->handler_block_return_address;
1238 }
1239
1240 gpointer
1241 mono_arch_create_handler_block_trampoline (void)
1242 {
1243         guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
1244         guint8 *code, *buf;
1245         int tramp_size = 64;
1246         code = buf = mono_global_codeman_reserve (tramp_size);
1247
1248         /*
1249         This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
1250         */
1251
1252         if (mono_get_jit_tls_offset () != -1) {
1253                 code = mono_amd64_emit_tls_get (code, AMD64_RDI, mono_get_jit_tls_offset ());
1254                 amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RDI, G_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 8);
1255                 /* Simulate a call */
1256                 amd64_push_reg (code, AMD64_RAX);
1257                 amd64_jump_code (code, tramp);
1258         } else {
1259                 /*Slow path uses a c helper*/
1260                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RSP, 8);
1261                 amd64_mov_reg_imm (code, AMD64_RAX, tramp);
1262                 amd64_push_reg (code, AMD64_RAX);
1263                 amd64_jump_code (code, handler_block_trampoline_helper);
1264         }
1265
1266         mono_arch_flush_icache (buf, code - buf);
1267         g_assert (code - buf <= tramp_size);
1268
1269         if (mono_jit_map_is_enabled ())
1270                 mono_emit_jit_tramp (buf, code - buf, "handler_block_trampoline");
1271
1272         return buf;
1273 }
1274
1275 /*
1276  * mono_arch_get_call_target:
1277  *
1278  *   Return the address called by the code before CODE if exists.
1279  */
1280 guint8*
1281 mono_arch_get_call_target (guint8 *code)
1282 {
1283         if (code [-5] == 0xe8) {
1284                 guint32 disp = *(guint32*)(code - 4);
1285                 guint8 *target = code + disp;
1286
1287                 return target;
1288         } else {
1289                 return NULL;
1290         }
1291 }
1292
1293 /*
1294  * mono_arch_get_plt_info_offset:
1295  *
1296  *   Return the PLT info offset belonging to the plt entry PLT_ENTRY.
1297  */
1298 guint32
1299 mono_arch_get_plt_info_offset (guint8 *plt_entry, mgreg_t *regs, guint8 *code)
1300 {
1301 #if defined(__native_client__) || defined(__native_client_codegen__)
1302         /* 18 = 3 (mov opcode) + 4 (disp) + 10 (nacljmp) + 1 (push opcode) */
1303         /* See aot-compiler.c arch_emit_plt_entry for details.             */
1304         return *(guint32*)(plt_entry + 18);
1305 #else
1306         return *(guint32*)(plt_entry + 6);
1307 #endif
1308 }