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