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