[jit] Add support for generating the push/pop the LMF from the LMF stack as IR instea...
[mono.git] / mono / mini / mini-amd64.c
1 /*
2  * mini-amd64.c: AMD64 backend for the Mono code generator
3  *
4  * Based on mini-x86.c.
5  *
6  * Authors:
7  *   Paolo Molaro (lupus@ximian.com)
8  *   Dietmar Maurer (dietmar@ximian.com)
9  *   Patrik Torstensson
10  *   Zoltan Varga (vargaz@gmail.com)
11  *
12  * (C) 2003 Ximian, Inc.
13  * Copyright 2003-2011 Novell, Inc (http://www.novell.com)
14  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
15  */
16 #include "mini.h"
17 #include <string.h>
18 #include <math.h>
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
22
23 #include <mono/metadata/appdomain.h>
24 #include <mono/metadata/debug-helpers.h>
25 #include <mono/metadata/threads.h>
26 #include <mono/metadata/profiler-private.h>
27 #include <mono/metadata/mono-debug.h>
28 #include <mono/metadata/gc-internal.h>
29 #include <mono/utils/mono-math.h>
30 #include <mono/utils/mono-mmap.h>
31 #include <mono/utils/mono-memory-model.h>
32 #include <mono/utils/mono-tls.h>
33 #include <mono/utils/mono-hwcap-x86.h>
34
35 #include "trace.h"
36 #include "ir-emit.h"
37 #include "mini-amd64.h"
38 #include "cpu-amd64.h"
39 #include "debugger-agent.h"
40 #include "mini-gc.h"
41
42 static gint lmf_tls_offset = -1;
43 static gint lmf_addr_tls_offset = -1;
44 static gint appdomain_tls_offset = -1;
45
46 #ifdef MONO_XEN_OPT
47 static gboolean optimize_for_xen = TRUE;
48 #else
49 #define optimize_for_xen 0
50 #endif
51
52 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
53
54 #define IS_IMM32(val) ((((guint64)val) >> 32) == 0)
55
56 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
57
58 #ifdef HOST_WIN32
59 /* Under windows, the calling convention is never stdcall */
60 #define CALLCONV_IS_STDCALL(call_conv) (FALSE)
61 #else
62 #define CALLCONV_IS_STDCALL(call_conv) ((call_conv) == MONO_CALL_STDCALL)
63 #endif
64
65 /* This mutex protects architecture specific caches */
66 #define mono_mini_arch_lock() EnterCriticalSection (&mini_arch_mutex)
67 #define mono_mini_arch_unlock() LeaveCriticalSection (&mini_arch_mutex)
68 static CRITICAL_SECTION mini_arch_mutex;
69
70 MonoBreakpointInfo
71 mono_breakpoint_info [MONO_BREAKPOINT_ARRAY_SIZE];
72
73 /* Structure used by the sequence points in AOTed code */
74 typedef struct {
75         gpointer ss_trigger_page;
76         gpointer bp_trigger_page;
77         gpointer bp_addrs [MONO_ZERO_LEN_ARRAY];
78 } SeqPointInfo;
79
80 /*
81  * The code generated for sequence points reads from this location, which is
82  * made read-only when single stepping is enabled.
83  */
84 static gpointer ss_trigger_page;
85
86 /* Enabled breakpoints read from this trigger page */
87 static gpointer bp_trigger_page;
88
89 /* The size of the breakpoint sequence */
90 static int breakpoint_size;
91
92 /* The size of the breakpoint instruction causing the actual fault */
93 static int breakpoint_fault_size;
94
95 /* The size of the single step instruction causing the actual fault */
96 static int single_step_fault_size;
97
98 #ifdef HOST_WIN32
99 /* On Win64 always reserve first 32 bytes for first four arguments */
100 #define ARGS_OFFSET 48
101 #else
102 #define ARGS_OFFSET 16
103 #endif
104 #define GP_SCRATCH_REG AMD64_R11
105
106 /*
107  * AMD64 register usage:
108  * - callee saved registers are used for global register allocation
109  * - %r11 is used for materializing 64 bit constants in opcodes
110  * - the rest is used for local allocation
111  */
112
113 /*
114  * Floating point comparison results:
115  *                  ZF PF CF
116  * A > B            0  0  0
117  * A < B            0  0  1
118  * A = B            1  0  0
119  * A > B            0  0  0
120  * UNORDERED        1  1  1
121  */
122
123 const char*
124 mono_arch_regname (int reg)
125 {
126         switch (reg) {
127         case AMD64_RAX: return "%rax";
128         case AMD64_RBX: return "%rbx";
129         case AMD64_RCX: return "%rcx";
130         case AMD64_RDX: return "%rdx";
131         case AMD64_RSP: return "%rsp";  
132         case AMD64_RBP: return "%rbp";
133         case AMD64_RDI: return "%rdi";
134         case AMD64_RSI: return "%rsi";
135         case AMD64_R8: return "%r8";
136         case AMD64_R9: return "%r9";
137         case AMD64_R10: return "%r10";
138         case AMD64_R11: return "%r11";
139         case AMD64_R12: return "%r12";
140         case AMD64_R13: return "%r13";
141         case AMD64_R14: return "%r14";
142         case AMD64_R15: return "%r15";
143         }
144         return "unknown";
145 }
146
147 static const char * packed_xmmregs [] = {
148         "p:xmm0", "p:xmm1", "p:xmm2", "p:xmm3", "p:xmm4", "p:xmm5", "p:xmm6", "p:xmm7", "p:xmm8",
149         "p:xmm9", "p:xmm10", "p:xmm11", "p:xmm12", "p:xmm13", "p:xmm14", "p:xmm15"
150 };
151
152 static const char * single_xmmregs [] = {
153         "s:xmm0", "s:xmm1", "s:xmm2", "s:xmm3", "s:xmm4", "s:xmm5", "s:xmm6", "s:xmm7", "s:xmm8",
154         "s:xmm9", "s:xmm10", "s:xmm11", "s:xmm12", "s:xmm13", "s:xmm14", "s:xmm15"
155 };
156
157 const char*
158 mono_arch_fregname (int reg)
159 {
160         if (reg < AMD64_XMM_NREG)
161                 return single_xmmregs [reg];
162         else
163                 return "unknown";
164 }
165
166 const char *
167 mono_arch_xregname (int reg)
168 {
169         if (reg < AMD64_XMM_NREG)
170                 return packed_xmmregs [reg];
171         else
172                 return "unknown";
173 }
174
175 static gboolean
176 debug_omit_fp (void)
177 {
178 #if 0
179         return mono_debug_count ();
180 #else
181         return TRUE;
182 #endif
183 }
184
185 static inline gboolean
186 amd64_is_near_call (guint8 *code)
187 {
188         /* Skip REX */
189         if ((code [0] >= 0x40) && (code [0] <= 0x4f))
190                 code += 1;
191
192         return code [0] == 0xe8;
193 }
194
195 #ifdef __native_client_codegen__
196
197 /* Keep track of instruction "depth", that is, the level of sub-instruction */
198 /* for any given instruction.  For instance, amd64_call_reg resolves to     */
199 /* amd64_call_reg_internal, which uses amd64_alu_* macros, etc.             */
200 /* We only want to force bundle alignment for the top level instruction,    */
201 /* so NaCl pseudo-instructions can be implemented with sub instructions.    */
202 static MonoNativeTlsKey nacl_instruction_depth;
203
204 static MonoNativeTlsKey nacl_rex_tag;
205 static MonoNativeTlsKey nacl_legacy_prefix_tag;
206
207 void
208 amd64_nacl_clear_legacy_prefix_tag ()
209 {
210         mono_native_tls_set_value (nacl_legacy_prefix_tag, NULL);
211 }
212
213 void
214 amd64_nacl_tag_legacy_prefix (guint8* code)
215 {
216         if (mono_native_tls_get_value (nacl_legacy_prefix_tag) == NULL)
217                 mono_native_tls_set_value (nacl_legacy_prefix_tag, code);
218 }
219
220 void
221 amd64_nacl_tag_rex (guint8* code)
222 {
223         mono_native_tls_set_value (nacl_rex_tag, code);
224 }
225
226 guint8*
227 amd64_nacl_get_legacy_prefix_tag ()
228 {
229         return (guint8*)mono_native_tls_get_value (nacl_legacy_prefix_tag);
230 }
231
232 guint8*
233 amd64_nacl_get_rex_tag ()
234 {
235         return (guint8*)mono_native_tls_get_value (nacl_rex_tag);
236 }
237
238 /* Increment the instruction "depth" described above */
239 void
240 amd64_nacl_instruction_pre ()
241 {
242         intptr_t depth = (intptr_t) mono_native_tls_get_value (nacl_instruction_depth);
243         depth++;
244         mono_native_tls_set_value (nacl_instruction_depth, (gpointer)depth);
245 }
246
247 /* amd64_nacl_instruction_post: Decrement instruction "depth", force bundle */
248 /* alignment if depth == 0 (top level instruction)                          */
249 /* IN: start, end    pointers to instruction beginning and end              */
250 /* OUT: start, end   pointers to beginning and end after possible alignment */
251 /* GLOBALS: nacl_instruction_depth     defined above                        */
252 void
253 amd64_nacl_instruction_post (guint8 **start, guint8 **end)
254 {
255         intptr_t depth = (intptr_t) mono_native_tls_get_value (nacl_instruction_depth);
256         depth--;
257         mono_native_tls_set_value (nacl_instruction_depth, (void*)depth);
258
259         g_assert ( depth >= 0 );
260         if (depth == 0) {
261                 uintptr_t space_in_block;
262                 uintptr_t instlen;
263                 guint8 *prefix = amd64_nacl_get_legacy_prefix_tag ();
264                 /* if legacy prefix is present, and if it was emitted before */
265                 /* the start of the instruction sequence, adjust the start   */
266                 if (prefix != NULL && prefix < *start) {
267                         g_assert (*start - prefix <= 3);/* only 3 are allowed */
268                         *start = prefix;
269                 }
270                 space_in_block = kNaClAlignment - ((uintptr_t)(*start) & kNaClAlignmentMask);
271                 instlen = (uintptr_t)(*end - *start);
272                 /* Only check for instructions which are less than        */
273                 /* kNaClAlignment. The only instructions that should ever */
274                 /* be that long are call sequences, which are already     */
275                 /* padded out to align the return to the next bundle.     */
276                 if (instlen > space_in_block && instlen < kNaClAlignment) {
277                         const size_t MAX_NACL_INST_LENGTH = kNaClAlignment;
278                         guint8 copy_of_instruction[MAX_NACL_INST_LENGTH];
279                         const size_t length = (size_t)((*end)-(*start));
280                         g_assert (length < MAX_NACL_INST_LENGTH);
281                         
282                         memcpy (copy_of_instruction, *start, length);
283                         *start = mono_arch_nacl_pad (*start, space_in_block);
284                         memcpy (*start, copy_of_instruction, length);
285                         *end = *start + length;
286                 }
287                 amd64_nacl_clear_legacy_prefix_tag ();
288                 amd64_nacl_tag_rex (NULL);
289         }
290 }
291
292 /* amd64_nacl_membase_handler: ensure all access to memory of the form      */
293 /*   OFFSET(%rXX) is sandboxed.  For allowable base registers %rip, %rbp,   */
294 /*   %rsp, and %r15, emit the membase as usual.  For all other registers,   */
295 /*   make sure the upper 32-bits are cleared, and use that register in the  */
296 /*   index field of a new address of this form: OFFSET(%r15,%eXX,1)         */
297 /* IN:      code                                                            */
298 /*             pointer to current instruction stream (in the                */
299 /*             middle of an instruction, after opcode is emitted)           */
300 /*          basereg/offset/dreg                                             */
301 /*             operands of normal membase address                           */
302 /* OUT:     code                                                            */
303 /*             pointer to the end of the membase/memindex emit              */
304 /* GLOBALS: nacl_rex_tag                                                    */
305 /*             position in instruction stream that rex prefix was emitted   */
306 /*          nacl_legacy_prefix_tag                                          */
307 /*             (possibly NULL) position in instruction of legacy x86 prefix */
308 void
309 amd64_nacl_membase_handler (guint8** code, gint8 basereg, gint32 offset, gint8 dreg)
310 {
311         gint8 true_basereg = basereg;
312
313         /* Cache these values, they might change  */
314         /* as new instructions are emitted below. */
315         guint8* rex_tag = amd64_nacl_get_rex_tag ();
316         guint8* legacy_prefix_tag = amd64_nacl_get_legacy_prefix_tag ();
317
318         /* 'basereg' is given masked to 0x7 at this point, so check */
319         /* the rex prefix to see if this is an extended register.   */
320         if ((rex_tag != NULL) && IS_REX(*rex_tag) && (*rex_tag & AMD64_REX_B)) {
321                 true_basereg |= 0x8;
322         }
323
324 #define X86_LEA_OPCODE (0x8D)
325
326         if (!amd64_is_valid_nacl_base (true_basereg) && (*(*code-1) != X86_LEA_OPCODE)) {
327                 guint8* old_instruction_start;
328                 
329                 /* This will hold the 'mov %eXX, %eXX' that clears the upper */
330                 /* 32-bits of the old base register (new index register)     */
331                 guint8 buf[32];
332                 guint8* buf_ptr = buf;
333                 size_t insert_len;
334
335                 g_assert (rex_tag != NULL);
336
337                 if (IS_REX(*rex_tag)) {
338                         /* The old rex.B should be the new rex.X */
339                         if (*rex_tag & AMD64_REX_B) {
340                                 *rex_tag |= AMD64_REX_X;
341                         }
342                         /* Since our new base is %r15 set rex.B */
343                         *rex_tag |= AMD64_REX_B;
344                 } else {
345                         /* Shift the instruction by one byte  */
346                         /* so we can insert a rex prefix      */
347                         memmove (rex_tag + 1, rex_tag, (size_t)(*code - rex_tag));
348                         *code += 1;
349                         /* New rex prefix only needs rex.B for %r15 base */
350                         *rex_tag = AMD64_REX(AMD64_REX_B);
351                 }
352
353                 if (legacy_prefix_tag) {
354                         old_instruction_start = legacy_prefix_tag;
355                 } else {
356                         old_instruction_start = rex_tag;
357                 }
358                 
359                 /* Clears the upper 32-bits of the previous base register */
360                 amd64_mov_reg_reg_size (buf_ptr, true_basereg, true_basereg, 4);
361                 insert_len = buf_ptr - buf;
362                 
363                 /* Move the old instruction forward to make */
364                 /* room for 'mov' stored in 'buf_ptr'       */
365                 memmove (old_instruction_start + insert_len, old_instruction_start, (size_t)(*code - old_instruction_start));
366                 *code += insert_len;
367                 memcpy (old_instruction_start, buf, insert_len);
368
369                 /* Sandboxed replacement for the normal membase_emit */
370                 x86_memindex_emit (*code, dreg, AMD64_R15, offset, basereg, 0);
371                 
372         } else {
373                 /* Normal default behavior, emit membase memory location */
374                 x86_membase_emit_body (*code, dreg, basereg, offset);
375         }
376 }
377
378
379 static inline unsigned char*
380 amd64_skip_nops (unsigned char* code)
381 {
382         guint8 in_nop;
383         do {
384                 in_nop = 0;
385                 if (   code[0] == 0x90) {
386                         in_nop = 1;
387                         code += 1;
388                 }
389                 if (   code[0] == 0x66 && code[1] == 0x90) {
390                         in_nop = 1;
391                         code += 2;
392                 }
393                 if (code[0] == 0x0f && code[1] == 0x1f
394                  && code[2] == 0x00) {
395                         in_nop = 1;
396                         code += 3;
397                 }
398                 if (code[0] == 0x0f && code[1] == 0x1f
399                  && code[2] == 0x40 && code[3] == 0x00) {
400                         in_nop = 1;
401                         code += 4;
402                 }
403                 if (code[0] == 0x0f && code[1] == 0x1f
404                  && code[2] == 0x44 && code[3] == 0x00
405                  && code[4] == 0x00) {
406                         in_nop = 1;
407                         code += 5;
408                 }
409                 if (code[0] == 0x66 && code[1] == 0x0f
410                  && code[2] == 0x1f && code[3] == 0x44
411                  && code[4] == 0x00 && code[5] == 0x00) {
412                         in_nop = 1;
413                         code += 6;
414                 }
415                 if (code[0] == 0x0f && code[1] == 0x1f
416                  && code[2] == 0x80 && code[3] == 0x00
417                  && code[4] == 0x00 && code[5] == 0x00
418                  && code[6] == 0x00) {
419                         in_nop = 1;
420                         code += 7;
421                 }
422                 if (code[0] == 0x0f && code[1] == 0x1f
423                  && code[2] == 0x84 && code[3] == 0x00
424                  && code[4] == 0x00 && code[5] == 0x00
425                  && code[6] == 0x00 && code[7] == 0x00) {
426                         in_nop = 1;
427                         code += 8;
428                 }
429         } while ( in_nop );
430         return code;
431 }
432
433 guint8*
434 mono_arch_nacl_skip_nops (guint8* code)
435 {
436   return amd64_skip_nops(code);
437 }
438
439 #endif /*__native_client_codegen__*/
440
441 static inline void 
442 amd64_patch (unsigned char* code, gpointer target)
443 {
444         guint8 rex = 0;
445
446 #ifdef __native_client_codegen__
447         code = amd64_skip_nops (code);
448 #endif
449 #if defined(__native_client_codegen__) && defined(__native_client__)
450         if (nacl_is_code_address (code)) {
451                 /* For tail calls, code is patched after being installed */
452                 /* but not through the normal "patch callsite" method.   */
453                 unsigned char buf[kNaClAlignment];
454                 unsigned char *aligned_code = (uintptr_t)code & ~kNaClAlignmentMask;
455                 int ret;
456                 memcpy (buf, aligned_code, kNaClAlignment);
457                 /* Patch a temp buffer of bundle size, */
458                 /* then install to actual location.    */
459                 amd64_patch (buf + ((uintptr_t)code - (uintptr_t)aligned_code), target);
460                 ret = nacl_dyncode_modify (aligned_code, buf, kNaClAlignment);
461                 g_assert (ret == 0);
462                 return;
463         }
464         target = nacl_modify_patch_target (target);
465 #endif
466
467         /* Skip REX */
468         if ((code [0] >= 0x40) && (code [0] <= 0x4f)) {
469                 rex = code [0];
470                 code += 1;
471         }
472
473         if ((code [0] & 0xf8) == 0xb8) {
474                 /* amd64_set_reg_template */
475                 *(guint64*)(code + 1) = (guint64)target;
476         }
477         else if ((code [0] == 0x8b) && rex && x86_modrm_mod (code [1]) == 0 && x86_modrm_rm (code [1]) == 5) {
478                 /* mov 0(%rip), %dreg */
479                 *(guint32*)(code + 2) = (guint32)(guint64)target - 7;
480         }
481         else if ((code [0] == 0xff) && (code [1] == 0x15)) {
482                 /* call *<OFFSET>(%rip) */
483                 *(guint32*)(code + 2) = ((guint32)(guint64)target) - 7;
484         }
485         else if (code [0] == 0xe8) {
486                 /* call <DISP> */
487                 gint64 disp = (guint8*)target - (guint8*)code;
488                 g_assert (amd64_is_imm32 (disp));
489                 x86_patch (code, (unsigned char*)target);
490         }
491         else
492                 x86_patch (code, (unsigned char*)target);
493 }
494
495 void 
496 mono_amd64_patch (unsigned char* code, gpointer target)
497 {
498         amd64_patch (code, target);
499 }
500
501 typedef enum {
502         ArgInIReg,
503         ArgInFloatSSEReg,
504         ArgInDoubleSSEReg,
505         ArgOnStack,
506         ArgValuetypeInReg,
507         ArgValuetypeAddrInIReg,
508         ArgNone /* only in pair_storage */
509 } ArgStorage;
510
511 typedef struct {
512         gint16 offset;
513         gint8  reg;
514         ArgStorage storage;
515
516         /* Only if storage == ArgValuetypeInReg */
517         ArgStorage pair_storage [2];
518         gint8 pair_regs [2];
519         int nregs;
520 } ArgInfo;
521
522 typedef struct {
523         int nargs;
524         guint32 stack_usage;
525         guint32 reg_usage;
526         guint32 freg_usage;
527         gboolean need_stack_align;
528         gboolean vtype_retaddr;
529         /* The index of the vret arg in the argument list */
530         int vret_arg_index;
531         ArgInfo ret;
532         ArgInfo sig_cookie;
533         ArgInfo args [1];
534 } CallInfo;
535
536 #define DEBUG(a) if (cfg->verbose_level > 1) a
537
538 #ifdef HOST_WIN32
539 #define PARAM_REGS 4
540
541 static AMD64_Reg_No param_regs [] = { AMD64_RCX, AMD64_RDX, AMD64_R8, AMD64_R9 };
542
543 static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
544 #else
545 #define PARAM_REGS 6
546  
547 static AMD64_Reg_No param_regs [] = { AMD64_RDI, AMD64_RSI, AMD64_RDX, AMD64_RCX, AMD64_R8, AMD64_R9 };
548
549  static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
550 #endif
551
552 static void inline
553 add_general (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo)
554 {
555     ainfo->offset = *stack_size;
556
557     if (*gr >= PARAM_REGS) {
558                 ainfo->storage = ArgOnStack;
559                 /* Since the same stack slot size is used for all arg */
560                 /*  types, it needs to be big enough to hold them all */
561                 (*stack_size) += sizeof(mgreg_t);
562     }
563     else {
564                 ainfo->storage = ArgInIReg;
565                 ainfo->reg = param_regs [*gr];
566                 (*gr) ++;
567     }
568 }
569
570 #ifdef HOST_WIN32
571 #define FLOAT_PARAM_REGS 4
572 #else
573 #define FLOAT_PARAM_REGS 8
574 #endif
575
576 static void inline
577 add_float (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo, gboolean is_double)
578 {
579     ainfo->offset = *stack_size;
580
581     if (*gr >= FLOAT_PARAM_REGS) {
582                 ainfo->storage = ArgOnStack;
583                 /* Since the same stack slot size is used for both float */
584                 /*  types, it needs to be big enough to hold them both */
585                 (*stack_size) += sizeof(mgreg_t);
586     }
587     else {
588                 /* A double register */
589                 if (is_double)
590                         ainfo->storage = ArgInDoubleSSEReg;
591                 else
592                         ainfo->storage = ArgInFloatSSEReg;
593                 ainfo->reg = *gr;
594                 (*gr) += 1;
595     }
596 }
597
598 typedef enum ArgumentClass {
599         ARG_CLASS_NO_CLASS,
600         ARG_CLASS_MEMORY,
601         ARG_CLASS_INTEGER,
602         ARG_CLASS_SSE
603 } ArgumentClass;
604
605 static ArgumentClass
606 merge_argument_class_from_type (MonoType *type, ArgumentClass class1)
607 {
608         ArgumentClass class2 = ARG_CLASS_NO_CLASS;
609         MonoType *ptype;
610
611         ptype = mini_type_get_underlying_type (NULL, type);
612         switch (ptype->type) {
613         case MONO_TYPE_BOOLEAN:
614         case MONO_TYPE_CHAR:
615         case MONO_TYPE_I1:
616         case MONO_TYPE_U1:
617         case MONO_TYPE_I2:
618         case MONO_TYPE_U2:
619         case MONO_TYPE_I4:
620         case MONO_TYPE_U4:
621         case MONO_TYPE_I:
622         case MONO_TYPE_U:
623         case MONO_TYPE_STRING:
624         case MONO_TYPE_OBJECT:
625         case MONO_TYPE_CLASS:
626         case MONO_TYPE_SZARRAY:
627         case MONO_TYPE_PTR:
628         case MONO_TYPE_FNPTR:
629         case MONO_TYPE_ARRAY:
630         case MONO_TYPE_I8:
631         case MONO_TYPE_U8:
632                 class2 = ARG_CLASS_INTEGER;
633                 break;
634         case MONO_TYPE_R4:
635         case MONO_TYPE_R8:
636 #ifdef HOST_WIN32
637                 class2 = ARG_CLASS_INTEGER;
638 #else
639                 class2 = ARG_CLASS_SSE;
640 #endif
641                 break;
642
643         case MONO_TYPE_TYPEDBYREF:
644                 g_assert_not_reached ();
645
646         case MONO_TYPE_GENERICINST:
647                 if (!mono_type_generic_inst_is_valuetype (ptype)) {
648                         class2 = ARG_CLASS_INTEGER;
649                         break;
650                 }
651                 /* fall through */
652         case MONO_TYPE_VALUETYPE: {
653                 MonoMarshalType *info = mono_marshal_load_type_info (ptype->data.klass);
654                 int i;
655
656                 for (i = 0; i < info->num_fields; ++i) {
657                         class2 = class1;
658                         class2 = merge_argument_class_from_type (info->fields [i].field->type, class2);
659                 }
660                 break;
661         }
662         default:
663                 g_assert_not_reached ();
664         }
665
666         /* Merge */
667         if (class1 == class2)
668                 ;
669         else if (class1 == ARG_CLASS_NO_CLASS)
670                 class1 = class2;
671         else if ((class1 == ARG_CLASS_MEMORY) || (class2 == ARG_CLASS_MEMORY))
672                 class1 = ARG_CLASS_MEMORY;
673         else if ((class1 == ARG_CLASS_INTEGER) || (class2 == ARG_CLASS_INTEGER))
674                 class1 = ARG_CLASS_INTEGER;
675         else
676                 class1 = ARG_CLASS_SSE;
677
678         return class1;
679 }
680 #ifdef __native_client_codegen__
681
682 /* Default alignment for Native Client is 32-byte. */
683 gint8 nacl_align_byte = -32; /* signed version of 0xe0 */
684
685 /* mono_arch_nacl_pad: Add pad bytes of alignment instructions at code,  */
686 /* Check that alignment doesn't cross an alignment boundary.             */
687 guint8*
688 mono_arch_nacl_pad(guint8 *code, int pad)
689 {
690         const int kMaxPadding = 8; /* see amd64-codegen.h:amd64_padding_size() */
691
692         if (pad == 0) return code;
693         /* assertion: alignment cannot cross a block boundary */
694         g_assert (((uintptr_t)code & (~kNaClAlignmentMask)) ==
695                  (((uintptr_t)code + pad - 1) & (~kNaClAlignmentMask)));
696         while (pad >= kMaxPadding) {
697                 amd64_padding (code, kMaxPadding);
698                 pad -= kMaxPadding;
699         }
700         if (pad != 0) amd64_padding (code, pad);
701         return code;
702 }
703 #endif
704
705 static void
706 add_valuetype (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig, ArgInfo *ainfo, MonoType *type,
707                            gboolean is_return,
708                            guint32 *gr, guint32 *fr, guint32 *stack_size)
709 {
710         guint32 size, quad, nquads, i;
711         /* Keep track of the size used in each quad so we can */
712         /* use the right size when copying args/return vars.  */
713         guint32 quadsize [2] = {8, 8};
714         ArgumentClass args [2];
715         MonoMarshalType *info = NULL;
716         MonoClass *klass;
717         MonoGenericSharingContext tmp_gsctx;
718         gboolean pass_on_stack = FALSE;
719         
720         /* 
721          * The gsctx currently contains no data, it is only used for checking whenever
722          * open types are allowed, some callers like mono_arch_get_argument_info ()
723          * don't pass it to us, so work around that.
724          */
725         if (!gsctx)
726                 gsctx = &tmp_gsctx;
727
728         klass = mono_class_from_mono_type (type);
729         size = mini_type_stack_size_full (gsctx, &klass->byval_arg, NULL, sig->pinvoke);
730 #ifndef HOST_WIN32
731         if (!sig->pinvoke && !disable_vtypes_in_regs && ((is_return && (size == 8)) || (!is_return && (size <= 16)))) {
732                 /* We pass and return vtypes of size 8 in a register */
733         } else if (!sig->pinvoke || (size == 0) || (size > 16)) {
734                 pass_on_stack = TRUE;
735         }
736 #else
737         if (!sig->pinvoke) {
738                 pass_on_stack = TRUE;
739         }
740 #endif
741
742         /* If this struct can't be split up naturally into 8-byte */
743         /* chunks (registers), pass it on the stack.              */
744         if (sig->pinvoke && !pass_on_stack) {
745                 guint32 align;
746                 guint32 field_size;
747
748                 info = mono_marshal_load_type_info (klass);
749                 g_assert(info);
750                 for (i = 0; i < info->num_fields; ++i) {
751                         field_size = mono_marshal_type_size (info->fields [i].field->type, 
752                                                            info->fields [i].mspec, 
753                                                            &align, TRUE, klass->unicode);
754                         if ((info->fields [i].offset < 8) && (info->fields [i].offset + field_size) > 8) {
755                                 pass_on_stack = TRUE;
756                                 break;
757                         }
758                 }
759         }
760
761         if (pass_on_stack) {
762                 /* Allways pass in memory */
763                 ainfo->offset = *stack_size;
764                 *stack_size += ALIGN_TO (size, 8);
765                 ainfo->storage = ArgOnStack;
766
767                 return;
768         }
769
770         /* FIXME: Handle structs smaller than 8 bytes */
771         //if ((size % 8) != 0)
772         //      NOT_IMPLEMENTED;
773
774         if (size > 8)
775                 nquads = 2;
776         else
777                 nquads = 1;
778
779         if (!sig->pinvoke) {
780                 /* Always pass in 1 or 2 integer registers */
781                 args [0] = ARG_CLASS_INTEGER;
782                 args [1] = ARG_CLASS_INTEGER;
783                 /* Only the simplest cases are supported */
784                 if (is_return && nquads != 1) {
785                         args [0] = ARG_CLASS_MEMORY;
786                         args [1] = ARG_CLASS_MEMORY;
787                 }
788         } else {
789                 /*
790                  * Implement the algorithm from section 3.2.3 of the X86_64 ABI.
791                  * The X87 and SSEUP stuff is left out since there are no such types in
792                  * the CLR.
793                  */
794                 info = mono_marshal_load_type_info (klass);
795                 g_assert (info);
796
797 #ifndef HOST_WIN32
798                 if (info->native_size > 16) {
799                         ainfo->offset = *stack_size;
800                         *stack_size += ALIGN_TO (info->native_size, 8);
801                         ainfo->storage = ArgOnStack;
802
803                         return;
804                 }
805 #else
806                 switch (info->native_size) {
807                 case 1: case 2: case 4: case 8:
808                         break;
809                 default:
810                         if (is_return) {
811                                 ainfo->storage = ArgOnStack;
812                                 ainfo->offset = *stack_size;
813                                 *stack_size += ALIGN_TO (info->native_size, 8);
814                         }
815                         else {
816                                 ainfo->storage = ArgValuetypeAddrInIReg;
817
818                                 if (*gr < PARAM_REGS) {
819                                         ainfo->pair_storage [0] = ArgInIReg;
820                                         ainfo->pair_regs [0] = param_regs [*gr];
821                                         (*gr) ++;
822                                 }
823                                 else {
824                                         ainfo->pair_storage [0] = ArgOnStack;
825                                         ainfo->offset = *stack_size;
826                                         *stack_size += 8;
827                                 }
828                         }
829
830                         return;
831                 }
832 #endif
833
834                 args [0] = ARG_CLASS_NO_CLASS;
835                 args [1] = ARG_CLASS_NO_CLASS;
836                 for (quad = 0; quad < nquads; ++quad) {
837                         int size;
838                         guint32 align;
839                         ArgumentClass class1;
840                 
841                         if (info->num_fields == 0)
842                                 class1 = ARG_CLASS_MEMORY;
843                         else
844                                 class1 = ARG_CLASS_NO_CLASS;
845                         for (i = 0; i < info->num_fields; ++i) {
846                                 size = mono_marshal_type_size (info->fields [i].field->type, 
847                                                                                            info->fields [i].mspec, 
848                                                                                            &align, TRUE, klass->unicode);
849                                 if ((info->fields [i].offset < 8) && (info->fields [i].offset + size) > 8) {
850                                         /* Unaligned field */
851                                         NOT_IMPLEMENTED;
852                                 }
853
854                                 /* Skip fields in other quad */
855                                 if ((quad == 0) && (info->fields [i].offset >= 8))
856                                         continue;
857                                 if ((quad == 1) && (info->fields [i].offset < 8))
858                                         continue;
859
860                                 /* How far into this quad this data extends.*/
861                                 /* (8 is size of quad) */
862                                 quadsize [quad] = info->fields [i].offset + size - (quad * 8);
863
864                                 class1 = merge_argument_class_from_type (info->fields [i].field->type, class1);
865                         }
866                         g_assert (class1 != ARG_CLASS_NO_CLASS);
867                         args [quad] = class1;
868                 }
869         }
870
871         /* Post merger cleanup */
872         if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY))
873                 args [0] = args [1] = ARG_CLASS_MEMORY;
874
875         /* Allocate registers */
876         {
877                 int orig_gr = *gr;
878                 int orig_fr = *fr;
879
880                 ainfo->storage = ArgValuetypeInReg;
881                 ainfo->pair_storage [0] = ainfo->pair_storage [1] = ArgNone;
882                 ainfo->nregs = nquads;
883                 for (quad = 0; quad < nquads; ++quad) {
884                         switch (args [quad]) {
885                         case ARG_CLASS_INTEGER:
886                                 if (*gr >= PARAM_REGS)
887                                         args [quad] = ARG_CLASS_MEMORY;
888                                 else {
889                                         ainfo->pair_storage [quad] = ArgInIReg;
890                                         if (is_return)
891                                                 ainfo->pair_regs [quad] = return_regs [*gr];
892                                         else
893                                                 ainfo->pair_regs [quad] = param_regs [*gr];
894                                         (*gr) ++;
895                                 }
896                                 break;
897                         case ARG_CLASS_SSE:
898                                 if (*fr >= FLOAT_PARAM_REGS)
899                                         args [quad] = ARG_CLASS_MEMORY;
900                                 else {
901                                         if (quadsize[quad] <= 4)
902                                                 ainfo->pair_storage [quad] = ArgInFloatSSEReg;
903                                         else ainfo->pair_storage [quad] = ArgInDoubleSSEReg;
904                                         ainfo->pair_regs [quad] = *fr;
905                                         (*fr) ++;
906                                 }
907                                 break;
908                         case ARG_CLASS_MEMORY:
909                                 break;
910                         default:
911                                 g_assert_not_reached ();
912                         }
913                 }
914
915                 if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY)) {
916                         /* Revert possible register assignments */
917                         *gr = orig_gr;
918                         *fr = orig_fr;
919
920                         ainfo->offset = *stack_size;
921                         if (sig->pinvoke)
922                                 *stack_size += ALIGN_TO (info->native_size, 8);
923                         else
924                                 *stack_size += nquads * sizeof(mgreg_t);
925                         ainfo->storage = ArgOnStack;
926                 }
927         }
928 }
929
930 /*
931  * get_call_info:
932  *
933  *  Obtain information about a call according to the calling convention.
934  * For AMD64, see the "System V ABI, x86-64 Architecture Processor Supplement 
935  * Draft Version 0.23" document for more information.
936  */
937 static CallInfo*
938 get_call_info (MonoGenericSharingContext *gsctx, MonoMemPool *mp, MonoMethodSignature *sig)
939 {
940         guint32 i, gr, fr, pstart;
941         MonoType *ret_type;
942         int n = sig->hasthis + sig->param_count;
943         guint32 stack_size = 0;
944         CallInfo *cinfo;
945         gboolean is_pinvoke = sig->pinvoke;
946
947         if (mp)
948                 cinfo = mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n));
949         else
950                 cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n));
951
952         cinfo->nargs = n;
953
954         gr = 0;
955         fr = 0;
956
957         /* return value */
958         {
959                 ret_type = mini_type_get_underlying_type (gsctx, sig->ret);
960                 switch (ret_type->type) {
961                 case MONO_TYPE_BOOLEAN:
962                 case MONO_TYPE_I1:
963                 case MONO_TYPE_U1:
964                 case MONO_TYPE_I2:
965                 case MONO_TYPE_U2:
966                 case MONO_TYPE_CHAR:
967                 case MONO_TYPE_I4:
968                 case MONO_TYPE_U4:
969                 case MONO_TYPE_I:
970                 case MONO_TYPE_U:
971                 case MONO_TYPE_PTR:
972                 case MONO_TYPE_FNPTR:
973                 case MONO_TYPE_CLASS:
974                 case MONO_TYPE_OBJECT:
975                 case MONO_TYPE_SZARRAY:
976                 case MONO_TYPE_ARRAY:
977                 case MONO_TYPE_STRING:
978                         cinfo->ret.storage = ArgInIReg;
979                         cinfo->ret.reg = AMD64_RAX;
980                         break;
981                 case MONO_TYPE_U8:
982                 case MONO_TYPE_I8:
983                         cinfo->ret.storage = ArgInIReg;
984                         cinfo->ret.reg = AMD64_RAX;
985                         break;
986                 case MONO_TYPE_R4:
987                         cinfo->ret.storage = ArgInFloatSSEReg;
988                         cinfo->ret.reg = AMD64_XMM0;
989                         break;
990                 case MONO_TYPE_R8:
991                         cinfo->ret.storage = ArgInDoubleSSEReg;
992                         cinfo->ret.reg = AMD64_XMM0;
993                         break;
994                 case MONO_TYPE_GENERICINST:
995                         if (!mono_type_generic_inst_is_valuetype (ret_type)) {
996                                 cinfo->ret.storage = ArgInIReg;
997                                 cinfo->ret.reg = AMD64_RAX;
998                                 break;
999                         }
1000                         /* fall through */
1001 #if defined( __native_client_codegen__ )
1002                 case MONO_TYPE_TYPEDBYREF:
1003 #endif
1004                 case MONO_TYPE_VALUETYPE: {
1005                         guint32 tmp_gr = 0, tmp_fr = 0, tmp_stacksize = 0;
1006
1007                         add_valuetype (gsctx, sig, &cinfo->ret, ret_type, TRUE, &tmp_gr, &tmp_fr, &tmp_stacksize);
1008                         if (cinfo->ret.storage == ArgOnStack) {
1009                                 cinfo->vtype_retaddr = TRUE;
1010                                 /* The caller passes the address where the value is stored */
1011                         }
1012                         break;
1013                 }
1014 #if !defined( __native_client_codegen__ )
1015                 case MONO_TYPE_TYPEDBYREF:
1016                         /* Same as a valuetype with size 24 */
1017                         cinfo->vtype_retaddr = TRUE;
1018                         break;
1019 #endif
1020                 case MONO_TYPE_VOID:
1021                         break;
1022                 default:
1023                         g_error ("Can't handle as return value 0x%x", ret_type->type);
1024                 }
1025         }
1026
1027         pstart = 0;
1028         /*
1029          * To simplify get_this_arg_reg () and LLVM integration, emit the vret arg after
1030          * the first argument, allowing 'this' to be always passed in the first arg reg.
1031          * Also do this if the first argument is a reference type, since virtual calls
1032          * are sometimes made using calli without sig->hasthis set, like in the delegate
1033          * invoke wrappers.
1034          */
1035         if (cinfo->vtype_retaddr && !is_pinvoke && (sig->hasthis || (sig->param_count > 0 && MONO_TYPE_IS_REFERENCE (mini_type_get_underlying_type (gsctx, sig->params [0]))))) {
1036                 if (sig->hasthis) {
1037                         add_general (&gr, &stack_size, cinfo->args + 0);
1038                 } else {
1039                         add_general (&gr, &stack_size, &cinfo->args [sig->hasthis + 0]);
1040                         pstart = 1;
1041                 }
1042                 add_general (&gr, &stack_size, &cinfo->ret);
1043                 cinfo->vret_arg_index = 1;
1044         } else {
1045                 /* this */
1046                 if (sig->hasthis)
1047                         add_general (&gr, &stack_size, cinfo->args + 0);
1048
1049                 if (cinfo->vtype_retaddr)
1050                         add_general (&gr, &stack_size, &cinfo->ret);
1051         }
1052
1053         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == 0)) {
1054                 gr = PARAM_REGS;
1055                 fr = FLOAT_PARAM_REGS;
1056                 
1057                 /* Emit the signature cookie just before the implicit arguments */
1058                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
1059         }
1060
1061         for (i = pstart; i < sig->param_count; ++i) {
1062                 ArgInfo *ainfo = &cinfo->args [sig->hasthis + i];
1063                 MonoType *ptype;
1064
1065 #ifdef HOST_WIN32
1066                 /* The float param registers and other param registers must be the same index on Windows x64.*/
1067                 if (gr > fr)
1068                         fr = gr;
1069                 else if (fr > gr)
1070                         gr = fr;
1071 #endif
1072
1073                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
1074                         /* We allways pass the sig cookie on the stack for simplicity */
1075                         /* 
1076                          * Prevent implicit arguments + the sig cookie from being passed 
1077                          * in registers.
1078                          */
1079                         gr = PARAM_REGS;
1080                         fr = FLOAT_PARAM_REGS;
1081
1082                         /* Emit the signature cookie just before the implicit arguments */
1083                         add_general (&gr, &stack_size, &cinfo->sig_cookie);
1084                 }
1085
1086                 ptype = mini_type_get_underlying_type (gsctx, sig->params [i]);
1087                 switch (ptype->type) {
1088                 case MONO_TYPE_BOOLEAN:
1089                 case MONO_TYPE_I1:
1090                 case MONO_TYPE_U1:
1091                         add_general (&gr, &stack_size, ainfo);
1092                         break;
1093                 case MONO_TYPE_I2:
1094                 case MONO_TYPE_U2:
1095                 case MONO_TYPE_CHAR:
1096                         add_general (&gr, &stack_size, ainfo);
1097                         break;
1098                 case MONO_TYPE_I4:
1099                 case MONO_TYPE_U4:
1100                         add_general (&gr, &stack_size, ainfo);
1101                         break;
1102                 case MONO_TYPE_I:
1103                 case MONO_TYPE_U:
1104                 case MONO_TYPE_PTR:
1105                 case MONO_TYPE_FNPTR:
1106                 case MONO_TYPE_CLASS:
1107                 case MONO_TYPE_OBJECT:
1108                 case MONO_TYPE_STRING:
1109                 case MONO_TYPE_SZARRAY:
1110                 case MONO_TYPE_ARRAY:
1111                         add_general (&gr, &stack_size, ainfo);
1112                         break;
1113                 case MONO_TYPE_GENERICINST:
1114                         if (!mono_type_generic_inst_is_valuetype (ptype)) {
1115                                 add_general (&gr, &stack_size, ainfo);
1116                                 break;
1117                         }
1118                         /* fall through */
1119                 case MONO_TYPE_VALUETYPE:
1120                         add_valuetype (gsctx, sig, ainfo, sig->params [i], FALSE, &gr, &fr, &stack_size);
1121                         break;
1122                 case MONO_TYPE_TYPEDBYREF:
1123 #if defined( HOST_WIN32 ) || defined( __native_client_codegen__ )
1124                         add_valuetype (gsctx, sig, ainfo, sig->params [i], FALSE, &gr, &fr, &stack_size);
1125 #else
1126                         stack_size += sizeof (MonoTypedRef);
1127                         ainfo->storage = ArgOnStack;
1128 #endif
1129                         break;
1130                 case MONO_TYPE_U8:
1131                 case MONO_TYPE_I8:
1132                         add_general (&gr, &stack_size, ainfo);
1133                         break;
1134                 case MONO_TYPE_R4:
1135                         add_float (&fr, &stack_size, ainfo, FALSE);
1136                         break;
1137                 case MONO_TYPE_R8:
1138                         add_float (&fr, &stack_size, ainfo, TRUE);
1139                         break;
1140                 default:
1141                         g_assert_not_reached ();
1142                 }
1143         }
1144
1145         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n > 0) && (sig->sentinelpos == sig->param_count)) {
1146                 gr = PARAM_REGS;
1147                 fr = FLOAT_PARAM_REGS;
1148                 
1149                 /* Emit the signature cookie just before the implicit arguments */
1150                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
1151         }
1152
1153 #ifdef HOST_WIN32
1154         // There always is 32 bytes reserved on the stack when calling on Winx64
1155         stack_size += 0x20;
1156 #endif
1157
1158 #ifndef MONO_AMD64_NO_PUSHES
1159         if (stack_size & 0x8) {
1160                 /* The AMD64 ABI requires each stack frame to be 16 byte aligned */
1161                 cinfo->need_stack_align = TRUE;
1162                 stack_size += 8;
1163         }
1164 #endif
1165
1166         cinfo->stack_usage = stack_size;
1167         cinfo->reg_usage = gr;
1168         cinfo->freg_usage = fr;
1169         return cinfo;
1170 }
1171
1172 /*
1173  * mono_arch_get_argument_info:
1174  * @csig:  a method signature
1175  * @param_count: the number of parameters to consider
1176  * @arg_info: an array to store the result infos
1177  *
1178  * Gathers information on parameters such as size, alignment and
1179  * padding. arg_info should be large enought to hold param_count + 1 entries. 
1180  *
1181  * Returns the size of the argument area on the stack.
1182  */
1183 int
1184 mono_arch_get_argument_info (MonoGenericSharingContext *gsctx, MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
1185 {
1186         int k;
1187         CallInfo *cinfo = get_call_info (NULL, NULL, csig);
1188         guint32 args_size = cinfo->stack_usage;
1189
1190         /* The arguments are saved to a stack area in mono_arch_instrument_prolog */
1191         if (csig->hasthis) {
1192                 arg_info [0].offset = 0;
1193         }
1194
1195         for (k = 0; k < param_count; k++) {
1196                 arg_info [k + 1].offset = ((k + csig->hasthis) * 8);
1197                 /* FIXME: */
1198                 arg_info [k + 1].size = 0;
1199         }
1200
1201         g_free (cinfo);
1202
1203         return args_size;
1204 }
1205
1206 gboolean
1207 mono_arch_tail_call_supported (MonoMethodSignature *caller_sig, MonoMethodSignature *callee_sig)
1208 {
1209         CallInfo *c1, *c2;
1210         gboolean res;
1211         MonoType *callee_ret;
1212
1213         c1 = get_call_info (NULL, NULL, caller_sig);
1214         c2 = get_call_info (NULL, NULL, callee_sig);
1215         res = c1->stack_usage >= c2->stack_usage;
1216         callee_ret = callee_sig->ret;
1217         if (callee_ret && MONO_TYPE_ISSTRUCT (callee_ret) && c2->ret.storage != ArgValuetypeInReg)
1218                 /* An address on the callee's stack is passed as the first argument */
1219                 res = FALSE;
1220
1221         g_free (c1);
1222         g_free (c2);
1223
1224         return res;
1225 }
1226
1227 /*
1228  * Initialize the cpu to execute managed code.
1229  */
1230 void
1231 mono_arch_cpu_init (void)
1232 {
1233 #ifndef _MSC_VER
1234         guint16 fpcw;
1235
1236         /* spec compliance requires running with double precision */
1237         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
1238         fpcw &= ~X86_FPCW_PRECC_MASK;
1239         fpcw |= X86_FPCW_PREC_DOUBLE;
1240         __asm__  __volatile__ ("fldcw %0\n": : "m" (fpcw));
1241         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
1242 #else
1243         /* TODO: This is crashing on Win64 right now.
1244         * _control87 (_PC_53, MCW_PC);
1245         */
1246 #endif
1247 }
1248
1249 /*
1250  * Initialize architecture specific code.
1251  */
1252 void
1253 mono_arch_init (void)
1254 {
1255         int flags;
1256
1257         InitializeCriticalSection (&mini_arch_mutex);
1258 #if defined(__native_client_codegen__)
1259         mono_native_tls_alloc (&nacl_instruction_depth, NULL);
1260         mono_native_tls_set_value (nacl_instruction_depth, (gpointer)0);
1261         mono_native_tls_alloc (&nacl_rex_tag, NULL);
1262         mono_native_tls_alloc (&nacl_legacy_prefix_tag, NULL);
1263 #endif
1264
1265 #ifdef MONO_ARCH_NOMAP32BIT
1266         flags = MONO_MMAP_READ;
1267         /* amd64_mov_reg_imm () + amd64_mov_reg_membase () */
1268         breakpoint_size = 13;
1269         breakpoint_fault_size = 3;
1270 #else
1271         flags = MONO_MMAP_READ|MONO_MMAP_32BIT;
1272         /* amd64_mov_reg_mem () */
1273         breakpoint_size = 8;
1274         breakpoint_fault_size = 8;
1275 #endif
1276
1277         /* amd64_alu_membase_imm_size (code, X86_CMP, AMD64_R11, 0, 0, 4); */
1278         single_step_fault_size = 4;
1279
1280         ss_trigger_page = mono_valloc (NULL, mono_pagesize (), flags);
1281         bp_trigger_page = mono_valloc (NULL, mono_pagesize (), flags);
1282         mono_mprotect (bp_trigger_page, mono_pagesize (), 0);
1283
1284         mono_aot_register_jit_icall ("mono_amd64_throw_exception", mono_amd64_throw_exception);
1285         mono_aot_register_jit_icall ("mono_amd64_throw_corlib_exception", mono_amd64_throw_corlib_exception);
1286         mono_aot_register_jit_icall ("mono_amd64_get_original_ip", mono_amd64_get_original_ip);
1287 }
1288
1289 /*
1290  * Cleanup architecture specific code.
1291  */
1292 void
1293 mono_arch_cleanup (void)
1294 {
1295         DeleteCriticalSection (&mini_arch_mutex);
1296 #if defined(__native_client_codegen__)
1297         mono_native_tls_free (nacl_instruction_depth);
1298         mono_native_tls_free (nacl_rex_tag);
1299         mono_native_tls_free (nacl_legacy_prefix_tag);
1300 #endif
1301 }
1302
1303 /*
1304  * This function returns the optimizations supported on this cpu.
1305  */
1306 guint32
1307 mono_arch_cpu_optimizations (guint32 *exclude_mask)
1308 {
1309         guint32 opts = 0;
1310
1311         *exclude_mask = 0;
1312
1313         if (mono_hwcap_x86_has_cmov) {
1314                 opts |= MONO_OPT_CMOV;
1315
1316                 if (mono_hwcap_x86_has_fcmov)
1317                         opts |= MONO_OPT_FCMOV;
1318                 else
1319                         *exclude_mask |= MONO_OPT_FCMOV;
1320         } else {
1321                 *exclude_mask |= MONO_OPT_CMOV;
1322         }
1323
1324         return opts;
1325 }
1326
1327 /*
1328  * This function test for all SSE functions supported.
1329  *
1330  * Returns a bitmask corresponding to all supported versions.
1331  * 
1332  */
1333 guint32
1334 mono_arch_cpu_enumerate_simd_versions (void)
1335 {
1336         guint32 sse_opts = 0;
1337
1338         if (mono_hwcap_x86_has_sse1)
1339                 sse_opts |= SIMD_VERSION_SSE1;
1340
1341         if (mono_hwcap_x86_has_sse2)
1342                 sse_opts |= SIMD_VERSION_SSE2;
1343
1344         if (mono_hwcap_x86_has_sse3)
1345                 sse_opts |= SIMD_VERSION_SSE3;
1346
1347         if (mono_hwcap_x86_has_ssse3)
1348                 sse_opts |= SIMD_VERSION_SSSE3;
1349
1350         if (mono_hwcap_x86_has_sse41)
1351                 sse_opts |= SIMD_VERSION_SSE41;
1352
1353         if (mono_hwcap_x86_has_sse42)
1354                 sse_opts |= SIMD_VERSION_SSE42;
1355
1356         if (mono_hwcap_x86_has_sse4a)
1357                 sse_opts |= SIMD_VERSION_SSE4a;
1358
1359         return sse_opts;
1360 }
1361
1362 #ifndef DISABLE_JIT
1363
1364 GList *
1365 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
1366 {
1367         GList *vars = NULL;
1368         int i;
1369
1370         for (i = 0; i < cfg->num_varinfo; i++) {
1371                 MonoInst *ins = cfg->varinfo [i];
1372                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
1373
1374                 /* unused vars */
1375                 if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
1376                         continue;
1377
1378                 if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || 
1379                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
1380                         continue;
1381
1382                 if (mono_is_regsize_var (ins->inst_vtype)) {
1383                         g_assert (MONO_VARINFO (cfg, i)->reg == -1);
1384                         g_assert (i == vmv->idx);
1385                         vars = g_list_prepend (vars, vmv);
1386                 }
1387         }
1388
1389         vars = mono_varlist_sort (cfg, vars, 0);
1390
1391         return vars;
1392 }
1393
1394 /**
1395  * mono_arch_compute_omit_fp:
1396  *
1397  *   Determine whenever the frame pointer can be eliminated.
1398  */
1399 static void
1400 mono_arch_compute_omit_fp (MonoCompile *cfg)
1401 {
1402         MonoMethodSignature *sig;
1403         MonoMethodHeader *header;
1404         int i, locals_size;
1405         CallInfo *cinfo;
1406
1407         if (cfg->arch.omit_fp_computed)
1408                 return;
1409
1410         header = cfg->header;
1411
1412         sig = mono_method_signature (cfg->method);
1413
1414         if (!cfg->arch.cinfo)
1415                 cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
1416         cinfo = cfg->arch.cinfo;
1417
1418         /*
1419          * FIXME: Remove some of the restrictions.
1420          */
1421         cfg->arch.omit_fp = TRUE;
1422         cfg->arch.omit_fp_computed = TRUE;
1423
1424 #ifdef __native_client_codegen__
1425         /* NaCl modules may not change the value of RBP, so it cannot be */
1426         /* used as a normal register, but it can be used as a frame pointer*/
1427         cfg->disable_omit_fp = TRUE;
1428         cfg->arch.omit_fp = FALSE;
1429 #endif
1430
1431         if (cfg->disable_omit_fp)
1432                 cfg->arch.omit_fp = FALSE;
1433
1434         if (!debug_omit_fp ())
1435                 cfg->arch.omit_fp = FALSE;
1436         /*
1437         if (cfg->method->save_lmf)
1438                 cfg->arch.omit_fp = FALSE;
1439         */
1440         if (cfg->flags & MONO_CFG_HAS_ALLOCA)
1441                 cfg->arch.omit_fp = FALSE;
1442         if (header->num_clauses)
1443                 cfg->arch.omit_fp = FALSE;
1444         if (cfg->param_area)
1445                 cfg->arch.omit_fp = FALSE;
1446         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG))
1447                 cfg->arch.omit_fp = FALSE;
1448         if ((mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) ||
1449                 (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE))
1450                 cfg->arch.omit_fp = FALSE;
1451         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1452                 ArgInfo *ainfo = &cinfo->args [i];
1453
1454                 if (ainfo->storage == ArgOnStack) {
1455                         /* 
1456                          * The stack offset can only be determined when the frame
1457                          * size is known.
1458                          */
1459                         cfg->arch.omit_fp = FALSE;
1460                 }
1461         }
1462
1463         locals_size = 0;
1464         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1465                 MonoInst *ins = cfg->varinfo [i];
1466                 int ialign;
1467
1468                 locals_size += mono_type_size (ins->inst_vtype, &ialign);
1469         }
1470 }
1471
1472 GList *
1473 mono_arch_get_global_int_regs (MonoCompile *cfg)
1474 {
1475         GList *regs = NULL;
1476
1477         mono_arch_compute_omit_fp (cfg);
1478
1479         if (cfg->globalra) {
1480                 if (cfg->arch.omit_fp)
1481                         regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
1482  
1483                 regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
1484                 regs = g_list_prepend (regs, (gpointer)AMD64_R12);
1485                 regs = g_list_prepend (regs, (gpointer)AMD64_R13);
1486                 regs = g_list_prepend (regs, (gpointer)AMD64_R14);
1487 #ifndef __native_client_codegen__
1488                 regs = g_list_prepend (regs, (gpointer)AMD64_R15);
1489 #endif
1490  
1491                 regs = g_list_prepend (regs, (gpointer)AMD64_R10);
1492                 regs = g_list_prepend (regs, (gpointer)AMD64_R9);
1493                 regs = g_list_prepend (regs, (gpointer)AMD64_R8);
1494                 regs = g_list_prepend (regs, (gpointer)AMD64_RDI);
1495                 regs = g_list_prepend (regs, (gpointer)AMD64_RSI);
1496                 regs = g_list_prepend (regs, (gpointer)AMD64_RDX);
1497                 regs = g_list_prepend (regs, (gpointer)AMD64_RCX);
1498                 regs = g_list_prepend (regs, (gpointer)AMD64_RAX);
1499         } else {
1500                 if (cfg->arch.omit_fp)
1501                         regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
1502
1503                 /* We use the callee saved registers for global allocation */
1504                 regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
1505                 regs = g_list_prepend (regs, (gpointer)AMD64_R12);
1506                 regs = g_list_prepend (regs, (gpointer)AMD64_R13);
1507                 regs = g_list_prepend (regs, (gpointer)AMD64_R14);
1508 #ifndef __native_client_codegen__
1509                 regs = g_list_prepend (regs, (gpointer)AMD64_R15);
1510 #endif
1511 #ifdef HOST_WIN32
1512                 regs = g_list_prepend (regs, (gpointer)AMD64_RDI);
1513                 regs = g_list_prepend (regs, (gpointer)AMD64_RSI);
1514 #endif
1515         }
1516
1517         return regs;
1518 }
1519  
1520 GList*
1521 mono_arch_get_global_fp_regs (MonoCompile *cfg)
1522 {
1523         GList *regs = NULL;
1524         int i;
1525
1526         /* All XMM registers */
1527         for (i = 0; i < 16; ++i)
1528                 regs = g_list_prepend (regs, GINT_TO_POINTER (i));
1529
1530         return regs;
1531 }
1532
1533 GList*
1534 mono_arch_get_iregs_clobbered_by_call (MonoCallInst *call)
1535 {
1536         static GList *r = NULL;
1537
1538         if (r == NULL) {
1539                 GList *regs = NULL;
1540
1541                 regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
1542                 regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
1543                 regs = g_list_prepend (regs, (gpointer)AMD64_R12);
1544                 regs = g_list_prepend (regs, (gpointer)AMD64_R13);
1545                 regs = g_list_prepend (regs, (gpointer)AMD64_R14);
1546 #ifndef __native_client_codegen__
1547                 regs = g_list_prepend (regs, (gpointer)AMD64_R15);
1548 #endif
1549
1550                 regs = g_list_prepend (regs, (gpointer)AMD64_R10);
1551                 regs = g_list_prepend (regs, (gpointer)AMD64_R9);
1552                 regs = g_list_prepend (regs, (gpointer)AMD64_R8);
1553                 regs = g_list_prepend (regs, (gpointer)AMD64_RDI);
1554                 regs = g_list_prepend (regs, (gpointer)AMD64_RSI);
1555                 regs = g_list_prepend (regs, (gpointer)AMD64_RDX);
1556                 regs = g_list_prepend (regs, (gpointer)AMD64_RCX);
1557                 regs = g_list_prepend (regs, (gpointer)AMD64_RAX);
1558
1559                 InterlockedCompareExchangePointer ((gpointer*)&r, regs, NULL);
1560         }
1561
1562         return r;
1563 }
1564
1565 GList*
1566 mono_arch_get_fregs_clobbered_by_call (MonoCallInst *call)
1567 {
1568         int i;
1569         static GList *r = NULL;
1570
1571         if (r == NULL) {
1572                 GList *regs = NULL;
1573
1574                 for (i = 0; i < AMD64_XMM_NREG; ++i)
1575                         regs = g_list_prepend (regs, GINT_TO_POINTER (MONO_MAX_IREGS + i));
1576
1577                 InterlockedCompareExchangePointer ((gpointer*)&r, regs, NULL);
1578         }
1579
1580         return r;
1581 }
1582
1583 /*
1584  * mono_arch_regalloc_cost:
1585  *
1586  *  Return the cost, in number of memory references, of the action of 
1587  * allocating the variable VMV into a register during global register
1588  * allocation.
1589  */
1590 guint32
1591 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
1592 {
1593         MonoInst *ins = cfg->varinfo [vmv->idx];
1594
1595         if (cfg->method->save_lmf)
1596                 /* The register is already saved */
1597                 /* substract 1 for the invisible store in the prolog */
1598                 return (ins->opcode == OP_ARG) ? 0 : 1;
1599         else
1600                 /* push+pop */
1601                 return (ins->opcode == OP_ARG) ? 1 : 2;
1602 }
1603
1604 /*
1605  * mono_arch_fill_argument_info:
1606  *
1607  *   Populate cfg->args, cfg->ret and cfg->vret_addr with information about the arguments
1608  * of the method.
1609  */
1610 void
1611 mono_arch_fill_argument_info (MonoCompile *cfg)
1612 {
1613         MonoType *sig_ret;
1614         MonoMethodSignature *sig;
1615         MonoMethodHeader *header;
1616         MonoInst *ins;
1617         int i;
1618         CallInfo *cinfo;
1619
1620         header = cfg->header;
1621
1622         sig = mono_method_signature (cfg->method);
1623
1624         cinfo = cfg->arch.cinfo;
1625         sig_ret = sig->ret;
1626         /*
1627          * Contrary to mono_arch_allocate_vars (), the information should describe
1628          * where the arguments are at the beginning of the method, not where they can be 
1629          * accessed during the execution of the method. The later makes no sense for the 
1630          * global register allocator, since a variable can be in more than one location.
1631          */
1632         if (sig_ret->type != MONO_TYPE_VOID) {
1633                 switch (cinfo->ret.storage) {
1634                 case ArgInIReg:
1635                 case ArgInFloatSSEReg:
1636                 case ArgInDoubleSSEReg:
1637                         if ((MONO_TYPE_ISSTRUCT (sig_ret) && !mono_class_from_mono_type (sig_ret)->enumtype) || ((sig_ret->type == MONO_TYPE_TYPEDBYREF) && cinfo->vtype_retaddr)) {
1638                                 cfg->vret_addr->opcode = OP_REGVAR;
1639                                 cfg->vret_addr->inst_c0 = cinfo->ret.reg;
1640                         }
1641                         else {
1642                                 cfg->ret->opcode = OP_REGVAR;
1643                                 cfg->ret->inst_c0 = cinfo->ret.reg;
1644                         }
1645                         break;
1646                 case ArgValuetypeInReg:
1647                         cfg->ret->opcode = OP_REGOFFSET;
1648                         cfg->ret->inst_basereg = -1;
1649                         cfg->ret->inst_offset = -1;
1650                         break;
1651                 default:
1652                         g_assert_not_reached ();
1653                 }
1654         }
1655
1656         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1657                 ArgInfo *ainfo = &cinfo->args [i];
1658                 MonoType *arg_type;
1659
1660                 ins = cfg->args [i];
1661
1662                 if (sig->hasthis && (i == 0))
1663                         arg_type = &mono_defaults.object_class->byval_arg;
1664                 else
1665                         arg_type = sig->params [i - sig->hasthis];
1666
1667                 switch (ainfo->storage) {
1668                 case ArgInIReg:
1669                 case ArgInFloatSSEReg:
1670                 case ArgInDoubleSSEReg:
1671                         ins->opcode = OP_REGVAR;
1672                         ins->inst_c0 = ainfo->reg;
1673                         break;
1674                 case ArgOnStack:
1675                         ins->opcode = OP_REGOFFSET;
1676                         ins->inst_basereg = -1;
1677                         ins->inst_offset = -1;
1678                         break;
1679                 case ArgValuetypeInReg:
1680                         /* Dummy */
1681                         ins->opcode = OP_NOP;
1682                         break;
1683                 default:
1684                         g_assert_not_reached ();
1685                 }
1686         }
1687 }
1688  
1689 void
1690 mono_arch_allocate_vars (MonoCompile *cfg)
1691 {
1692         MonoType *sig_ret;
1693         MonoMethodSignature *sig;
1694         MonoMethodHeader *header;
1695         MonoInst *ins;
1696         int i, offset;
1697         guint32 locals_stack_size, locals_stack_align;
1698         gint32 *offsets;
1699         CallInfo *cinfo;
1700
1701         header = cfg->header;
1702
1703         sig = mono_method_signature (cfg->method);
1704
1705         cinfo = cfg->arch.cinfo;
1706         sig_ret = sig->ret;
1707
1708         mono_arch_compute_omit_fp (cfg);
1709
1710         /*
1711          * We use the ABI calling conventions for managed code as well.
1712          * Exception: valuetypes are only sometimes passed or returned in registers.
1713          */
1714
1715         /*
1716          * The stack looks like this:
1717          * <incoming arguments passed on the stack>
1718          * <return value>
1719          * <lmf/caller saved registers>
1720          * <locals>
1721          * <spill area>
1722          * <localloc area>  -> grows dynamically
1723          * <params area>
1724          */
1725
1726         if (cfg->arch.omit_fp) {
1727                 cfg->flags |= MONO_CFG_HAS_SPILLUP;
1728                 cfg->frame_reg = AMD64_RSP;
1729                 offset = 0;
1730         } else {
1731                 /* Locals are allocated backwards from %fp */
1732                 cfg->frame_reg = AMD64_RBP;
1733                 offset = 0;
1734         }
1735
1736         if (cfg->method->save_lmf) {
1737                 /* The LMF var is allocated normally */
1738         } else {
1739                 if (cfg->arch.omit_fp)
1740                         cfg->arch.reg_save_area_offset = offset;
1741                 /* Reserve space for callee saved registers */
1742                 for (i = 0; i < AMD64_NREG; ++i)
1743                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
1744                                 offset += sizeof(mgreg_t);
1745                         }
1746         }
1747
1748         if (sig_ret->type != MONO_TYPE_VOID) {
1749                 switch (cinfo->ret.storage) {
1750                 case ArgInIReg:
1751                 case ArgInFloatSSEReg:
1752                 case ArgInDoubleSSEReg:
1753                         if ((MONO_TYPE_ISSTRUCT (sig_ret) && !mono_class_from_mono_type (sig_ret)->enumtype) || ((sig_ret->type == MONO_TYPE_TYPEDBYREF) && cinfo->vtype_retaddr)) {
1754                                 if (cfg->globalra) {
1755                                         cfg->vret_addr->opcode = OP_REGVAR;
1756                                         cfg->vret_addr->inst_c0 = cinfo->ret.reg;
1757                                 } else {
1758                                         /* The register is volatile */
1759                                         cfg->vret_addr->opcode = OP_REGOFFSET;
1760                                         cfg->vret_addr->inst_basereg = cfg->frame_reg;
1761                                         if (cfg->arch.omit_fp) {
1762                                                 cfg->vret_addr->inst_offset = offset;
1763                                                 offset += 8;
1764                                         } else {
1765                                                 offset += 8;
1766                                                 cfg->vret_addr->inst_offset = -offset;
1767                                         }
1768                                         if (G_UNLIKELY (cfg->verbose_level > 1)) {
1769                                                 printf ("vret_addr =");
1770                                                 mono_print_ins (cfg->vret_addr);
1771                                         }
1772                                 }
1773                         }
1774                         else {
1775                                 cfg->ret->opcode = OP_REGVAR;
1776                                 cfg->ret->inst_c0 = cinfo->ret.reg;
1777                         }
1778                         break;
1779                 case ArgValuetypeInReg:
1780                         /* Allocate a local to hold the result, the epilog will copy it to the correct place */
1781                         cfg->ret->opcode = OP_REGOFFSET;
1782                         cfg->ret->inst_basereg = cfg->frame_reg;
1783                         if (cfg->arch.omit_fp) {
1784                                 cfg->ret->inst_offset = offset;
1785                                 offset += cinfo->ret.pair_storage [1] == ArgNone ? 8 : 16;
1786                         } else {
1787                                 offset += cinfo->ret.pair_storage [1] == ArgNone ? 8 : 16;
1788                                 cfg->ret->inst_offset = - offset;
1789                         }
1790                         break;
1791                 default:
1792                         g_assert_not_reached ();
1793                 }
1794                 if (!cfg->globalra)
1795                         cfg->ret->dreg = cfg->ret->inst_c0;
1796         }
1797
1798         /* Allocate locals */
1799         if (!cfg->globalra) {
1800                 offsets = mono_allocate_stack_slots (cfg, cfg->arch.omit_fp ? FALSE: TRUE, &locals_stack_size, &locals_stack_align);
1801                 if (locals_stack_size > MONO_ARCH_MAX_FRAME_SIZE) {
1802                         char *mname = mono_method_full_name (cfg->method, TRUE);
1803                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
1804                         cfg->exception_message = g_strdup_printf ("Method %s stack is too big.", mname);
1805                         g_free (mname);
1806                         return;
1807                 }
1808                 
1809                 if (locals_stack_align) {
1810                         offset += (locals_stack_align - 1);
1811                         offset &= ~(locals_stack_align - 1);
1812                 }
1813                 if (cfg->arch.omit_fp) {
1814                         cfg->locals_min_stack_offset = offset;
1815                         cfg->locals_max_stack_offset = offset + locals_stack_size;
1816                 } else {
1817                         cfg->locals_min_stack_offset = - (offset + locals_stack_size);
1818                         cfg->locals_max_stack_offset = - offset;
1819                 }
1820                 
1821                 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1822                         if (offsets [i] != -1) {
1823                                 MonoInst *ins = cfg->varinfo [i];
1824                                 ins->opcode = OP_REGOFFSET;
1825                                 ins->inst_basereg = cfg->frame_reg;
1826                                 if (cfg->arch.omit_fp)
1827                                         ins->inst_offset = (offset + offsets [i]);
1828                                 else
1829                                         ins->inst_offset = - (offset + offsets [i]);
1830                                 //printf ("allocated local %d to ", i); mono_print_tree_nl (ins);
1831                         }
1832                 }
1833                 offset += locals_stack_size;
1834         }
1835
1836         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) {
1837                 g_assert (!cfg->arch.omit_fp);
1838                 g_assert (cinfo->sig_cookie.storage == ArgOnStack);
1839                 cfg->sig_cookie = cinfo->sig_cookie.offset + ARGS_OFFSET;
1840         }
1841
1842         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1843                 ins = cfg->args [i];
1844                 if (ins->opcode != OP_REGVAR) {
1845                         ArgInfo *ainfo = &cinfo->args [i];
1846                         gboolean inreg = TRUE;
1847                         MonoType *arg_type;
1848
1849                         if (sig->hasthis && (i == 0))
1850                                 arg_type = &mono_defaults.object_class->byval_arg;
1851                         else
1852                                 arg_type = sig->params [i - sig->hasthis];
1853
1854                         if (cfg->globalra) {
1855                                 /* The new allocator needs info about the original locations of the arguments */
1856                                 switch (ainfo->storage) {
1857                                 case ArgInIReg:
1858                                 case ArgInFloatSSEReg:
1859                                 case ArgInDoubleSSEReg:
1860                                         ins->opcode = OP_REGVAR;
1861                                         ins->inst_c0 = ainfo->reg;
1862                                         break;
1863                                 case ArgOnStack:
1864                                         g_assert (!cfg->arch.omit_fp);
1865                                         ins->opcode = OP_REGOFFSET;
1866                                         ins->inst_basereg = cfg->frame_reg;
1867                                         ins->inst_offset = ainfo->offset + ARGS_OFFSET;
1868                                         break;
1869                                 case ArgValuetypeInReg:
1870                                         ins->opcode = OP_REGOFFSET;
1871                                         ins->inst_basereg = cfg->frame_reg;
1872                                         /* These arguments are saved to the stack in the prolog */
1873                                         offset = ALIGN_TO (offset, sizeof(mgreg_t));
1874                                         if (cfg->arch.omit_fp) {
1875                                                 ins->inst_offset = offset;
1876                                                 offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
1877                                         } else {
1878                                                 offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
1879                                                 ins->inst_offset = - offset;
1880                                         }
1881                                         break;
1882                                 default:
1883                                         g_assert_not_reached ();
1884                                 }
1885
1886                                 continue;
1887                         }
1888
1889                         /* FIXME: Allocate volatile arguments to registers */
1890                         if (ins->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1891                                 inreg = FALSE;
1892
1893                         /* 
1894                          * Under AMD64, all registers used to pass arguments to functions
1895                          * are volatile across calls.
1896                          * FIXME: Optimize this.
1897                          */
1898                         if ((ainfo->storage == ArgInIReg) || (ainfo->storage == ArgInFloatSSEReg) || (ainfo->storage == ArgInDoubleSSEReg) || (ainfo->storage == ArgValuetypeInReg))
1899                                 inreg = FALSE;
1900
1901                         ins->opcode = OP_REGOFFSET;
1902
1903                         switch (ainfo->storage) {
1904                         case ArgInIReg:
1905                         case ArgInFloatSSEReg:
1906                         case ArgInDoubleSSEReg:
1907                                 if (inreg) {
1908                                         ins->opcode = OP_REGVAR;
1909                                         ins->dreg = ainfo->reg;
1910                                 }
1911                                 break;
1912                         case ArgOnStack:
1913                                 g_assert (!cfg->arch.omit_fp);
1914                                 ins->opcode = OP_REGOFFSET;
1915                                 ins->inst_basereg = cfg->frame_reg;
1916                                 ins->inst_offset = ainfo->offset + ARGS_OFFSET;
1917                                 break;
1918                         case ArgValuetypeInReg:
1919                                 break;
1920                         case ArgValuetypeAddrInIReg: {
1921                                 MonoInst *indir;
1922                                 g_assert (!cfg->arch.omit_fp);
1923                                 
1924                                 MONO_INST_NEW (cfg, indir, 0);
1925                                 indir->opcode = OP_REGOFFSET;
1926                                 if (ainfo->pair_storage [0] == ArgInIReg) {
1927                                         indir->inst_basereg = cfg->frame_reg;
1928                                         offset = ALIGN_TO (offset, sizeof (gpointer));
1929                                         offset += (sizeof (gpointer));
1930                                         indir->inst_offset = - offset;
1931                                 }
1932                                 else {
1933                                         indir->inst_basereg = cfg->frame_reg;
1934                                         indir->inst_offset = ainfo->offset + ARGS_OFFSET;
1935                                 }
1936                                 
1937                                 ins->opcode = OP_VTARG_ADDR;
1938                                 ins->inst_left = indir;
1939                                 
1940                                 break;
1941                         }
1942                         default:
1943                                 NOT_IMPLEMENTED;
1944                         }
1945
1946                         if (!inreg && (ainfo->storage != ArgOnStack) && (ainfo->storage != ArgValuetypeAddrInIReg)) {
1947                                 ins->opcode = OP_REGOFFSET;
1948                                 ins->inst_basereg = cfg->frame_reg;
1949                                 /* These arguments are saved to the stack in the prolog */
1950                                 offset = ALIGN_TO (offset, sizeof(mgreg_t));
1951                                 if (cfg->arch.omit_fp) {
1952                                         ins->inst_offset = offset;
1953                                         offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
1954                                         // Arguments are yet supported by the stack map creation code
1955                                         //cfg->locals_max_stack_offset = MAX (cfg->locals_max_stack_offset, offset);
1956                                 } else {
1957                                         offset += (ainfo->storage == ArgValuetypeInReg) ? ainfo->nregs * sizeof (mgreg_t) : sizeof (mgreg_t);
1958                                         ins->inst_offset = - offset;
1959                                         //cfg->locals_min_stack_offset = MIN (cfg->locals_min_stack_offset, offset);
1960                                 }
1961                         }
1962                 }
1963         }
1964
1965         cfg->stack_offset = offset;
1966 }
1967
1968 void
1969 mono_arch_create_vars (MonoCompile *cfg)
1970 {
1971         MonoMethodSignature *sig;
1972         CallInfo *cinfo;
1973
1974         sig = mono_method_signature (cfg->method);
1975
1976         if (!cfg->arch.cinfo)
1977                 cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
1978         cinfo = cfg->arch.cinfo;
1979
1980         if (cinfo->ret.storage == ArgValuetypeInReg)
1981                 cfg->ret_var_is_local = TRUE;
1982
1983         if ((cinfo->ret.storage != ArgValuetypeInReg) && MONO_TYPE_ISSTRUCT (sig->ret)) {
1984                 cfg->vret_addr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_ARG);
1985                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
1986                         printf ("vret_addr = ");
1987                         mono_print_ins (cfg->vret_addr);
1988                 }
1989         }
1990
1991         if (cfg->gen_seq_points) {
1992                 MonoInst *ins;
1993
1994                 if (cfg->compile_aot) {
1995                         MonoInst *ins = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1996                         ins->flags |= MONO_INST_VOLATILE;
1997                         cfg->arch.seq_point_info_var = ins;
1998                 }
1999
2000             ins = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2001                 ins->flags |= MONO_INST_VOLATILE;
2002                 cfg->arch.ss_trigger_page_var = ins;
2003         }
2004
2005 #ifdef MONO_AMD64_NO_PUSHES
2006         /*
2007          * When this is set, we pass arguments on the stack by moves, and by allocating 
2008          * a bigger stack frame, instead of pushes.
2009          * Pushes complicate exception handling because the arguments on the stack have
2010          * to be popped each time a frame is unwound. They also make fp elimination
2011          * impossible.
2012          * FIXME: This doesn't work inside filter/finally clauses, since those execute
2013          * on a new frame which doesn't include a param area.
2014          */
2015         cfg->arch.no_pushes = TRUE;
2016 #endif
2017
2018         if (cfg->method->save_lmf) {
2019                 MonoInst *lmf_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2020                 lmf_var->flags |= MONO_INST_VOLATILE;
2021                 lmf_var->flags |= MONO_INST_LMF;
2022                 cfg->arch.lmf_var = lmf_var;
2023         }
2024
2025 #ifndef MONO_AMD64_NO_PUSHES
2026         cfg->arch_eh_jit_info = 1;
2027 #endif
2028 }
2029
2030 static void
2031 add_outarg_reg (MonoCompile *cfg, MonoCallInst *call, ArgStorage storage, int reg, MonoInst *tree)
2032 {
2033         MonoInst *ins;
2034
2035         switch (storage) {
2036         case ArgInIReg:
2037                 MONO_INST_NEW (cfg, ins, OP_MOVE);
2038                 ins->dreg = mono_alloc_ireg_copy (cfg, tree->dreg);
2039                 ins->sreg1 = tree->dreg;
2040                 MONO_ADD_INS (cfg->cbb, ins);
2041                 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, reg, FALSE);
2042                 break;
2043         case ArgInFloatSSEReg:
2044                 MONO_INST_NEW (cfg, ins, OP_AMD64_SET_XMMREG_R4);
2045                 ins->dreg = mono_alloc_freg (cfg);
2046                 ins->sreg1 = tree->dreg;
2047                 MONO_ADD_INS (cfg->cbb, ins);
2048
2049                 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, reg, TRUE);
2050                 break;
2051         case ArgInDoubleSSEReg:
2052                 MONO_INST_NEW (cfg, ins, OP_FMOVE);
2053                 ins->dreg = mono_alloc_freg (cfg);
2054                 ins->sreg1 = tree->dreg;
2055                 MONO_ADD_INS (cfg->cbb, ins);
2056
2057                 mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, reg, TRUE);
2058
2059                 break;
2060         default:
2061                 g_assert_not_reached ();
2062         }
2063 }
2064
2065 static int
2066 arg_storage_to_load_membase (ArgStorage storage)
2067 {
2068         switch (storage) {
2069         case ArgInIReg:
2070 #if defined(__mono_ilp32__)
2071                 return OP_LOADI8_MEMBASE;
2072 #else
2073                 return OP_LOAD_MEMBASE;
2074 #endif
2075         case ArgInDoubleSSEReg:
2076                 return OP_LOADR8_MEMBASE;
2077         case ArgInFloatSSEReg:
2078                 return OP_LOADR4_MEMBASE;
2079         default:
2080                 g_assert_not_reached ();
2081         }
2082
2083         return -1;
2084 }
2085
2086 static void
2087 emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo)
2088 {
2089         MonoInst *arg;
2090         MonoMethodSignature *tmp_sig;
2091         int sig_reg;
2092
2093         if (call->tail_call)
2094                 NOT_IMPLEMENTED;
2095
2096         g_assert (cinfo->sig_cookie.storage == ArgOnStack);
2097                         
2098         /*
2099          * mono_ArgIterator_Setup assumes the signature cookie is 
2100          * passed first and all the arguments which were before it are
2101          * passed on the stack after the signature. So compensate by 
2102          * passing a different signature.
2103          */
2104         tmp_sig = mono_metadata_signature_dup_full (cfg->method->klass->image, call->signature);
2105         tmp_sig->param_count -= call->signature->sentinelpos;
2106         tmp_sig->sentinelpos = 0;
2107         memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*));
2108
2109         sig_reg = mono_alloc_ireg (cfg);
2110         MONO_EMIT_NEW_SIGNATURECONST (cfg, sig_reg, tmp_sig);
2111
2112         if (cfg->arch.no_pushes) {
2113                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, cinfo->sig_cookie.offset, sig_reg);
2114         } else {
2115                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2116                 arg->sreg1 = sig_reg;
2117                 MONO_ADD_INS (cfg->cbb, arg);
2118         }
2119 }
2120
2121 static inline LLVMArgStorage
2122 arg_storage_to_llvm_arg_storage (MonoCompile *cfg, ArgStorage storage)
2123 {
2124         switch (storage) {
2125         case ArgInIReg:
2126                 return LLVMArgInIReg;
2127         case ArgNone:
2128                 return LLVMArgNone;
2129         default:
2130                 g_assert_not_reached ();
2131                 return LLVMArgNone;
2132         }
2133 }
2134
2135 #ifdef ENABLE_LLVM
2136 LLVMCallInfo*
2137 mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
2138 {
2139         int i, n;
2140         CallInfo *cinfo;
2141         ArgInfo *ainfo;
2142         int j;
2143         LLVMCallInfo *linfo;
2144         MonoType *t, *sig_ret;
2145
2146         n = sig->param_count + sig->hasthis;
2147         sig_ret = sig->ret;
2148         cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2149
2150         linfo = mono_mempool_alloc0 (cfg->mempool, sizeof (LLVMCallInfo) + (sizeof (LLVMArgInfo) * n));
2151
2152         /*
2153          * LLVM always uses the native ABI while we use our own ABI, the
2154          * only difference is the handling of vtypes:
2155          * - we only pass/receive them in registers in some cases, and only 
2156          *   in 1 or 2 integer registers.
2157          */
2158         if (cinfo->ret.storage == ArgValuetypeInReg) {
2159                 if (sig->pinvoke) {
2160                         cfg->exception_message = g_strdup ("pinvoke + vtypes");
2161                         cfg->disable_llvm = TRUE;
2162                         return linfo;
2163                 }
2164
2165                 linfo->ret.storage = LLVMArgVtypeInReg;
2166                 for (j = 0; j < 2; ++j)
2167                         linfo->ret.pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, cinfo->ret.pair_storage [j]);
2168         }
2169
2170         if (MONO_TYPE_ISSTRUCT (sig_ret) && cinfo->ret.storage == ArgInIReg) {
2171                 /* Vtype returned using a hidden argument */
2172                 linfo->ret.storage = LLVMArgVtypeRetAddr;
2173                 linfo->vret_arg_index = cinfo->vret_arg_index;
2174         }
2175
2176         for (i = 0; i < n; ++i) {
2177                 ainfo = cinfo->args + i;
2178
2179                 if (i >= sig->hasthis)
2180                         t = sig->params [i - sig->hasthis];
2181                 else
2182                         t = &mono_defaults.int_class->byval_arg;
2183
2184                 linfo->args [i].storage = LLVMArgNone;
2185
2186                 switch (ainfo->storage) {
2187                 case ArgInIReg:
2188                         linfo->args [i].storage = LLVMArgInIReg;
2189                         break;
2190                 case ArgInDoubleSSEReg:
2191                 case ArgInFloatSSEReg:
2192                         linfo->args [i].storage = LLVMArgInFPReg;
2193                         break;
2194                 case ArgOnStack:
2195                         if (MONO_TYPE_ISSTRUCT (t)) {
2196                                 linfo->args [i].storage = LLVMArgVtypeByVal;
2197                         } else {
2198                                 linfo->args [i].storage = LLVMArgInIReg;
2199                                 if (!t->byref) {
2200                                         if (t->type == MONO_TYPE_R4)
2201                                                 linfo->args [i].storage = LLVMArgInFPReg;
2202                                         else if (t->type == MONO_TYPE_R8)
2203                                                 linfo->args [i].storage = LLVMArgInFPReg;
2204                                 }
2205                         }
2206                         break;
2207                 case ArgValuetypeInReg:
2208                         if (sig->pinvoke) {
2209                                 cfg->exception_message = g_strdup ("pinvoke + vtypes");
2210                                 cfg->disable_llvm = TRUE;
2211                                 return linfo;
2212                         }
2213
2214                         linfo->args [i].storage = LLVMArgVtypeInReg;
2215                         for (j = 0; j < 2; ++j)
2216                                 linfo->args [i].pair_storage [j] = arg_storage_to_llvm_arg_storage (cfg, ainfo->pair_storage [j]);
2217                         break;
2218                 default:
2219                         cfg->exception_message = g_strdup ("ainfo->storage");
2220                         cfg->disable_llvm = TRUE;
2221                         break;
2222                 }
2223         }
2224
2225         return linfo;
2226 }
2227 #endif
2228
2229 void
2230 mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
2231 {
2232         MonoInst *arg, *in;
2233         MonoMethodSignature *sig;
2234         MonoType *sig_ret;
2235         int i, n, stack_size;
2236         CallInfo *cinfo;
2237         ArgInfo *ainfo;
2238
2239         stack_size = 0;
2240
2241         sig = call->signature;
2242         n = sig->param_count + sig->hasthis;
2243
2244         cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
2245
2246         sig_ret = sig->ret;
2247
2248         if (COMPILE_LLVM (cfg)) {
2249                 /* We shouldn't be called in the llvm case */
2250                 cfg->disable_llvm = TRUE;
2251                 return;
2252         }
2253
2254         if (cinfo->need_stack_align) {
2255                 if (!cfg->arch.no_pushes)
2256                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2257         }
2258
2259         /* 
2260          * Emit all arguments which are passed on the stack to prevent register
2261          * allocation problems.
2262          */
2263         if (cfg->arch.no_pushes) {
2264                 for (i = 0; i < n; ++i) {
2265                         MonoType *t;
2266                         ainfo = cinfo->args + i;
2267
2268                         in = call->args [i];
2269
2270                         if (sig->hasthis && i == 0)
2271                                 t = &mono_defaults.object_class->byval_arg;
2272                         else
2273                                 t = sig->params [i - sig->hasthis];
2274
2275                         if (ainfo->storage == ArgOnStack && !MONO_TYPE_ISSTRUCT (t) && !call->tail_call) {
2276                                 if (!t->byref) {
2277                                         if (t->type == MONO_TYPE_R4)
2278                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER4_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2279                                         else if (t->type == MONO_TYPE_R8)
2280                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER8_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2281                                         else
2282                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2283                                 } else {
2284                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, in->dreg);
2285                                 }
2286                                 if (cfg->compute_gc_maps) {
2287                                         MonoInst *def;
2288
2289                                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, t);
2290                                 }
2291                         }
2292                 }
2293         }
2294
2295         /*
2296          * Emit all parameters passed in registers in non-reverse order for better readability
2297          * and to help the optimization in emit_prolog ().
2298          */
2299         for (i = 0; i < n; ++i) {
2300                 ainfo = cinfo->args + i;
2301
2302                 in = call->args [i];
2303
2304                 if (ainfo->storage == ArgInIReg)
2305                         add_outarg_reg (cfg, call, ainfo->storage, ainfo->reg, in);
2306         }
2307
2308         for (i = n - 1; i >= 0; --i) {
2309                 ainfo = cinfo->args + i;
2310
2311                 in = call->args [i];
2312
2313                 switch (ainfo->storage) {
2314                 case ArgInIReg:
2315                         /* Already done */
2316                         break;
2317                 case ArgInFloatSSEReg:
2318                 case ArgInDoubleSSEReg:
2319                         add_outarg_reg (cfg, call, ainfo->storage, ainfo->reg, in);
2320                         break;
2321                 case ArgOnStack:
2322                 case ArgValuetypeInReg:
2323                 case ArgValuetypeAddrInIReg:
2324                         if (ainfo->storage == ArgOnStack && call->tail_call) {
2325                                 MonoInst *call_inst = (MonoInst*)call;
2326                                 cfg->args [i]->flags |= MONO_INST_VOLATILE;
2327                                 EMIT_NEW_ARGSTORE (cfg, call_inst, i, in);
2328                         } else if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
2329                                 guint32 align;
2330                                 guint32 size;
2331
2332                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_TYPEDBYREF) {
2333                                         size = sizeof (MonoTypedRef);
2334                                         align = sizeof (gpointer);
2335                                 }
2336                                 else {
2337                                         if (sig->pinvoke)
2338                                                 size = mono_type_native_stack_size (&in->klass->byval_arg, &align);
2339                                         else {
2340                                                 /* 
2341                                                  * Other backends use mono_type_stack_size (), but that
2342                                                  * aligns the size to 8, which is larger than the size of
2343                                                  * the source, leading to reads of invalid memory if the
2344                                                  * source is at the end of address space.
2345                                                  */
2346                                                 size = mono_class_value_size (in->klass, &align);
2347                                         }
2348                                 }
2349                                 g_assert (in->klass);
2350
2351                                 if (ainfo->storage == ArgOnStack && size >= 10000) {
2352                                         /* Avoid asserts in emit_memcpy () */
2353                                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
2354                                         cfg->exception_message = g_strdup_printf ("Passing an argument of size '%d'.", size);
2355                                         /* Continue normally */
2356                                 }
2357
2358                                 if (size > 0) {
2359                                         MONO_INST_NEW (cfg, arg, OP_OUTARG_VT);
2360                                         arg->sreg1 = in->dreg;
2361                                         arg->klass = in->klass;
2362                                         arg->backend.size = size;
2363                                         arg->inst_p0 = call;
2364                                         arg->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo));
2365                                         memcpy (arg->inst_p1, ainfo, sizeof (ArgInfo));
2366
2367                                         MONO_ADD_INS (cfg->cbb, arg);
2368                                 }
2369                         } else {
2370                                 if (cfg->arch.no_pushes) {
2371                                         /* Already done */
2372                                 } else {
2373                                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2374                                         arg->sreg1 = in->dreg;
2375                                         if (!sig->params [i - sig->hasthis]->byref) {
2376                                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4) {
2377                                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2378                                                         arg->opcode = OP_STORER4_MEMBASE_REG;
2379                                                         arg->inst_destbasereg = X86_ESP;
2380                                                         arg->inst_offset = 0;
2381                                                 } else if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8) {
2382                                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
2383                                                         arg->opcode = OP_STORER8_MEMBASE_REG;
2384                                                         arg->inst_destbasereg = X86_ESP;
2385                                                         arg->inst_offset = 0;
2386                                                 }
2387                                         }
2388                                         MONO_ADD_INS (cfg->cbb, arg);
2389                                 }
2390                         }
2391                         break;
2392                 default:
2393                         g_assert_not_reached ();
2394                 }
2395
2396                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos))
2397                         /* Emit the signature cookie just before the implicit arguments */
2398                         emit_sig_cookie (cfg, call, cinfo);
2399         }
2400
2401         /* Handle the case where there are no implicit arguments */
2402         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sig->sentinelpos))
2403                 emit_sig_cookie (cfg, call, cinfo);
2404
2405         if (sig_ret && MONO_TYPE_ISSTRUCT (sig_ret)) {
2406                 MonoInst *vtarg;
2407
2408                 if (cinfo->ret.storage == ArgValuetypeInReg) {
2409                         if (cinfo->ret.pair_storage [0] == ArgInIReg && cinfo->ret.pair_storage [1] == ArgNone) {
2410                                 /*
2411                                  * Tell the JIT to use a more efficient calling convention: call using
2412                                  * OP_CALL, compute the result location after the call, and save the 
2413                                  * result there.
2414                                  */
2415                                 call->vret_in_reg = TRUE;
2416                                 /* 
2417                                  * Nullify the instruction computing the vret addr to enable 
2418                                  * future optimizations.
2419                                  */
2420                                 if (call->vret_var)
2421                                         NULLIFY_INS (call->vret_var);
2422                         } else {
2423                                 if (call->tail_call)
2424                                         NOT_IMPLEMENTED;
2425                                 /*
2426                                  * The valuetype is in RAX:RDX after the call, need to be copied to
2427                                  * the stack. Push the address here, so the call instruction can
2428                                  * access it.
2429                                  */
2430                                 if (!cfg->arch.vret_addr_loc) {
2431                                         cfg->arch.vret_addr_loc = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2432                                         /* Prevent it from being register allocated or optimized away */
2433                                         ((MonoInst*)cfg->arch.vret_addr_loc)->flags |= MONO_INST_VOLATILE;
2434                                 }
2435
2436                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ((MonoInst*)cfg->arch.vret_addr_loc)->dreg, call->vret_var->dreg);
2437                         }
2438                 }
2439                 else {
2440                         MONO_INST_NEW (cfg, vtarg, OP_MOVE);
2441                         vtarg->sreg1 = call->vret_var->dreg;
2442                         vtarg->dreg = mono_alloc_preg (cfg);
2443                         MONO_ADD_INS (cfg->cbb, vtarg);
2444
2445                         mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->ret.reg, FALSE);
2446                 }
2447         }
2448
2449 #ifdef HOST_WIN32
2450         if (call->inst.opcode != OP_TAILCALL) {
2451                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 0x20);
2452         }
2453 #endif
2454
2455         if (cfg->method->save_lmf) {
2456                 MONO_INST_NEW (cfg, arg, OP_AMD64_SAVE_SP_TO_LMF);
2457                 MONO_ADD_INS (cfg->cbb, arg);
2458         }
2459
2460         call->stack_usage = cinfo->stack_usage;
2461 }
2462
2463 void
2464 mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src)
2465 {
2466         MonoInst *arg;
2467         MonoCallInst *call = (MonoCallInst*)ins->inst_p0;
2468         ArgInfo *ainfo = (ArgInfo*)ins->inst_p1;
2469         int size = ins->backend.size;
2470
2471         if (ainfo->storage == ArgValuetypeInReg) {
2472                 MonoInst *load;
2473                 int part;
2474
2475                 for (part = 0; part < 2; ++part) {
2476                         if (ainfo->pair_storage [part] == ArgNone)
2477                                 continue;
2478
2479                         MONO_INST_NEW (cfg, load, arg_storage_to_load_membase (ainfo->pair_storage [part]));
2480                         load->inst_basereg = src->dreg;
2481                         load->inst_offset = part * sizeof(mgreg_t);
2482
2483                         switch (ainfo->pair_storage [part]) {
2484                         case ArgInIReg:
2485                                 load->dreg = mono_alloc_ireg (cfg);
2486                                 break;
2487                         case ArgInDoubleSSEReg:
2488                         case ArgInFloatSSEReg:
2489                                 load->dreg = mono_alloc_freg (cfg);
2490                                 break;
2491                         default:
2492                                 g_assert_not_reached ();
2493                         }
2494                         MONO_ADD_INS (cfg->cbb, load);
2495
2496                         add_outarg_reg (cfg, call, ainfo->pair_storage [part], ainfo->pair_regs [part], load);
2497                 }
2498         } else if (ainfo->storage == ArgValuetypeAddrInIReg) {
2499                 MonoInst *vtaddr, *load;
2500                 vtaddr = mono_compile_create_var (cfg, &ins->klass->byval_arg, OP_LOCAL);
2501                 
2502                 g_assert (!cfg->arch.no_pushes);
2503
2504                 MONO_INST_NEW (cfg, load, OP_LDADDR);
2505                 cfg->has_indirection = TRUE;
2506                 load->inst_p0 = vtaddr;
2507                 vtaddr->flags |= MONO_INST_INDIRECT;
2508                 load->type = STACK_MP;
2509                 load->klass = vtaddr->klass;
2510                 load->dreg = mono_alloc_ireg (cfg);
2511                 MONO_ADD_INS (cfg->cbb, load);
2512                 mini_emit_memcpy (cfg, load->dreg, 0, src->dreg, 0, size, 4);
2513
2514                 if (ainfo->pair_storage [0] == ArgInIReg) {
2515                         MONO_INST_NEW (cfg, arg, OP_X86_LEA_MEMBASE);
2516                         arg->dreg = mono_alloc_ireg (cfg);
2517                         arg->sreg1 = load->dreg;
2518                         arg->inst_imm = 0;
2519                         MONO_ADD_INS (cfg->cbb, arg);
2520                         mono_call_inst_add_outarg_reg (cfg, call, arg->dreg, ainfo->pair_regs [0], FALSE);
2521                 } else {
2522                         MONO_INST_NEW (cfg, arg, OP_X86_PUSH);
2523                         arg->sreg1 = load->dreg;
2524                         MONO_ADD_INS (cfg->cbb, arg);
2525                 }
2526         } else {
2527                 if (size == 8) {
2528                         if (cfg->arch.no_pushes) {
2529                                 int dreg = mono_alloc_ireg (cfg);
2530
2531                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, 0);
2532                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, AMD64_RSP, ainfo->offset, dreg);
2533                         } else {
2534                                 /* Can't use this for < 8 since it does an 8 byte memory load */
2535                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_MEMBASE);
2536                                 arg->inst_basereg = src->dreg;
2537                                 arg->inst_offset = 0;
2538                                 MONO_ADD_INS (cfg->cbb, arg);
2539                         }
2540                 } else if (size <= 40) {
2541                         if (cfg->arch.no_pushes) {
2542                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2543                         } else {
2544                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, ALIGN_TO (size, 8));
2545                                 mini_emit_memcpy (cfg, X86_ESP, 0, src->dreg, 0, size, 4);
2546                         }
2547                 } else {
2548                         if (cfg->arch.no_pushes) {
2549                                 // FIXME: Code growth
2550                                 mini_emit_memcpy (cfg, AMD64_RSP, ainfo->offset, src->dreg, 0, size, 4);
2551                         } else {
2552                                 MONO_INST_NEW (cfg, arg, OP_X86_PUSH_OBJ);
2553                                 arg->inst_basereg = src->dreg;
2554                                 arg->inst_offset = 0;
2555                                 arg->inst_imm = size;
2556                                 MONO_ADD_INS (cfg->cbb, arg);
2557                         }
2558                 }
2559
2560                 if (cfg->compute_gc_maps) {
2561                         MonoInst *def;
2562                         EMIT_NEW_GC_PARAM_SLOT_LIVENESS_DEF (cfg, def, ainfo->offset, &ins->klass->byval_arg);
2563                 }
2564         }
2565 }
2566
2567 void
2568 mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val)
2569 {
2570         MonoType *ret = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
2571
2572         if (ret->type == MONO_TYPE_R4) {
2573                 if (COMPILE_LLVM (cfg))
2574                         MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2575                 else
2576                         MONO_EMIT_NEW_UNALU (cfg, OP_AMD64_SET_XMMREG_R4, cfg->ret->dreg, val->dreg);
2577                 return;
2578         } else if (ret->type == MONO_TYPE_R8) {
2579                 MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg);
2580                 return;
2581         }
2582                         
2583         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg);
2584 }
2585
2586 #endif /* DISABLE_JIT */
2587
2588 #define EMIT_COND_BRANCH(ins,cond,sign) \
2589         if (ins->inst_true_bb->native_offset) { \
2590                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
2591         } else { \
2592                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
2593                 if ((cfg->opt & MONO_OPT_BRANCH) && \
2594             x86_is_imm8 (ins->inst_true_bb->max_offset - offset)) \
2595                         x86_branch8 (code, cond, 0, sign); \
2596                 else \
2597                         x86_branch32 (code, cond, 0, sign); \
2598 }
2599
2600 typedef struct {
2601         MonoMethodSignature *sig;
2602         CallInfo *cinfo;
2603 } ArchDynCallInfo;
2604
2605 typedef struct {
2606         mgreg_t regs [PARAM_REGS];
2607         mgreg_t res;
2608         guint8 *ret;
2609 } DynCallArgs;
2610
2611 static gboolean
2612 dyn_call_supported (MonoMethodSignature *sig, CallInfo *cinfo)
2613 {
2614         int i;
2615
2616 #ifdef HOST_WIN32
2617         return FALSE;
2618 #endif
2619
2620         switch (cinfo->ret.storage) {
2621         case ArgNone:
2622         case ArgInIReg:
2623                 break;
2624         case ArgValuetypeInReg: {
2625                 ArgInfo *ainfo = &cinfo->ret;
2626
2627                 if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2628                         return FALSE;
2629                 if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2630                         return FALSE;
2631                 break;
2632         }
2633         default:
2634                 return FALSE;
2635         }
2636
2637         for (i = 0; i < cinfo->nargs; ++i) {
2638                 ArgInfo *ainfo = &cinfo->args [i];
2639                 switch (ainfo->storage) {
2640                 case ArgInIReg:
2641                         break;
2642                 case ArgValuetypeInReg:
2643                         if (ainfo->pair_storage [0] != ArgNone && ainfo->pair_storage [0] != ArgInIReg)
2644                                 return FALSE;
2645                         if (ainfo->pair_storage [1] != ArgNone && ainfo->pair_storage [1] != ArgInIReg)
2646                                 return FALSE;
2647                         break;
2648                 default:
2649                         return FALSE;
2650                 }
2651         }
2652
2653         return TRUE;
2654 }
2655
2656 /*
2657  * mono_arch_dyn_call_prepare:
2658  *
2659  *   Return a pointer to an arch-specific structure which contains information 
2660  * needed by mono_arch_get_dyn_call_args (). Return NULL if OP_DYN_CALL is not
2661  * supported for SIG.
2662  * This function is equivalent to ffi_prep_cif in libffi.
2663  */
2664 MonoDynCallInfo*
2665 mono_arch_dyn_call_prepare (MonoMethodSignature *sig)
2666 {
2667         ArchDynCallInfo *info;
2668         CallInfo *cinfo;
2669
2670         cinfo = get_call_info (NULL, NULL, sig);
2671
2672         if (!dyn_call_supported (sig, cinfo)) {
2673                 g_free (cinfo);
2674                 return NULL;
2675         }
2676
2677         info = g_new0 (ArchDynCallInfo, 1);
2678         // FIXME: Preprocess the info to speed up get_dyn_call_args ().
2679         info->sig = sig;
2680         info->cinfo = cinfo;
2681         
2682         return (MonoDynCallInfo*)info;
2683 }
2684
2685 /*
2686  * mono_arch_dyn_call_free:
2687  *
2688  *   Free a MonoDynCallInfo structure.
2689  */
2690 void
2691 mono_arch_dyn_call_free (MonoDynCallInfo *info)
2692 {
2693         ArchDynCallInfo *ainfo = (ArchDynCallInfo*)info;
2694
2695         g_free (ainfo->cinfo);
2696         g_free (ainfo);
2697 }
2698
2699 #if !defined(__native_client__)
2700 #define PTR_TO_GREG(ptr) (mgreg_t)(ptr)
2701 #define GREG_TO_PTR(greg) (gpointer)(greg)
2702 #else
2703 /* Correctly handle casts to/from 32-bit pointers without compiler warnings */
2704 #define PTR_TO_GREG(ptr) (mgreg_t)(uintptr_t)(ptr)
2705 #define GREG_TO_PTR(greg) (gpointer)(guint32)(greg)
2706 #endif
2707
2708 /*
2709  * mono_arch_get_start_dyn_call:
2710  *
2711  *   Convert the arguments ARGS to a format which can be passed to OP_DYN_CALL, and
2712  * store the result into BUF.
2713  * ARGS should be an array of pointers pointing to the arguments.
2714  * RET should point to a memory buffer large enought to hold the result of the
2715  * call.
2716  * This function should be as fast as possible, any work which does not depend
2717  * on the actual values of the arguments should be done in 
2718  * mono_arch_dyn_call_prepare ().
2719  * start_dyn_call + OP_DYN_CALL + finish_dyn_call is equivalent to ffi_call in
2720  * libffi.
2721  */
2722 void
2723 mono_arch_start_dyn_call (MonoDynCallInfo *info, gpointer **args, guint8 *ret, guint8 *buf, int buf_len)
2724 {
2725         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2726         DynCallArgs *p = (DynCallArgs*)buf;
2727         int arg_index, greg, i, pindex;
2728         MonoMethodSignature *sig = dinfo->sig;
2729
2730         g_assert (buf_len >= sizeof (DynCallArgs));
2731
2732         p->res = 0;
2733         p->ret = ret;
2734
2735         arg_index = 0;
2736         greg = 0;
2737         pindex = 0;
2738
2739         if (sig->hasthis || dinfo->cinfo->vret_arg_index == 1) {
2740                 p->regs [greg ++] = PTR_TO_GREG(*(args [arg_index ++]));
2741                 if (!sig->hasthis)
2742                         pindex = 1;
2743         }
2744
2745         if (dinfo->cinfo->vtype_retaddr)
2746                 p->regs [greg ++] = PTR_TO_GREG(ret);
2747
2748         for (i = pindex; i < sig->param_count; i++) {
2749                 MonoType *t = mono_type_get_underlying_type (sig->params [i]);
2750                 gpointer *arg = args [arg_index ++];
2751
2752                 if (t->byref) {
2753                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2754                         continue;
2755                 }
2756
2757                 switch (t->type) {
2758                 case MONO_TYPE_STRING:
2759                 case MONO_TYPE_CLASS:  
2760                 case MONO_TYPE_ARRAY:
2761                 case MONO_TYPE_SZARRAY:
2762                 case MONO_TYPE_OBJECT:
2763                 case MONO_TYPE_PTR:
2764                 case MONO_TYPE_I:
2765                 case MONO_TYPE_U:
2766 #if !defined(__mono_ilp32__)
2767                 case MONO_TYPE_I8:
2768                 case MONO_TYPE_U8:
2769 #endif
2770                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2771                         p->regs [greg ++] = PTR_TO_GREG(*(arg));
2772                         break;
2773 #if defined(__mono_ilp32__)
2774                 case MONO_TYPE_I8:
2775                 case MONO_TYPE_U8:
2776                         g_assert (dinfo->cinfo->args [i + sig->hasthis].reg == param_regs [greg]);
2777                         p->regs [greg ++] = *(guint64*)(arg);
2778                         break;
2779 #endif
2780                 case MONO_TYPE_BOOLEAN:
2781                 case MONO_TYPE_U1:
2782                         p->regs [greg ++] = *(guint8*)(arg);
2783                         break;
2784                 case MONO_TYPE_I1:
2785                         p->regs [greg ++] = *(gint8*)(arg);
2786                         break;
2787                 case MONO_TYPE_I2:
2788                         p->regs [greg ++] = *(gint16*)(arg);
2789                         break;
2790                 case MONO_TYPE_U2:
2791                 case MONO_TYPE_CHAR:
2792                         p->regs [greg ++] = *(guint16*)(arg);
2793                         break;
2794                 case MONO_TYPE_I4:
2795                         p->regs [greg ++] = *(gint32*)(arg);
2796                         break;
2797                 case MONO_TYPE_U4:
2798                         p->regs [greg ++] = *(guint32*)(arg);
2799                         break;
2800                 case MONO_TYPE_GENERICINST:
2801                     if (MONO_TYPE_IS_REFERENCE (t)) {
2802                                 p->regs [greg ++] = PTR_TO_GREG(*(arg));
2803                                 break;
2804                         } else {
2805                                 /* Fall through */
2806                         }
2807                 case MONO_TYPE_VALUETYPE: {
2808                         ArgInfo *ainfo = &dinfo->cinfo->args [i + sig->hasthis];
2809
2810                         g_assert (ainfo->storage == ArgValuetypeInReg);
2811                         if (ainfo->pair_storage [0] != ArgNone) {
2812                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2813                                 p->regs [greg ++] = ((mgreg_t*)(arg))[0];
2814                         }
2815                         if (ainfo->pair_storage [1] != ArgNone) {
2816                                 g_assert (ainfo->pair_storage [1] == ArgInIReg);
2817                                 p->regs [greg ++] = ((mgreg_t*)(arg))[1];
2818                         }
2819                         break;
2820                 }
2821                 default:
2822                         g_assert_not_reached ();
2823                 }
2824         }
2825
2826         g_assert (greg <= PARAM_REGS);
2827 }
2828
2829 /*
2830  * mono_arch_finish_dyn_call:
2831  *
2832  *   Store the result of a dyn call into the return value buffer passed to
2833  * start_dyn_call ().
2834  * This function should be as fast as possible, any work which does not depend
2835  * on the actual values of the arguments should be done in 
2836  * mono_arch_dyn_call_prepare ().
2837  */
2838 void
2839 mono_arch_finish_dyn_call (MonoDynCallInfo *info, guint8 *buf)
2840 {
2841         ArchDynCallInfo *dinfo = (ArchDynCallInfo*)info;
2842         MonoMethodSignature *sig = dinfo->sig;
2843         guint8 *ret = ((DynCallArgs*)buf)->ret;
2844         mgreg_t res = ((DynCallArgs*)buf)->res;
2845         MonoType *sig_ret = mono_type_get_underlying_type (sig->ret);
2846
2847         switch (sig_ret->type) {
2848         case MONO_TYPE_VOID:
2849                 *(gpointer*)ret = NULL;
2850                 break;
2851         case MONO_TYPE_STRING:
2852         case MONO_TYPE_CLASS:  
2853         case MONO_TYPE_ARRAY:
2854         case MONO_TYPE_SZARRAY:
2855         case MONO_TYPE_OBJECT:
2856         case MONO_TYPE_I:
2857         case MONO_TYPE_U:
2858         case MONO_TYPE_PTR:
2859                 *(gpointer*)ret = GREG_TO_PTR(res);
2860                 break;
2861         case MONO_TYPE_I1:
2862                 *(gint8*)ret = res;
2863                 break;
2864         case MONO_TYPE_U1:
2865         case MONO_TYPE_BOOLEAN:
2866                 *(guint8*)ret = res;
2867                 break;
2868         case MONO_TYPE_I2:
2869                 *(gint16*)ret = res;
2870                 break;
2871         case MONO_TYPE_U2:
2872         case MONO_TYPE_CHAR:
2873                 *(guint16*)ret = res;
2874                 break;
2875         case MONO_TYPE_I4:
2876                 *(gint32*)ret = res;
2877                 break;
2878         case MONO_TYPE_U4:
2879                 *(guint32*)ret = res;
2880                 break;
2881         case MONO_TYPE_I8:
2882                 *(gint64*)ret = res;
2883                 break;
2884         case MONO_TYPE_U8:
2885                 *(guint64*)ret = res;
2886                 break;
2887         case MONO_TYPE_GENERICINST:
2888                 if (MONO_TYPE_IS_REFERENCE (sig_ret)) {
2889                         *(gpointer*)ret = GREG_TO_PTR(res);
2890                         break;
2891                 } else {
2892                         /* Fall through */
2893                 }
2894         case MONO_TYPE_VALUETYPE:
2895                 if (dinfo->cinfo->vtype_retaddr) {
2896                         /* Nothing to do */
2897                 } else {
2898                         ArgInfo *ainfo = &dinfo->cinfo->ret;
2899
2900                         g_assert (ainfo->storage == ArgValuetypeInReg);
2901
2902                         if (ainfo->pair_storage [0] != ArgNone) {
2903                                 g_assert (ainfo->pair_storage [0] == ArgInIReg);
2904                                 ((mgreg_t*)ret)[0] = res;
2905                         }
2906
2907                         g_assert (ainfo->pair_storage [1] == ArgNone);
2908                 }
2909                 break;
2910         default:
2911                 g_assert_not_reached ();
2912         }
2913 }
2914
2915 /* emit an exception if condition is fail */
2916 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
2917         do {                                                        \
2918                 MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \
2919                 if (tins == NULL) {                                                                             \
2920                         mono_add_patch_info (cfg, code - cfg->native_code,   \
2921                                         MONO_PATCH_INFO_EXC, exc_name);  \
2922                         x86_branch32 (code, cond, 0, signed);               \
2923                 } else {        \
2924                         EMIT_COND_BRANCH (tins, cond, signed);  \
2925                 }                       \
2926         } while (0); 
2927
2928 #define EMIT_FPCOMPARE(code) do { \
2929         amd64_fcompp (code); \
2930         amd64_fnstsw (code); \
2931 } while (0); 
2932
2933 #define EMIT_SSE2_FPFUNC(code, op, dreg, sreg1) do { \
2934     amd64_movsd_membase_reg (code, AMD64_RSP, -8, (sreg1)); \
2935         amd64_fld_membase (code, AMD64_RSP, -8, TRUE); \
2936         amd64_ ##op (code); \
2937         amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE); \
2938         amd64_movsd_reg_membase (code, (dreg), AMD64_RSP, -8); \
2939 } while (0);
2940
2941 static guint8*
2942 emit_call_body (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
2943 {
2944         gboolean no_patch = FALSE;
2945
2946         /* 
2947          * FIXME: Add support for thunks
2948          */
2949         {
2950                 gboolean near_call = FALSE;
2951
2952                 /*
2953                  * Indirect calls are expensive so try to make a near call if possible.
2954                  * The caller memory is allocated by the code manager so it is 
2955                  * guaranteed to be at a 32 bit offset.
2956                  */
2957
2958                 if (patch_type != MONO_PATCH_INFO_ABS) {
2959                         /* The target is in memory allocated using the code manager */
2960                         near_call = TRUE;
2961
2962                         if ((patch_type == MONO_PATCH_INFO_METHOD) || (patch_type == MONO_PATCH_INFO_METHOD_JUMP)) {
2963                                 if (((MonoMethod*)data)->klass->image->aot_module)
2964                                         /* The callee might be an AOT method */
2965                                         near_call = FALSE;
2966                                 if (((MonoMethod*)data)->dynamic)
2967                                         /* The target is in malloc-ed memory */
2968                                         near_call = FALSE;
2969                         }
2970
2971                         if (patch_type == MONO_PATCH_INFO_INTERNAL_METHOD) {
2972                                 /* 
2973                                  * The call might go directly to a native function without
2974                                  * the wrapper.
2975                                  */
2976                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (data);
2977                                 if (mi) {
2978                                         gconstpointer target = mono_icall_get_wrapper (mi);
2979                                         if ((((guint64)target) >> 32) != 0)
2980                                                 near_call = FALSE;
2981                                 }
2982                         }
2983                 }
2984                 else {
2985                         MonoJumpInfo *jinfo = NULL;
2986
2987                         if (cfg->abs_patches)
2988                                 jinfo = g_hash_table_lookup (cfg->abs_patches, data);
2989                         if (jinfo) {
2990                                 if (jinfo->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
2991                                         MonoJitICallInfo *mi = mono_find_jit_icall_by_name (jinfo->data.name);
2992                                         if (mi && (((guint64)mi->func) >> 32) == 0)
2993                                                 near_call = TRUE;
2994                                         no_patch = TRUE;
2995                                 } else {
2996                                         /* 
2997                                          * This is not really an optimization, but required because the
2998                                          * generic class init trampolines use R11 to pass the vtable.
2999                                          */
3000                                         near_call = TRUE;
3001                                 }
3002                         } else {
3003                                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (data);
3004                                 if (info) {
3005                                         if (info->func == info->wrapper) {
3006                                                 /* No wrapper */
3007                                                 if ((((guint64)info->func) >> 32) == 0)
3008                                                         near_call = TRUE;
3009                                         }
3010                                         else {
3011                                                 /* See the comment in mono_codegen () */
3012                                                 if ((info->name [0] != 'v') || (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL))
3013                                                         near_call = TRUE;
3014                                         }
3015                                 }
3016                                 else if ((((guint64)data) >> 32) == 0) {
3017                                         near_call = TRUE;
3018                                         no_patch = TRUE;
3019                                 }
3020                         }
3021                 }
3022
3023                 if (cfg->method->dynamic)
3024                         /* These methods are allocated using malloc */
3025                         near_call = FALSE;
3026
3027 #ifdef MONO_ARCH_NOMAP32BIT
3028                 near_call = FALSE;
3029 #endif
3030 #if defined(__native_client__)
3031                 /* Always use near_call == TRUE for Native Client */
3032                 near_call = TRUE;
3033 #endif
3034                 /* The 64bit XEN kernel does not honour the MAP_32BIT flag. (#522894) */
3035                 if (optimize_for_xen)
3036                         near_call = FALSE;
3037
3038                 if (cfg->compile_aot) {
3039                         near_call = TRUE;
3040                         no_patch = TRUE;
3041                 }
3042
3043                 if (near_call) {
3044                         /* 
3045                          * Align the call displacement to an address divisible by 4 so it does
3046                          * not span cache lines. This is required for code patching to work on SMP
3047                          * systems.
3048                          */
3049                         if (!no_patch && ((guint32)(code + 1 - cfg->native_code) % 4) != 0) {
3050                                 guint32 pad_size = 4 - ((guint32)(code + 1 - cfg->native_code) % 4);
3051                                 amd64_padding (code, pad_size);
3052                         }
3053                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3054                         amd64_call_code (code, 0);
3055                 }
3056                 else {
3057                         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
3058                         amd64_set_reg_template (code, GP_SCRATCH_REG);
3059                         amd64_call_reg (code, GP_SCRATCH_REG);
3060                 }
3061         }
3062
3063         return code;
3064 }
3065
3066 static inline guint8*
3067 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data, gboolean win64_adjust_stack)
3068 {
3069 #ifdef HOST_WIN32
3070         if (win64_adjust_stack)
3071                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 32);
3072 #endif
3073         code = emit_call_body (cfg, code, patch_type, data);
3074 #ifdef HOST_WIN32
3075         if (win64_adjust_stack)
3076                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 32);
3077 #endif  
3078         
3079         return code;
3080 }
3081
3082 static inline int
3083 store_membase_imm_to_store_membase_reg (int opcode)
3084 {
3085         switch (opcode) {
3086         case OP_STORE_MEMBASE_IMM:
3087                 return OP_STORE_MEMBASE_REG;
3088         case OP_STOREI4_MEMBASE_IMM:
3089                 return OP_STOREI4_MEMBASE_REG;
3090         case OP_STOREI8_MEMBASE_IMM:
3091                 return OP_STOREI8_MEMBASE_REG;
3092         }
3093
3094         return -1;
3095 }
3096
3097 #ifndef DISABLE_JIT
3098
3099 #define INST_IGNORES_CFLAGS(opcode) (!(((opcode) == OP_ADC) || ((opcode) == OP_ADC_IMM) || ((opcode) == OP_IADC) || ((opcode) == OP_IADC_IMM) || ((opcode) == OP_SBB) || ((opcode) == OP_SBB_IMM) || ((opcode) == OP_ISBB) || ((opcode) == OP_ISBB_IMM)))
3100
3101 /*
3102  * mono_arch_peephole_pass_1:
3103  *
3104  *   Perform peephole opts which should/can be performed before local regalloc
3105  */
3106 void
3107 mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
3108 {
3109         MonoInst *ins, *n;
3110
3111         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3112                 MonoInst *last_ins = ins->prev;
3113
3114                 switch (ins->opcode) {
3115                 case OP_ADD_IMM:
3116                 case OP_IADD_IMM:
3117                 case OP_LADD_IMM:
3118                         if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS) && (ins->inst_imm > 0)) {
3119                                 /* 
3120                                  * X86_LEA is like ADD, but doesn't have the
3121                                  * sreg1==dreg restriction. inst_imm > 0 is needed since LEA sign-extends 
3122                                  * its operand to 64 bit.
3123                                  */
3124                                 ins->opcode = OP_X86_LEA_MEMBASE;
3125                                 ins->inst_basereg = ins->sreg1;
3126                         }
3127                         break;
3128                 case OP_LXOR:
3129                 case OP_IXOR:
3130                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3131                                 MonoInst *ins2;
3132
3133                                 /* 
3134                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3135                                  * the latter has length 2-3 instead of 6 (reverse constant
3136                                  * propagation). These instruction sequences are very common
3137                                  * in the initlocals bblock.
3138                                  */
3139                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3140                                         if (((ins2->opcode == OP_STORE_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_IMM) || (ins2->opcode == OP_STOREI8_MEMBASE_IMM) || (ins2->opcode == OP_STORE_MEMBASE_IMM)) && (ins2->inst_imm == 0)) {
3141                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3142                                                 ins2->sreg1 = ins->dreg;
3143                                         } else if ((ins2->opcode == OP_STOREI1_MEMBASE_IMM) || (ins2->opcode == OP_STOREI2_MEMBASE_IMM) || (ins2->opcode == OP_STOREI8_MEMBASE_REG) || (ins2->opcode == OP_STORE_MEMBASE_REG)) {
3144                                                 /* Continue */
3145                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3146                                                 NULLIFY_INS (ins2);
3147                                                 /* Continue */
3148                                         } else {
3149                                                 break;
3150                                         }
3151                                 }
3152                         }
3153                         break;
3154                 case OP_COMPARE_IMM:
3155                 case OP_LCOMPARE_IMM:
3156                         /* OP_COMPARE_IMM (reg, 0) 
3157                          * --> 
3158                          * OP_AMD64_TEST_NULL (reg) 
3159                          */
3160                         if (!ins->inst_imm)
3161                                 ins->opcode = OP_AMD64_TEST_NULL;
3162                         break;
3163                 case OP_ICOMPARE_IMM:
3164                         if (!ins->inst_imm)
3165                                 ins->opcode = OP_X86_TEST_NULL;
3166                         break;
3167                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
3168                         /* 
3169                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3170                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
3171                          * -->
3172                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
3173                          * OP_COMPARE_IMM reg, imm
3174                          *
3175                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
3176                          */
3177                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
3178                             ins->inst_basereg == last_ins->inst_destbasereg &&
3179                             ins->inst_offset == last_ins->inst_offset) {
3180                                         ins->opcode = OP_ICOMPARE_IMM;
3181                                         ins->sreg1 = last_ins->sreg1;
3182
3183                                         /* check if we can remove cmp reg,0 with test null */
3184                                         if (!ins->inst_imm)
3185                                                 ins->opcode = OP_X86_TEST_NULL;
3186                                 }
3187
3188                         break;
3189                 }
3190
3191                 mono_peephole_ins (bb, ins);
3192         }
3193 }
3194
3195 void
3196 mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
3197 {
3198         MonoInst *ins, *n;
3199
3200         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3201                 switch (ins->opcode) {
3202                 case OP_ICONST:
3203                 case OP_I8CONST: {
3204                         /* reg = 0 -> XOR (reg, reg) */
3205                         /* XOR sets cflags on x86, so we cant do it always */
3206                         if (ins->inst_c0 == 0 && (!ins->next || (ins->next && INST_IGNORES_CFLAGS (ins->next->opcode)))) {
3207                                 ins->opcode = OP_LXOR;
3208                                 ins->sreg1 = ins->dreg;
3209                                 ins->sreg2 = ins->dreg;
3210                                 /* Fall through */
3211                         } else {
3212                                 break;
3213                         }
3214                 }
3215                 case OP_LXOR:
3216                         /*
3217                          * Use IXOR to avoid a rex prefix if possible. The cpu will sign extend the 
3218                          * 0 result into 64 bits.
3219                          */
3220                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3221                                 ins->opcode = OP_IXOR;
3222                         }
3223                         /* Fall through */
3224                 case OP_IXOR:
3225                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
3226                                 MonoInst *ins2;
3227
3228                                 /* 
3229                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
3230                                  * the latter has length 2-3 instead of 6 (reverse constant
3231                                  * propagation). These instruction sequences are very common
3232                                  * in the initlocals bblock.
3233                                  */
3234                                 for (ins2 = ins->next; ins2; ins2 = ins2->next) {
3235                                         if (((ins2->opcode == OP_STORE_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_IMM) || (ins2->opcode == OP_STOREI8_MEMBASE_IMM) || (ins2->opcode == OP_STORE_MEMBASE_IMM)) && (ins2->inst_imm == 0)) {
3236                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
3237                                                 ins2->sreg1 = ins->dreg;
3238                                         } else if ((ins2->opcode == OP_STOREI1_MEMBASE_IMM) || (ins2->opcode == OP_STOREI2_MEMBASE_IMM) || (ins2->opcode == OP_STOREI4_MEMBASE_REG) || (ins2->opcode == OP_STOREI8_MEMBASE_REG) || (ins2->opcode == OP_STORE_MEMBASE_REG) || (ins2->opcode == OP_LIVERANGE_START) || (ins2->opcode == OP_GC_LIVENESS_DEF) || (ins2->opcode == OP_GC_LIVENESS_USE)) {
3239                                                 /* Continue */
3240                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
3241                                                 NULLIFY_INS (ins2);
3242                                                 /* Continue */
3243                                         } else {
3244                                                 break;
3245                                         }
3246                                 }
3247                         }
3248                         break;
3249                 case OP_IADD_IMM:
3250                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3251                                 ins->opcode = OP_X86_INC_REG;
3252                         break;
3253                 case OP_ISUB_IMM:
3254                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
3255                                 ins->opcode = OP_X86_DEC_REG;
3256                         break;
3257                 }
3258
3259                 mono_peephole_ins (bb, ins);
3260         }
3261 }
3262
3263 #define NEW_INS(cfg,ins,dest,op) do {   \
3264                 MONO_INST_NEW ((cfg), (dest), (op)); \
3265         (dest)->cil_code = (ins)->cil_code; \
3266         mono_bblock_insert_before_ins (bb, ins, (dest)); \
3267         } while (0)
3268
3269 /*
3270  * mono_arch_lowering_pass:
3271  *
3272  *  Converts complex opcodes into simpler ones so that each IR instruction
3273  * corresponds to one machine instruction.
3274  */
3275 void
3276 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
3277 {
3278         MonoInst *ins, *n, *temp;
3279
3280         /*
3281          * FIXME: Need to add more instructions, but the current machine 
3282          * description can't model some parts of the composite instructions like
3283          * cdq.
3284          */
3285         MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
3286                 switch (ins->opcode) {
3287                 case OP_DIV_IMM:
3288                 case OP_REM_IMM:
3289                 case OP_IDIV_IMM:
3290                 case OP_IDIV_UN_IMM:
3291                 case OP_IREM_UN_IMM:
3292                         mono_decompose_op_imm (cfg, bb, ins);
3293                         break;
3294                 case OP_IREM_IMM:
3295                         /* Keep the opcode if we can implement it efficiently */
3296                         if (!((ins->inst_imm > 0) && (mono_is_power_of_two (ins->inst_imm) != -1)))
3297                                 mono_decompose_op_imm (cfg, bb, ins);
3298                         break;
3299                 case OP_COMPARE_IMM:
3300                 case OP_LCOMPARE_IMM:
3301                         if (!amd64_is_imm32 (ins->inst_imm)) {
3302                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3303                                 temp->inst_c0 = ins->inst_imm;
3304                                 temp->dreg = mono_alloc_ireg (cfg);
3305                                 ins->opcode = OP_COMPARE;
3306                                 ins->sreg2 = temp->dreg;
3307                         }
3308                         break;
3309 #ifndef __mono_ilp32__
3310                 case OP_LOAD_MEMBASE:
3311 #endif
3312                 case OP_LOADI8_MEMBASE:
3313 #ifndef __native_client_codegen__
3314                 /*  Don't generate memindex opcodes (to simplify */
3315                 /*  read sandboxing) */
3316                         if (!amd64_is_imm32 (ins->inst_offset)) {
3317                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3318                                 temp->inst_c0 = ins->inst_offset;
3319                                 temp->dreg = mono_alloc_ireg (cfg);
3320                                 ins->opcode = OP_AMD64_LOADI8_MEMINDEX;
3321                                 ins->inst_indexreg = temp->dreg;
3322                         }
3323 #endif
3324                         break;
3325 #ifndef __mono_ilp32__
3326                 case OP_STORE_MEMBASE_IMM:
3327 #endif
3328                 case OP_STOREI8_MEMBASE_IMM:
3329                         if (!amd64_is_imm32 (ins->inst_imm)) {
3330                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
3331                                 temp->inst_c0 = ins->inst_imm;
3332                                 temp->dreg = mono_alloc_ireg (cfg);
3333                                 ins->opcode = OP_STOREI8_MEMBASE_REG;
3334                                 ins->sreg1 = temp->dreg;
3335                         }
3336                         break;
3337 #ifdef MONO_ARCH_SIMD_INTRINSICS
3338                 case OP_EXPAND_I1: {
3339                                 int temp_reg1 = mono_alloc_ireg (cfg);
3340                                 int temp_reg2 = mono_alloc_ireg (cfg);
3341                                 int original_reg = ins->sreg1;
3342
3343                                 NEW_INS (cfg, ins, temp, OP_ICONV_TO_U1);
3344                                 temp->sreg1 = original_reg;
3345                                 temp->dreg = temp_reg1;
3346
3347                                 NEW_INS (cfg, ins, temp, OP_SHL_IMM);
3348                                 temp->sreg1 = temp_reg1;
3349                                 temp->dreg = temp_reg2;
3350                                 temp->inst_imm = 8;
3351
3352                                 NEW_INS (cfg, ins, temp, OP_LOR);
3353                                 temp->sreg1 = temp->dreg = temp_reg2;
3354                                 temp->sreg2 = temp_reg1;
3355
3356                                 ins->opcode = OP_EXPAND_I2;
3357                                 ins->sreg1 = temp_reg2;
3358                         }
3359                         break;
3360 #endif
3361                 default:
3362                         break;
3363                 }
3364         }
3365
3366         bb->max_vreg = cfg->next_vreg;
3367 }
3368
3369 static const int 
3370 branch_cc_table [] = {
3371         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3372         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
3373         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
3374 };
3375
3376 /* Maps CMP_... constants to X86_CC_... constants */
3377 static const int
3378 cc_table [] = {
3379         X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT,
3380         X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT
3381 };
3382
3383 static const int
3384 cc_signed_table [] = {
3385         TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
3386         FALSE, FALSE, FALSE, FALSE
3387 };
3388
3389 /*#include "cprop.c"*/
3390
3391 static unsigned char*
3392 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed)
3393 {
3394         amd64_sse_cvttsd2si_reg_reg (code, dreg, sreg);
3395
3396         if (size == 1)
3397                 amd64_widen_reg (code, dreg, dreg, is_signed, FALSE);
3398         else if (size == 2)
3399                 amd64_widen_reg (code, dreg, dreg, is_signed, TRUE);
3400         return code;
3401 }
3402
3403 static unsigned char*
3404 mono_emit_stack_alloc (MonoCompile *cfg, guchar *code, MonoInst* tree)
3405 {
3406         int sreg = tree->sreg1;
3407         int need_touch = FALSE;
3408
3409 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
3410         if (!tree->flags & MONO_INST_INIT)
3411                 need_touch = TRUE;
3412 #endif
3413
3414         if (need_touch) {
3415                 guint8* br[5];
3416
3417                 /*
3418                  * Under Windows:
3419                  * If requested stack size is larger than one page,
3420                  * perform stack-touch operation
3421                  */
3422                 /*
3423                  * Generate stack probe code.
3424                  * Under Windows, it is necessary to allocate one page at a time,
3425                  * "touching" stack after each successful sub-allocation. This is
3426                  * because of the way stack growth is implemented - there is a
3427                  * guard page before the lowest stack page that is currently commited.
3428                  * Stack normally grows sequentially so OS traps access to the
3429                  * guard page and commits more pages when needed.
3430                  */
3431                 amd64_test_reg_imm (code, sreg, ~0xFFF);
3432                 br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3433
3434                 br[2] = code; /* loop */
3435                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
3436                 amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
3437                 amd64_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
3438                 amd64_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
3439                 br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
3440                 amd64_patch (br[3], br[2]);
3441                 amd64_test_reg_reg (code, sreg, sreg);
3442                 br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
3443                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3444
3445                 br[1] = code; x86_jump8 (code, 0);
3446
3447                 amd64_patch (br[0], code);
3448                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
3449                 amd64_patch (br[1], code);
3450                 amd64_patch (br[4], code);
3451         }
3452         else
3453                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, tree->sreg1);
3454
3455         if (tree->flags & MONO_INST_INIT) {
3456                 int offset = 0;
3457                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX) {
3458                         amd64_push_reg (code, AMD64_RAX);
3459                         offset += 8;
3460                 }
3461                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX) {
3462                         amd64_push_reg (code, AMD64_RCX);
3463                         offset += 8;
3464                 }
3465                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI) {
3466                         amd64_push_reg (code, AMD64_RDI);
3467                         offset += 8;
3468                 }
3469                 
3470                 amd64_shift_reg_imm (code, X86_SHR, sreg, 3);
3471                 if (sreg != AMD64_RCX)
3472                         amd64_mov_reg_reg (code, AMD64_RCX, sreg, 8);
3473                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3474                                 
3475                 amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, offset);
3476                 if (cfg->param_area && cfg->arch.no_pushes)
3477                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RDI, cfg->param_area);
3478                 amd64_cld (code);
3479 #if defined(__default_codegen__)
3480                 amd64_prefix (code, X86_REP_PREFIX);
3481                 amd64_stosl (code);
3482 #elif defined(__native_client_codegen__)
3483                 /* NaCl stos pseudo-instruction */
3484                 amd64_codegen_pre(code);
3485                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
3486                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
3487                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
3488                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
3489                 amd64_prefix (code, X86_REP_PREFIX);
3490                 amd64_stosl (code);
3491                 amd64_codegen_post(code);
3492 #endif /* __native_client_codegen__ */
3493                 
3494                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI)
3495                         amd64_pop_reg (code, AMD64_RDI);
3496                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX)
3497                         amd64_pop_reg (code, AMD64_RCX);
3498                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX)
3499                         amd64_pop_reg (code, AMD64_RAX);
3500         }
3501         return code;
3502 }
3503
3504 static guint8*
3505 emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
3506 {
3507         CallInfo *cinfo;
3508         guint32 quad;
3509
3510         /* Move return value to the target register */
3511         /* FIXME: do this in the local reg allocator */
3512         switch (ins->opcode) {
3513         case OP_CALL:
3514         case OP_CALL_REG:
3515         case OP_CALL_MEMBASE:
3516         case OP_LCALL:
3517         case OP_LCALL_REG:
3518         case OP_LCALL_MEMBASE:
3519                 g_assert (ins->dreg == AMD64_RAX);
3520                 break;
3521         case OP_FCALL:
3522         case OP_FCALL_REG:
3523         case OP_FCALL_MEMBASE:
3524                 if (((MonoCallInst*)ins)->signature->ret->type == MONO_TYPE_R4) {
3525                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, AMD64_XMM0);
3526                 }
3527                 else {
3528                         if (ins->dreg != AMD64_XMM0)
3529                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM0);
3530                 }
3531                 break;
3532         case OP_VCALL:
3533         case OP_VCALL_REG:
3534         case OP_VCALL_MEMBASE:
3535         case OP_VCALL2:
3536         case OP_VCALL2_REG:
3537         case OP_VCALL2_MEMBASE:
3538                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, ((MonoCallInst*)ins)->signature);
3539                 if (cinfo->ret.storage == ArgValuetypeInReg) {
3540                         MonoInst *loc = cfg->arch.vret_addr_loc;
3541
3542                         /* Load the destination address */
3543                         g_assert (loc->opcode == OP_REGOFFSET);
3544                         amd64_mov_reg_membase (code, AMD64_RCX, loc->inst_basereg, loc->inst_offset, sizeof(gpointer));
3545
3546                         for (quad = 0; quad < 2; quad ++) {
3547                                 switch (cinfo->ret.pair_storage [quad]) {
3548                                 case ArgInIReg:
3549                                         amd64_mov_membase_reg (code, AMD64_RCX, (quad * sizeof(mgreg_t)), cinfo->ret.pair_regs [quad], sizeof(mgreg_t));
3550                                         break;
3551                                 case ArgInFloatSSEReg:
3552                                         amd64_movss_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3553                                         break;
3554                                 case ArgInDoubleSSEReg:
3555                                         amd64_movsd_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
3556                                         break;
3557                                 case ArgNone:
3558                                         break;
3559                                 default:
3560                                         NOT_IMPLEMENTED;
3561                                 }
3562                         }
3563                 }
3564                 break;
3565         }
3566
3567         return code;
3568 }
3569
3570 #endif /* DISABLE_JIT */
3571
3572 #ifdef __APPLE__
3573 static int tls_gs_offset;
3574 #endif
3575
3576 gboolean
3577 mono_amd64_have_tls_get (void)
3578 {
3579 #ifdef __APPLE__
3580         static gboolean have_tls_get = FALSE;
3581         static gboolean inited = FALSE;
3582         guint8 *ins;
3583
3584         if (inited)
3585                 return have_tls_get;
3586
3587         ins = (guint8*)pthread_getspecific;
3588
3589         /*
3590          * We're looking for these two instructions:
3591          *
3592          * mov    %gs:[offset](,%rdi,8),%rax
3593          * retq
3594          */
3595         have_tls_get = ins [0] == 0x65 &&
3596                        ins [1] == 0x48 &&
3597                        ins [2] == 0x8b &&
3598                        ins [3] == 0x04 &&
3599                        ins [4] == 0xfd &&
3600                        ins [6] == 0x00 &&
3601                        ins [7] == 0x00 &&
3602                        ins [8] == 0x00 &&
3603                        ins [9] == 0xc3;
3604
3605         inited = TRUE;
3606
3607         tls_gs_offset = ins[5];
3608
3609         return have_tls_get;
3610 #else
3611         return TRUE;
3612 #endif
3613 }
3614
3615 /*
3616  * mono_amd64_emit_tls_get:
3617  * @code: buffer to store code to
3618  * @dreg: hard register where to place the result
3619  * @tls_offset: offset info
3620  *
3621  * mono_amd64_emit_tls_get emits in @code the native code that puts in
3622  * the dreg register the item in the thread local storage identified
3623  * by tls_offset.
3624  *
3625  * Returns: a pointer to the end of the stored code
3626  */
3627 guint8*
3628 mono_amd64_emit_tls_get (guint8* code, int dreg, int tls_offset)
3629 {
3630 #ifdef HOST_WIN32
3631         g_assert (tls_offset < 64);
3632         x86_prefix (code, X86_GS_PREFIX);
3633         amd64_mov_reg_mem (code, dreg, (tls_offset * 8) + 0x1480, 8);
3634 #elif defined(__APPLE__)
3635         x86_prefix (code, X86_GS_PREFIX);
3636         amd64_mov_reg_mem (code, dreg, tls_gs_offset + (tls_offset * 8), 8);
3637 #else
3638         if (optimize_for_xen) {
3639                 x86_prefix (code, X86_FS_PREFIX);
3640                 amd64_mov_reg_mem (code, dreg, 0, 8);
3641                 amd64_mov_reg_membase (code, dreg, dreg, tls_offset, 8);
3642         } else {
3643                 x86_prefix (code, X86_FS_PREFIX);
3644                 amd64_mov_reg_mem (code, dreg, tls_offset, 8);
3645         }
3646 #endif
3647         return code;
3648 }
3649
3650 static guint8*
3651 emit_tls_get_reg (guint8* code, int dreg, int offset_reg)
3652 {
3653 #ifdef TARGET_OSX
3654         // FIXME: tls_gs_offset can change too, do these when calculating the tls offset
3655         if (dreg != offset_reg)
3656                 amd64_mov_reg_reg (code, dreg, offset_reg, sizeof (gpointer));
3657         amd64_shift_reg_imm (code, X86_SHL, dreg, 3);
3658         if (tls_gs_offset)
3659                 amd64_alu_reg_imm (code, X86_ADD, dreg, tls_gs_offset);
3660         x86_prefix (code, X86_GS_PREFIX);
3661         amd64_mov_reg_membase (code, dreg, dreg, 0, sizeof (gpointer));
3662 #elif defined(__linux__)
3663         int tmpreg = -1;
3664
3665         if (dreg == offset_reg) {
3666                 /* Use a temporary reg by saving it to the redzone */
3667                 tmpreg = dreg == AMD64_RAX ? AMD64_RCX : AMD64_RAX;
3668                 amd64_mov_membase_reg (code, AMD64_RSP, -8, tmpreg, 8);
3669                 amd64_mov_reg_reg (code, tmpreg, offset_reg, sizeof (gpointer));
3670                 offset_reg = tmpreg;
3671         }
3672         x86_prefix (code, X86_FS_PREFIX);
3673         amd64_mov_reg_mem (code, dreg, 0, 8);
3674         amd64_mov_reg_memindex (code, dreg, dreg, 0, offset_reg, 0, 8);
3675         if (tmpreg != -1)
3676                 amd64_mov_reg_membase (code, tmpreg, AMD64_RSP, -8, 8);
3677 #else
3678         g_assert_not_reached ();
3679 #endif
3680         return code;
3681 }
3682
3683 /*
3684  * emit_setup_lmf:
3685  *
3686  *   Emit code to initialize an LMF structure at LMF_OFFSET.
3687  */
3688 static guint8*
3689 emit_setup_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, int cfa_offset)
3690 {
3691         int i;
3692
3693         /* 
3694          * The ip field is not set, the exception handling code will obtain it from the stack location pointed to by the sp field.
3695          */
3696         /* 
3697          * sp is saved right before calls but we need to save it here too so
3698          * async stack walks would work.
3699          */
3700         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
3701         /* Skip method (only needed for trampoline LMF frames) */
3702         /* Save callee saved regs */
3703         for (i = 0; i < MONO_MAX_IREGS; ++i) {
3704                 int offset;
3705
3706                 switch (i) {
3707                 case AMD64_RBX: offset = G_STRUCT_OFFSET (MonoLMF, rbx); break;
3708                 case AMD64_RBP: offset = G_STRUCT_OFFSET (MonoLMF, rbp); break;
3709                 case AMD64_R12: offset = G_STRUCT_OFFSET (MonoLMF, r12); break;
3710                 case AMD64_R13: offset = G_STRUCT_OFFSET (MonoLMF, r13); break;
3711                 case AMD64_R14: offset = G_STRUCT_OFFSET (MonoLMF, r14); break;
3712 #ifndef __native_client_codegen__
3713                 case AMD64_R15: offset = G_STRUCT_OFFSET (MonoLMF, r15); break;
3714 #endif
3715 #ifdef HOST_WIN32
3716                 case AMD64_RDI: offset = G_STRUCT_OFFSET (MonoLMF, rdi); break;
3717                 case AMD64_RSI: offset = G_STRUCT_OFFSET (MonoLMF, rsi); break;
3718 #endif
3719                 default:
3720                         offset = -1;
3721                         break;
3722                 }
3723
3724                 if (offset != -1) {
3725                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + offset, i, 8);
3726                         if ((cfg->arch.omit_fp || (i != AMD64_RBP)) && cfa_offset != -1)
3727                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - (lmf_offset + offset)));
3728                 }
3729         }
3730
3731         /* These can't contain refs */
3732         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), SLOT_NOREF);
3733         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), SLOT_NOREF);
3734         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, method), SLOT_NOREF);
3735         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rip), SLOT_NOREF);
3736         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), SLOT_NOREF);
3737
3738         /* These are handled automatically by the stack marking code */
3739         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), SLOT_NOREF);
3740         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), SLOT_NOREF);
3741         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), SLOT_NOREF);
3742         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), SLOT_NOREF);
3743         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), SLOT_NOREF);
3744         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), SLOT_NOREF);
3745 #ifdef HOST_WIN32
3746         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), SLOT_NOREF);
3747         mini_gc_set_slot_type_from_fp (cfg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), SLOT_NOREF);
3748 #endif
3749
3750         return code;
3751 }
3752
3753 /*
3754  * emit_save_lmf:
3755  *
3756  *   Emit code to push an LMF structure on the LMF stack.
3757  */
3758 static guint8*
3759 emit_save_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset, gboolean *args_clobbered)
3760 {
3761         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3762                 /*
3763                  * Optimized version which uses the mono_lmf TLS variable instead of 
3764                  * indirection through the mono_lmf_addr TLS variable.
3765                  */
3766                 /* %rax = previous_lmf */
3767                 x86_prefix (code, X86_FS_PREFIX);
3768                 amd64_mov_reg_mem (code, AMD64_RAX, lmf_tls_offset, 8);
3769
3770                 /* Save previous_lmf */
3771                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_RAX, 8);
3772                 /* Set new lmf */
3773                 if (lmf_offset == 0) {
3774                         x86_prefix (code, X86_FS_PREFIX);
3775                         amd64_mov_mem_reg (code, lmf_tls_offset, cfg->frame_reg, 8);
3776                 } else {
3777                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3778                         x86_prefix (code, X86_FS_PREFIX);
3779                         amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3780                 }
3781         } else {
3782                 if (lmf_addr_tls_offset != -1) {
3783                         /* Load lmf quicky using the FS register */
3784                         code = mono_amd64_emit_tls_get (code, AMD64_RAX, lmf_addr_tls_offset);
3785 #ifdef HOST_WIN32
3786                         /* The TLS key actually contains a pointer to the MonoJitTlsData structure */
3787                         /* FIXME: Add a separate key for LMF to avoid this */
3788                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RAX, G_STRUCT_OFFSET (MonoJitTlsData, lmf));
3789 #endif
3790                 }
3791                 else {
3792                         /* 
3793                          * The call might clobber argument registers, but they are already
3794                          * saved to the stack/global regs.
3795                          */
3796                         if (args_clobbered)
3797                                 *args_clobbered = TRUE;
3798                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3799                                                           (gpointer)"mono_get_lmf_addr", TRUE);         
3800                 }
3801
3802                 /* Save lmf_addr */
3803                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, sizeof(gpointer));
3804                 /* Save previous_lmf */
3805                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, sizeof(gpointer));
3806                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, sizeof(gpointer));
3807                 /* Set new lmf */
3808                 amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
3809                 amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, sizeof(gpointer));
3810         }
3811
3812         return code;
3813 }
3814
3815 /*
3816  * emit_save_lmf:
3817  *
3818  *   Emit code to pop an LMF structure from the LMF stack.
3819  */
3820 static guint8*
3821 emit_restore_lmf (MonoCompile *cfg, guint8 *code, gint32 lmf_offset)
3822 {
3823         if ((lmf_tls_offset != -1) && !optimize_for_xen) {
3824                 /*
3825                  * Optimized version which uses the mono_lmf TLS variable instead of indirection
3826                  * through the mono_lmf_addr TLS variable.
3827                  */
3828                 /* reg = previous_lmf */
3829                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3830                 x86_prefix (code, X86_FS_PREFIX);
3831                 amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
3832         } else {
3833                 /* Restore previous lmf */
3834                 amd64_mov_reg_membase (code, AMD64_RCX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), sizeof(gpointer));
3835                 amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), sizeof(gpointer));
3836                 amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, sizeof(gpointer));
3837         }
3838
3839         return code;
3840 }
3841
3842 #define REAL_PRINT_REG(text,reg) \
3843 mono_assert (reg >= 0); \
3844 amd64_push_reg (code, AMD64_RAX); \
3845 amd64_push_reg (code, AMD64_RDX); \
3846 amd64_push_reg (code, AMD64_RCX); \
3847 amd64_push_reg (code, reg); \
3848 amd64_push_imm (code, reg); \
3849 amd64_push_imm (code, text " %d %p\n"); \
3850 amd64_mov_reg_imm (code, AMD64_RAX, printf); \
3851 amd64_call_reg (code, AMD64_RAX); \
3852 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 3*4); \
3853 amd64_pop_reg (code, AMD64_RCX); \
3854 amd64_pop_reg (code, AMD64_RDX); \
3855 amd64_pop_reg (code, AMD64_RAX);
3856
3857 /* benchmark and set based on cpu */
3858 #define LOOP_ALIGNMENT 8
3859 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
3860
3861 #ifndef DISABLE_JIT
3862 void
3863 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
3864 {
3865         MonoInst *ins;
3866         MonoCallInst *call;
3867         guint offset;
3868         guint8 *code = cfg->native_code + cfg->code_len;
3869         MonoInst *last_ins = NULL;
3870         guint last_offset = 0;
3871         int max_len;
3872
3873         /* Fix max_offset estimate for each successor bb */
3874         if (cfg->opt & MONO_OPT_BRANCH) {
3875                 int current_offset = cfg->code_len;
3876                 MonoBasicBlock *current_bb;
3877                 for (current_bb = bb; current_bb != NULL; current_bb = current_bb->next_bb) {
3878                         current_bb->max_offset = current_offset;
3879                         current_offset += current_bb->max_length;
3880                 }
3881         }
3882
3883         if (cfg->opt & MONO_OPT_LOOP) {
3884                 int pad, align = LOOP_ALIGNMENT;
3885                 /* set alignment depending on cpu */
3886                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
3887                         pad = align - pad;
3888                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
3889                         amd64_padding (code, pad);
3890                         cfg->code_len += pad;
3891                         bb->native_offset = cfg->code_len;
3892                 }
3893         }
3894
3895 #if defined(__native_client_codegen__)
3896         /* For Native Client, all indirect call/jump targets must be */
3897         /* 32-byte aligned.  Exception handler blocks are jumped to  */
3898         /* indirectly as well.                                       */
3899         gboolean bb_needs_alignment = (bb->flags & BB_INDIRECT_JUMP_TARGET) ||
3900                                       (bb->flags & BB_EXCEPTION_HANDLER);
3901
3902         if ( bb_needs_alignment && ((cfg->code_len & kNaClAlignmentMask) != 0)) {
3903                 int pad = kNaClAlignment - (cfg->code_len & kNaClAlignmentMask);
3904                 if (pad != kNaClAlignment) code = mono_arch_nacl_pad(code, pad);
3905                 cfg->code_len += pad;
3906                 bb->native_offset = cfg->code_len;
3907         }
3908 #endif  /*__native_client_codegen__*/
3909
3910         if (cfg->verbose_level > 2)
3911                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
3912
3913         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
3914                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
3915                 g_assert (!cfg->compile_aot);
3916
3917                 cov->data [bb->dfn].cil_code = bb->cil_code;
3918                 amd64_mov_reg_imm (code, AMD64_R11, (guint64)&cov->data [bb->dfn].count);
3919                 /* this is not thread save, but good enough */
3920                 amd64_inc_membase (code, AMD64_R11, 0);
3921         }
3922
3923         offset = code - cfg->native_code;
3924
3925         mono_debug_open_block (cfg, bb, offset);
3926
3927     if (mono_break_at_bb_method && mono_method_desc_full_match (mono_break_at_bb_method, cfg->method) && bb->block_num == mono_break_at_bb_bb_num)
3928                 x86_breakpoint (code);
3929
3930         MONO_BB_FOR_EACH_INS (bb, ins) {
3931                 offset = code - cfg->native_code;
3932
3933                 max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
3934
3935 #define EXTRA_CODE_SPACE (NACL_SIZE (16, 16 + kNaClAlignment))
3936
3937                 if (G_UNLIKELY (offset > (cfg->code_size - max_len - EXTRA_CODE_SPACE))) {
3938                         cfg->code_size *= 2;
3939                         cfg->native_code = mono_realloc_native_code(cfg);
3940                         code = cfg->native_code + offset;
3941                         cfg->stat_code_reallocs++;
3942                 }
3943
3944                 if (cfg->debug_info)
3945                         mono_debug_record_line_number (cfg, ins, offset);
3946
3947                 switch (ins->opcode) {
3948                 case OP_BIGMUL:
3949                         amd64_mul_reg (code, ins->sreg2, TRUE);
3950                         break;
3951                 case OP_BIGMUL_UN:
3952                         amd64_mul_reg (code, ins->sreg2, FALSE);
3953                         break;
3954                 case OP_X86_SETEQ_MEMBASE:
3955                         amd64_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
3956                         break;
3957                 case OP_STOREI1_MEMBASE_IMM:
3958                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
3959                         break;
3960                 case OP_STOREI2_MEMBASE_IMM:
3961                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
3962                         break;
3963                 case OP_STOREI4_MEMBASE_IMM:
3964                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
3965                         break;
3966                 case OP_STOREI1_MEMBASE_REG:
3967                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
3968                         break;
3969                 case OP_STOREI2_MEMBASE_REG:
3970                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
3971                         break;
3972                 /* In AMD64 NaCl, pointers are 4 bytes, */
3973                 /*  so STORE_* != STOREI8_*. Likewise below. */
3974                 case OP_STORE_MEMBASE_REG:
3975                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, sizeof(gpointer));
3976                         break;
3977                 case OP_STOREI8_MEMBASE_REG:
3978                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 8);
3979                         break;
3980                 case OP_STOREI4_MEMBASE_REG:
3981                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
3982                         break;
3983                 case OP_STORE_MEMBASE_IMM:
3984 #ifndef __native_client_codegen__
3985                         /* In NaCl, this could be a PCONST type, which could */
3986                         /* mean a pointer type was copied directly into the  */
3987                         /* lower 32-bits of inst_imm, so for InvalidPtr==-1  */
3988                         /* the value would be 0x00000000FFFFFFFF which is    */
3989                         /* not proper for an imm32 unless you cast it.       */
3990                         g_assert (amd64_is_imm32 (ins->inst_imm));
3991 #endif
3992                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, (gint32)ins->inst_imm, sizeof(gpointer));
3993                         break;
3994                 case OP_STOREI8_MEMBASE_IMM:
3995                         g_assert (amd64_is_imm32 (ins->inst_imm));
3996                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 8);
3997                         break;
3998                 case OP_LOAD_MEM:
3999 #ifdef __mono_ilp32__
4000                         /* In ILP32, pointers are 4 bytes, so separate these */
4001                         /* cases, use literal 8 below where we really want 8 */
4002                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4003                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, sizeof(gpointer));
4004                         break;
4005 #endif
4006                 case OP_LOADI8_MEM:
4007                         // FIXME: Decompose this earlier
4008                         if (amd64_is_imm32 (ins->inst_imm))
4009                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 8);
4010                         else {
4011                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4012                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 8);
4013                         }
4014                         break;
4015                 case OP_LOADI4_MEM:
4016                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4017                         amd64_movsxd_reg_membase (code, ins->dreg, ins->dreg, 0);
4018                         break;
4019                 case OP_LOADU4_MEM:
4020                         // FIXME: Decompose this earlier
4021                         if (amd64_is_imm32 (ins->inst_imm))
4022                                 amd64_mov_reg_mem (code, ins->dreg, ins->inst_imm, 4);
4023                         else {
4024                                 amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4025                                 amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
4026                         }
4027                         break;
4028                 case OP_LOADU1_MEM:
4029                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4030                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, FALSE);
4031                         break;
4032                 case OP_LOADU2_MEM:
4033                         /* For NaCl, pointers are 4 bytes, so separate these */
4034                         /* cases, use literal 8 below where we really want 8 */
4035                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_imm);
4036                         amd64_widen_membase (code, ins->dreg, ins->dreg, 0, FALSE, TRUE);
4037                         break;
4038                 case OP_LOAD_MEMBASE:
4039                         g_assert (amd64_is_imm32 (ins->inst_offset));
4040                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, sizeof(gpointer));
4041                         break;
4042                 case OP_LOADI8_MEMBASE:
4043                         /* Use literal 8 instead of sizeof pointer or */
4044                         /* register, we really want 8 for this opcode */
4045                         g_assert (amd64_is_imm32 (ins->inst_offset));
4046                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 8);
4047                         break;
4048                 case OP_LOADI4_MEMBASE:
4049                         amd64_movsxd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
4050                         break;
4051                 case OP_LOADU4_MEMBASE:
4052                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
4053                         break;
4054                 case OP_LOADU1_MEMBASE:
4055                         /* The cpu zero extends the result into 64 bits */
4056                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE, 4);
4057                         break;
4058                 case OP_LOADI1_MEMBASE:
4059                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
4060                         break;
4061                 case OP_LOADU2_MEMBASE:
4062                         /* The cpu zero extends the result into 64 bits */
4063                         amd64_widen_membase_size (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE, 4);
4064                         break;
4065                 case OP_LOADI2_MEMBASE:
4066                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
4067                         break;
4068                 case OP_AMD64_LOADI8_MEMINDEX:
4069                         amd64_mov_reg_memindex_size (code, ins->dreg, ins->inst_basereg, 0, ins->inst_indexreg, 0, 8);
4070                         break;
4071                 case OP_LCONV_TO_I1:
4072                 case OP_ICONV_TO_I1:
4073                 case OP_SEXT_I1:
4074                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
4075                         break;
4076                 case OP_LCONV_TO_I2:
4077                 case OP_ICONV_TO_I2:
4078                 case OP_SEXT_I2:
4079                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
4080                         break;
4081                 case OP_LCONV_TO_U1:
4082                 case OP_ICONV_TO_U1:
4083                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
4084                         break;
4085                 case OP_LCONV_TO_U2:
4086                 case OP_ICONV_TO_U2:
4087                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
4088                         break;
4089                 case OP_ZEXT_I4:
4090                         /* Clean out the upper word */
4091                         amd64_mov_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
4092                         break;
4093                 case OP_SEXT_I4:
4094                         amd64_movsxd_reg_reg (code, ins->dreg, ins->sreg1);
4095                         break;
4096                 case OP_COMPARE:
4097                 case OP_LCOMPARE:
4098                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
4099                         break;
4100                 case OP_COMPARE_IMM:
4101 #if defined(__mono_ilp32__)
4102                         /* Comparison of pointer immediates should be 4 bytes to avoid sign-extend problems */
4103                         g_assert (amd64_is_imm32 (ins->inst_imm));
4104                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
4105                         break;
4106 #endif
4107                 case OP_LCOMPARE_IMM:
4108                         g_assert (amd64_is_imm32 (ins->inst_imm));
4109                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
4110                         break;
4111                 case OP_X86_COMPARE_REG_MEMBASE:
4112                         amd64_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
4113                         break;
4114                 case OP_X86_TEST_NULL:
4115                         amd64_test_reg_reg_size (code, ins->sreg1, ins->sreg1, 4);
4116                         break;
4117                 case OP_AMD64_TEST_NULL:
4118                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
4119                         break;
4120
4121                 case OP_X86_ADD_REG_MEMBASE:
4122                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4123                         break;
4124                 case OP_X86_SUB_REG_MEMBASE:
4125                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4126                         break;
4127                 case OP_X86_AND_REG_MEMBASE:
4128                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4129                         break;
4130                 case OP_X86_OR_REG_MEMBASE:
4131                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4132                         break;
4133                 case OP_X86_XOR_REG_MEMBASE:
4134                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4135                         break;
4136
4137                 case OP_X86_ADD_MEMBASE_IMM:
4138                         /* FIXME: Make a 64 version too */
4139                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4140                         break;
4141                 case OP_X86_SUB_MEMBASE_IMM:
4142                         g_assert (amd64_is_imm32 (ins->inst_imm));
4143                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4144                         break;
4145                 case OP_X86_AND_MEMBASE_IMM:
4146                         g_assert (amd64_is_imm32 (ins->inst_imm));
4147                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4148                         break;
4149                 case OP_X86_OR_MEMBASE_IMM:
4150                         g_assert (amd64_is_imm32 (ins->inst_imm));
4151                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4152                         break;
4153                 case OP_X86_XOR_MEMBASE_IMM:
4154                         g_assert (amd64_is_imm32 (ins->inst_imm));
4155                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4156                         break;
4157                 case OP_X86_ADD_MEMBASE_REG:
4158                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4159                         break;
4160                 case OP_X86_SUB_MEMBASE_REG:
4161                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4162                         break;
4163                 case OP_X86_AND_MEMBASE_REG:
4164                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4165                         break;
4166                 case OP_X86_OR_MEMBASE_REG:
4167                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4168                         break;
4169                 case OP_X86_XOR_MEMBASE_REG:
4170                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4171                         break;
4172                 case OP_X86_INC_MEMBASE:
4173                         amd64_inc_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4174                         break;
4175                 case OP_X86_INC_REG:
4176                         amd64_inc_reg_size (code, ins->dreg, 4);
4177                         break;
4178                 case OP_X86_DEC_MEMBASE:
4179                         amd64_dec_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
4180                         break;
4181                 case OP_X86_DEC_REG:
4182                         amd64_dec_reg_size (code, ins->dreg, 4);
4183                         break;
4184                 case OP_X86_MUL_REG_MEMBASE:
4185                 case OP_X86_MUL_MEMBASE_REG:
4186                         amd64_imul_reg_membase_size (code, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4187                         break;
4188                 case OP_AMD64_ICOMPARE_MEMBASE_REG:
4189                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
4190                         break;
4191                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
4192                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4193                         break;
4194                 case OP_AMD64_COMPARE_MEMBASE_REG:
4195                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4196                         break;
4197                 case OP_AMD64_COMPARE_MEMBASE_IMM:
4198                         g_assert (amd64_is_imm32 (ins->inst_imm));
4199                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4200                         break;
4201                 case OP_X86_COMPARE_MEMBASE8_IMM:
4202                         amd64_alu_membase8_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
4203                         break;
4204                 case OP_AMD64_ICOMPARE_REG_MEMBASE:
4205                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
4206                         break;
4207                 case OP_AMD64_COMPARE_REG_MEMBASE:
4208                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4209                         break;
4210
4211                 case OP_AMD64_ADD_REG_MEMBASE:
4212                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4213                         break;
4214                 case OP_AMD64_SUB_REG_MEMBASE:
4215                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4216                         break;
4217                 case OP_AMD64_AND_REG_MEMBASE:
4218                         amd64_alu_reg_membase_size (code, X86_AND, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4219                         break;
4220                 case OP_AMD64_OR_REG_MEMBASE:
4221                         amd64_alu_reg_membase_size (code, X86_OR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4222                         break;
4223                 case OP_AMD64_XOR_REG_MEMBASE:
4224                         amd64_alu_reg_membase_size (code, X86_XOR, ins->sreg1, ins->sreg2, ins->inst_offset, 8);
4225                         break;
4226
4227                 case OP_AMD64_ADD_MEMBASE_REG:
4228                         amd64_alu_membase_reg_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4229                         break;
4230                 case OP_AMD64_SUB_MEMBASE_REG:
4231                         amd64_alu_membase_reg_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4232                         break;
4233                 case OP_AMD64_AND_MEMBASE_REG:
4234                         amd64_alu_membase_reg_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4235                         break;
4236                 case OP_AMD64_OR_MEMBASE_REG:
4237                         amd64_alu_membase_reg_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4238                         break;
4239                 case OP_AMD64_XOR_MEMBASE_REG:
4240                         amd64_alu_membase_reg_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->sreg2, 8);
4241                         break;
4242
4243                 case OP_AMD64_ADD_MEMBASE_IMM:
4244                         g_assert (amd64_is_imm32 (ins->inst_imm));
4245                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4246                         break;
4247                 case OP_AMD64_SUB_MEMBASE_IMM:
4248                         g_assert (amd64_is_imm32 (ins->inst_imm));
4249                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4250                         break;
4251                 case OP_AMD64_AND_MEMBASE_IMM:
4252                         g_assert (amd64_is_imm32 (ins->inst_imm));
4253                         amd64_alu_membase_imm_size (code, X86_AND, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4254                         break;
4255                 case OP_AMD64_OR_MEMBASE_IMM:
4256                         g_assert (amd64_is_imm32 (ins->inst_imm));
4257                         amd64_alu_membase_imm_size (code, X86_OR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4258                         break;
4259                 case OP_AMD64_XOR_MEMBASE_IMM:
4260                         g_assert (amd64_is_imm32 (ins->inst_imm));
4261                         amd64_alu_membase_imm_size (code, X86_XOR, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 8);
4262                         break;
4263
4264                 case OP_BREAK:
4265                         amd64_breakpoint (code);
4266                         break;
4267                 case OP_RELAXED_NOP:
4268                         x86_prefix (code, X86_REP_PREFIX);
4269                         x86_nop (code);
4270                         break;
4271                 case OP_HARD_NOP:
4272                         x86_nop (code);
4273                         break;
4274                 case OP_NOP:
4275                 case OP_DUMMY_USE:
4276                 case OP_DUMMY_STORE:
4277                 case OP_NOT_REACHED:
4278                 case OP_NOT_NULL:
4279                         break;
4280                 case OP_SEQ_POINT: {
4281                         int i;
4282
4283                         /* 
4284                          * Read from the single stepping trigger page. This will cause a
4285                          * SIGSEGV when single stepping is enabled.
4286                          * We do this _before_ the breakpoint, so single stepping after
4287                          * a breakpoint is hit will step to the next IL offset.
4288                          */
4289                         if (ins->flags & MONO_INST_SINGLE_STEP_LOC) {
4290                                 MonoInst *var = cfg->arch.ss_trigger_page_var;
4291
4292                                 amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4293                                 amd64_alu_membase_imm_size (code, X86_CMP, AMD64_R11, 0, 0, 4);
4294                         }
4295
4296                         /* 
4297                          * This is the address which is saved in seq points, 
4298                          */
4299                         mono_add_seq_point (cfg, bb, ins, code - cfg->native_code);
4300
4301                         if (cfg->compile_aot) {
4302                                 guint32 offset = code - cfg->native_code;
4303                                 guint32 val;
4304                                 MonoInst *info_var = cfg->arch.seq_point_info_var;
4305
4306                                 /* Load info var */
4307                                 amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
4308                                 val = ((offset) * sizeof (guint8*)) + G_STRUCT_OFFSET (SeqPointInfo, bp_addrs);
4309                                 /* Load the info->bp_addrs [offset], which is either a valid address or the address of a trigger page */
4310                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, val, 8);
4311                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8);
4312                         } else {
4313                                 /* 
4314                                  * A placeholder for a possible breakpoint inserted by
4315                                  * mono_arch_set_breakpoint ().
4316                                  */
4317                                 for (i = 0; i < breakpoint_size; ++i)
4318                                         x86_nop (code);
4319                         }
4320                         /*
4321                          * Add an additional nop so skipping the bp doesn't cause the ip to point
4322                          * to another IL offset.
4323                          */
4324                         x86_nop (code);
4325                         break;
4326                 }
4327                 case OP_ADDCC:
4328                 case OP_LADDCC:
4329                 case OP_LADD:
4330                         amd64_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
4331                         break;
4332                 case OP_ADC:
4333                         amd64_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
4334                         break;
4335                 case OP_ADD_IMM:
4336                 case OP_LADD_IMM:
4337                         g_assert (amd64_is_imm32 (ins->inst_imm));
4338                         amd64_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
4339                         break;
4340                 case OP_ADC_IMM:
4341                         g_assert (amd64_is_imm32 (ins->inst_imm));
4342                         amd64_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
4343                         break;
4344                 case OP_SUBCC:
4345                 case OP_LSUBCC:
4346                 case OP_LSUB:
4347                         amd64_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
4348                         break;
4349                 case OP_SBB:
4350                         amd64_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
4351                         break;
4352                 case OP_SUB_IMM:
4353                 case OP_LSUB_IMM:
4354                         g_assert (amd64_is_imm32 (ins->inst_imm));
4355                         amd64_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
4356                         break;
4357                 case OP_SBB_IMM:
4358                         g_assert (amd64_is_imm32 (ins->inst_imm));
4359                         amd64_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
4360                         break;
4361                 case OP_LAND:
4362                         amd64_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
4363                         break;
4364                 case OP_AND_IMM:
4365                 case OP_LAND_IMM:
4366                         g_assert (amd64_is_imm32 (ins->inst_imm));
4367                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
4368                         break;
4369                 case OP_LMUL:
4370                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
4371                         break;
4372                 case OP_MUL_IMM:
4373                 case OP_LMUL_IMM:
4374                 case OP_IMUL_IMM: {
4375                         guint32 size = (ins->opcode == OP_IMUL_IMM) ? 4 : 8;
4376                         
4377                         switch (ins->inst_imm) {
4378                         case 2:
4379                                 /* MOV r1, r2 */
4380                                 /* ADD r1, r1 */
4381                                 if (ins->dreg != ins->sreg1)
4382                                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, size);
4383                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4384                                 break;
4385                         case 3:
4386                                 /* LEA r1, [r2 + r2*2] */
4387                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4388                                 break;
4389                         case 5:
4390                                 /* LEA r1, [r2 + r2*4] */
4391                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4392                                 break;
4393                         case 6:
4394                                 /* LEA r1, [r2 + r2*2] */
4395                                 /* ADD r1, r1          */
4396                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4397                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4398                                 break;
4399                         case 9:
4400                                 /* LEA r1, [r2 + r2*8] */
4401                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 3);
4402                                 break;
4403                         case 10:
4404                                 /* LEA r1, [r2 + r2*4] */
4405                                 /* ADD r1, r1          */
4406                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4407                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
4408                                 break;
4409                         case 12:
4410                                 /* LEA r1, [r2 + r2*2] */
4411                                 /* SHL r1, 2           */
4412                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
4413                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
4414                                 break;
4415                         case 25:
4416                                 /* LEA r1, [r2 + r2*4] */
4417                                 /* LEA r1, [r1 + r1*4] */
4418                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4419                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
4420                                 break;
4421                         case 100:
4422                                 /* LEA r1, [r2 + r2*4] */
4423                                 /* SHL r1, 2           */
4424                                 /* LEA r1, [r1 + r1*4] */
4425                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
4426                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
4427                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
4428                                 break;
4429                         default:
4430                                 amd64_imul_reg_reg_imm_size (code, ins->dreg, ins->sreg1, ins->inst_imm, size);
4431                                 break;
4432                         }
4433                         break;
4434                 }
4435                 case OP_LDIV:
4436                 case OP_LREM:
4437 #if defined( __native_client_codegen__ )
4438                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg2, 0);
4439                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4440 #endif
4441                         /* Regalloc magic makes the div/rem cases the same */
4442                         if (ins->sreg2 == AMD64_RDX) {
4443                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4444                                 amd64_cdq (code);
4445                                 amd64_div_membase (code, AMD64_RSP, -8, TRUE);
4446                         } else {
4447                                 amd64_cdq (code);
4448                                 amd64_div_reg (code, ins->sreg2, TRUE);
4449                         }
4450                         break;
4451                 case OP_LDIV_UN:
4452                 case OP_LREM_UN:
4453 #if defined( __native_client_codegen__ )
4454                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg2, 0);
4455                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4456 #endif
4457                         if (ins->sreg2 == AMD64_RDX) {
4458                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4459                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4460                                 amd64_div_membase (code, AMD64_RSP, -8, FALSE);
4461                         } else {
4462                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4463                                 amd64_div_reg (code, ins->sreg2, FALSE);
4464                         }
4465                         break;
4466                 case OP_IDIV:
4467                 case OP_IREM:
4468 #if defined( __native_client_codegen__ )
4469                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg2, 0);
4470                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4471 #endif
4472                         if (ins->sreg2 == AMD64_RDX) {
4473                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4474                                 amd64_cdq_size (code, 4);
4475                                 amd64_div_membase_size (code, AMD64_RSP, -8, TRUE, 4);
4476                         } else {
4477                                 amd64_cdq_size (code, 4);
4478                                 amd64_div_reg_size (code, ins->sreg2, TRUE, 4);
4479                         }
4480                         break;
4481                 case OP_IDIV_UN:
4482                 case OP_IREM_UN:
4483 #if defined( __native_client_codegen__ )
4484                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg2, 0, 4);
4485                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, TRUE, "DivideByZeroException");
4486 #endif
4487                         if (ins->sreg2 == AMD64_RDX) {
4488                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
4489                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4490                                 amd64_div_membase_size (code, AMD64_RSP, -8, FALSE, 4);
4491                         } else {
4492                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
4493                                 amd64_div_reg_size (code, ins->sreg2, FALSE, 4);
4494                         }
4495                         break;
4496                 case OP_IREM_IMM: {
4497                         int power = mono_is_power_of_two (ins->inst_imm);
4498
4499                         g_assert (ins->sreg1 == X86_EAX);
4500                         g_assert (ins->dreg == X86_EAX);
4501                         g_assert (power >= 0);
4502
4503                         if (power == 0) {
4504                                 amd64_mov_reg_imm (code, ins->dreg, 0);
4505                                 break;
4506                         }
4507
4508                         /* Based on gcc code */
4509
4510                         /* Add compensation for negative dividents */
4511                         amd64_mov_reg_reg_size (code, AMD64_RDX, AMD64_RAX, 4);
4512                         if (power > 1)
4513                                 amd64_shift_reg_imm_size (code, X86_SAR, AMD64_RDX, 31, 4);
4514                         amd64_shift_reg_imm_size (code, X86_SHR, AMD64_RDX, 32 - power, 4);
4515                         amd64_alu_reg_reg_size (code, X86_ADD, AMD64_RAX, AMD64_RDX, 4);
4516                         /* Compute remainder */
4517                         amd64_alu_reg_imm_size (code, X86_AND, AMD64_RAX, (1 << power) - 1, 4);
4518                         /* Remove compensation */
4519                         amd64_alu_reg_reg_size (code, X86_SUB, AMD64_RAX, AMD64_RDX, 4);
4520                         break;
4521                 }
4522                 case OP_LMUL_OVF:
4523                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
4524                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4525                         break;
4526                 case OP_LOR:
4527                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
4528                         break;
4529                 case OP_OR_IMM:
4530                 case OP_LOR_IMM:
4531                         g_assert (amd64_is_imm32 (ins->inst_imm));
4532                         amd64_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
4533                         break;
4534                 case OP_LXOR:
4535                         amd64_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
4536                         break;
4537                 case OP_XOR_IMM:
4538                 case OP_LXOR_IMM:
4539                         g_assert (amd64_is_imm32 (ins->inst_imm));
4540                         amd64_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
4541                         break;
4542                 case OP_LSHL:
4543                         g_assert (ins->sreg2 == AMD64_RCX);
4544                         amd64_shift_reg (code, X86_SHL, ins->dreg);
4545                         break;
4546                 case OP_LSHR:
4547                         g_assert (ins->sreg2 == AMD64_RCX);
4548                         amd64_shift_reg (code, X86_SAR, ins->dreg);
4549                         break;
4550                 case OP_SHR_IMM:
4551                         g_assert (amd64_is_imm32 (ins->inst_imm));
4552                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
4553                         break;
4554                 case OP_LSHR_IMM:
4555                         g_assert (amd64_is_imm32 (ins->inst_imm));
4556                         amd64_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
4557                         break;
4558                 case OP_SHR_UN_IMM:
4559                         g_assert (amd64_is_imm32 (ins->inst_imm));
4560                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
4561                         break;
4562                 case OP_LSHR_UN_IMM:
4563                         g_assert (amd64_is_imm32 (ins->inst_imm));
4564                         amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
4565                         break;
4566                 case OP_LSHR_UN:
4567                         g_assert (ins->sreg2 == AMD64_RCX);
4568                         amd64_shift_reg (code, X86_SHR, ins->dreg);
4569                         break;
4570                 case OP_SHL_IMM:
4571                         g_assert (amd64_is_imm32 (ins->inst_imm));
4572                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
4573                         break;
4574                 case OP_LSHL_IMM:
4575                         g_assert (amd64_is_imm32 (ins->inst_imm));
4576                         amd64_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
4577                         break;
4578
4579                 case OP_IADDCC:
4580                 case OP_IADD:
4581                         amd64_alu_reg_reg_size (code, X86_ADD, ins->sreg1, ins->sreg2, 4);
4582                         break;
4583                 case OP_IADC:
4584                         amd64_alu_reg_reg_size (code, X86_ADC, ins->sreg1, ins->sreg2, 4);
4585                         break;
4586                 case OP_IADD_IMM:
4587                         amd64_alu_reg_imm_size (code, X86_ADD, ins->dreg, ins->inst_imm, 4);
4588                         break;
4589                 case OP_IADC_IMM:
4590                         amd64_alu_reg_imm_size (code, X86_ADC, ins->dreg, ins->inst_imm, 4);
4591                         break;
4592                 case OP_ISUBCC:
4593                 case OP_ISUB:
4594                         amd64_alu_reg_reg_size (code, X86_SUB, ins->sreg1, ins->sreg2, 4);
4595                         break;
4596                 case OP_ISBB:
4597                         amd64_alu_reg_reg_size (code, X86_SBB, ins->sreg1, ins->sreg2, 4);
4598                         break;
4599                 case OP_ISUB_IMM:
4600                         amd64_alu_reg_imm_size (code, X86_SUB, ins->dreg, ins->inst_imm, 4);
4601                         break;
4602                 case OP_ISBB_IMM:
4603                         amd64_alu_reg_imm_size (code, X86_SBB, ins->dreg, ins->inst_imm, 4);
4604                         break;
4605                 case OP_IAND:
4606                         amd64_alu_reg_reg_size (code, X86_AND, ins->sreg1, ins->sreg2, 4);
4607                         break;
4608                 case OP_IAND_IMM:
4609                         amd64_alu_reg_imm_size (code, X86_AND, ins->sreg1, ins->inst_imm, 4);
4610                         break;
4611                 case OP_IOR:
4612                         amd64_alu_reg_reg_size (code, X86_OR, ins->sreg1, ins->sreg2, 4);
4613                         break;
4614                 case OP_IOR_IMM:
4615                         amd64_alu_reg_imm_size (code, X86_OR, ins->sreg1, ins->inst_imm, 4);
4616                         break;
4617                 case OP_IXOR:
4618                         amd64_alu_reg_reg_size (code, X86_XOR, ins->sreg1, ins->sreg2, 4);
4619                         break;
4620                 case OP_IXOR_IMM:
4621                         amd64_alu_reg_imm_size (code, X86_XOR, ins->sreg1, ins->inst_imm, 4);
4622                         break;
4623                 case OP_INEG:
4624                         amd64_neg_reg_size (code, ins->sreg1, 4);
4625                         break;
4626                 case OP_INOT:
4627                         amd64_not_reg_size (code, ins->sreg1, 4);
4628                         break;
4629                 case OP_ISHL:
4630                         g_assert (ins->sreg2 == AMD64_RCX);
4631                         amd64_shift_reg_size (code, X86_SHL, ins->dreg, 4);
4632                         break;
4633                 case OP_ISHR:
4634                         g_assert (ins->sreg2 == AMD64_RCX);
4635                         amd64_shift_reg_size (code, X86_SAR, ins->dreg, 4);
4636                         break;
4637                 case OP_ISHR_IMM:
4638                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
4639                         break;
4640                 case OP_ISHR_UN_IMM:
4641                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
4642                         break;
4643                 case OP_ISHR_UN:
4644                         g_assert (ins->sreg2 == AMD64_RCX);
4645                         amd64_shift_reg_size (code, X86_SHR, ins->dreg, 4);
4646                         break;
4647                 case OP_ISHL_IMM:
4648                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
4649                         break;
4650                 case OP_IMUL:
4651                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
4652                         break;
4653                 case OP_IMUL_OVF:
4654                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
4655                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4656                         break;
4657                 case OP_IMUL_OVF_UN:
4658                 case OP_LMUL_OVF_UN: {
4659                         /* the mul operation and the exception check should most likely be split */
4660                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
4661                         int size = (ins->opcode == OP_IMUL_OVF_UN) ? 4 : 8;
4662                         /*g_assert (ins->sreg2 == X86_EAX);
4663                         g_assert (ins->dreg == X86_EAX);*/
4664                         if (ins->sreg2 == X86_EAX) {
4665                                 non_eax_reg = ins->sreg1;
4666                         } else if (ins->sreg1 == X86_EAX) {
4667                                 non_eax_reg = ins->sreg2;
4668                         } else {
4669                                 /* no need to save since we're going to store to it anyway */
4670                                 if (ins->dreg != X86_EAX) {
4671                                         saved_eax = TRUE;
4672                                         amd64_push_reg (code, X86_EAX);
4673                                 }
4674                                 amd64_mov_reg_reg (code, X86_EAX, ins->sreg1, size);
4675                                 non_eax_reg = ins->sreg2;
4676                         }
4677                         if (ins->dreg == X86_EDX) {
4678                                 if (!saved_eax) {
4679                                         saved_eax = TRUE;
4680                                         amd64_push_reg (code, X86_EAX);
4681                                 }
4682                         } else {
4683                                 saved_edx = TRUE;
4684                                 amd64_push_reg (code, X86_EDX);
4685                         }
4686                         amd64_mul_reg_size (code, non_eax_reg, FALSE, size);
4687                         /* save before the check since pop and mov don't change the flags */
4688                         if (ins->dreg != X86_EAX)
4689                                 amd64_mov_reg_reg (code, ins->dreg, X86_EAX, size);
4690                         if (saved_edx)
4691                                 amd64_pop_reg (code, X86_EDX);
4692                         if (saved_eax)
4693                                 amd64_pop_reg (code, X86_EAX);
4694                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
4695                         break;
4696                 }
4697                 case OP_ICOMPARE:
4698                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
4699                         break;
4700                 case OP_ICOMPARE_IMM:
4701                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
4702                         break;
4703                 case OP_IBEQ:
4704                 case OP_IBLT:
4705                 case OP_IBGT:
4706                 case OP_IBGE:
4707                 case OP_IBLE:
4708                 case OP_LBEQ:
4709                 case OP_LBLT:
4710                 case OP_LBGT:
4711                 case OP_LBGE:
4712                 case OP_LBLE:
4713                 case OP_IBNE_UN:
4714                 case OP_IBLT_UN:
4715                 case OP_IBGT_UN:
4716                 case OP_IBGE_UN:
4717                 case OP_IBLE_UN:
4718                 case OP_LBNE_UN:
4719                 case OP_LBLT_UN:
4720                 case OP_LBGT_UN:
4721                 case OP_LBGE_UN:
4722                 case OP_LBLE_UN:
4723                         EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
4724                         break;
4725
4726                 case OP_CMOV_IEQ:
4727                 case OP_CMOV_IGE:
4728                 case OP_CMOV_IGT:
4729                 case OP_CMOV_ILE:
4730                 case OP_CMOV_ILT:
4731                 case OP_CMOV_INE_UN:
4732                 case OP_CMOV_IGE_UN:
4733                 case OP_CMOV_IGT_UN:
4734                 case OP_CMOV_ILE_UN:
4735                 case OP_CMOV_ILT_UN:
4736                 case OP_CMOV_LEQ:
4737                 case OP_CMOV_LGE:
4738                 case OP_CMOV_LGT:
4739                 case OP_CMOV_LLE:
4740                 case OP_CMOV_LLT:
4741                 case OP_CMOV_LNE_UN:
4742                 case OP_CMOV_LGE_UN:
4743                 case OP_CMOV_LGT_UN:
4744                 case OP_CMOV_LLE_UN:
4745                 case OP_CMOV_LLT_UN:
4746                         g_assert (ins->dreg == ins->sreg1);
4747                         /* This needs to operate on 64 bit values */
4748                         amd64_cmov_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, ins->sreg2);
4749                         break;
4750
4751                 case OP_LNOT:
4752                         amd64_not_reg (code, ins->sreg1);
4753                         break;
4754                 case OP_LNEG:
4755                         amd64_neg_reg (code, ins->sreg1);
4756                         break;
4757
4758                 case OP_ICONST:
4759                 case OP_I8CONST:
4760                         if ((((guint64)ins->inst_c0) >> 32) == 0)
4761                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 4);
4762                         else
4763                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 8);
4764                         break;
4765                 case OP_AOTCONST:
4766                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
4767                         amd64_mov_reg_membase (code, ins->dreg, AMD64_RIP, 0, sizeof(gpointer));
4768                         break;
4769                 case OP_JUMP_TABLE:
4770                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
4771                         amd64_mov_reg_imm_size (code, ins->dreg, 0, 8);
4772                         break;
4773                 case OP_MOVE:
4774                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, sizeof(mgreg_t));
4775                         break;
4776                 case OP_AMD64_SET_XMMREG_R4: {
4777                         amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg1);
4778                         break;
4779                 }
4780                 case OP_AMD64_SET_XMMREG_R8: {
4781                         if (ins->dreg != ins->sreg1)
4782                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
4783                         break;
4784                 }
4785                 case OP_TAILCALL: {
4786                         MonoCallInst *call = (MonoCallInst*)ins;
4787                         int pos = 0, i;
4788
4789                         /* FIXME: no tracing support... */
4790                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4791                                 code = mono_arch_instrument_epilog_full (cfg, mono_profiler_method_leave, code, FALSE, TRUE);
4792
4793                         g_assert (!cfg->method->save_lmf);
4794
4795                         if (cfg->arch.omit_fp) {
4796                                 guint32 save_offset = 0;
4797                                 /* Pop callee-saved registers */
4798                                 for (i = 0; i < AMD64_NREG; ++i)
4799                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4800                                                 amd64_mov_reg_membase (code, i, AMD64_RSP, save_offset, 8);
4801                                                 save_offset += 8;
4802                                         }
4803                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
4804
4805                                 // FIXME:
4806                                 if (call->stack_usage)
4807                                         NOT_IMPLEMENTED;
4808                         }
4809                         else {
4810                                 for (i = 0; i < AMD64_NREG; ++i)
4811                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
4812                                                 pos -= sizeof(mgreg_t);
4813
4814                                 /* Restore callee-saved registers */
4815                                 for (i = AMD64_NREG - 1; i > 0; --i) {
4816                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4817                                                 amd64_mov_reg_membase (code, i, AMD64_RBP, pos, sizeof(mgreg_t));
4818                                                 pos += sizeof(mgreg_t);
4819                                         }
4820                                 }
4821
4822                                 /* Copy arguments on the stack to our argument area */
4823                                 for (i = 0; i < call->stack_usage; i += sizeof(mgreg_t)) {
4824                                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, i, sizeof(mgreg_t));
4825                                         amd64_mov_membase_reg (code, AMD64_RBP, 16 + i, AMD64_RAX, sizeof(mgreg_t));
4826                                 }
4827                         
4828                                 if (pos)
4829                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
4830
4831                                 amd64_leave (code);
4832                         }
4833
4834                         offset = code - cfg->native_code;
4835                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, call->method);
4836                         if (cfg->compile_aot)
4837                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
4838                         else
4839                                 amd64_set_reg_template (code, AMD64_R11);
4840                         amd64_jump_reg (code, AMD64_R11);
4841                         ins->flags |= MONO_INST_GC_CALLSITE;
4842                         ins->backend.pc_offset = code - cfg->native_code;
4843                         break;
4844                 }
4845                 case OP_CHECK_THIS:
4846                         /* ensure ins->sreg1 is not NULL */
4847                         amd64_alu_membase_imm_size (code, X86_CMP, ins->sreg1, 0, 0, 4);
4848                         break;
4849                 case OP_ARGLIST: {
4850                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, cfg->sig_cookie);
4851                         amd64_mov_membase_reg (code, ins->sreg1, 0, AMD64_R11, sizeof(gpointer));
4852                         break;
4853                 }
4854                 case OP_CALL:
4855                 case OP_FCALL:
4856                 case OP_LCALL:
4857                 case OP_VCALL:
4858                 case OP_VCALL2:
4859                 case OP_VOIDCALL:
4860                         call = (MonoCallInst*)ins;
4861                         /*
4862                          * The AMD64 ABI forces callers to know about varargs.
4863                          */
4864                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke))
4865                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4866                         else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
4867                                 /* 
4868                                  * Since the unmanaged calling convention doesn't contain a 
4869                                  * 'vararg' entry, we have to treat every pinvoke call as a
4870                                  * potential vararg call.
4871                                  */
4872                                 guint32 nregs, i;
4873                                 nregs = 0;
4874                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
4875                                         if (call->used_fregs & (1 << i))
4876                                                 nregs ++;
4877                                 if (!nregs)
4878                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4879                                 else
4880                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
4881                         }
4882
4883                         if (ins->flags & MONO_INST_HAS_METHOD)
4884                                 code = emit_call (cfg, code, MONO_PATCH_INFO_METHOD, call->method, FALSE);
4885                         else
4886                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, call->fptr, FALSE);
4887                         ins->flags |= MONO_INST_GC_CALLSITE;
4888                         ins->backend.pc_offset = code - cfg->native_code;
4889                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4890                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4891                         code = emit_move_return_value (cfg, ins, code);
4892                         break;
4893                 case OP_FCALL_REG:
4894                 case OP_LCALL_REG:
4895                 case OP_VCALL_REG:
4896                 case OP_VCALL2_REG:
4897                 case OP_VOIDCALL_REG:
4898                 case OP_CALL_REG:
4899                         call = (MonoCallInst*)ins;
4900
4901                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
4902                                 amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
4903                                 ins->sreg1 = AMD64_R11;
4904                         }
4905
4906                         /*
4907                          * The AMD64 ABI forces callers to know about varargs.
4908                          */
4909                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke)) {
4910                                 if (ins->sreg1 == AMD64_RAX) {
4911                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
4912                                         ins->sreg1 = AMD64_R11;
4913                                 }
4914                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4915                         } else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
4916                                 /* 
4917                                  * Since the unmanaged calling convention doesn't contain a 
4918                                  * 'vararg' entry, we have to treat every pinvoke call as a
4919                                  * potential vararg call.
4920                                  */
4921                                 guint32 nregs, i;
4922                                 nregs = 0;
4923                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
4924                                         if (call->used_fregs & (1 << i))
4925                                                 nregs ++;
4926                                 if (ins->sreg1 == AMD64_RAX) {
4927                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
4928                                         ins->sreg1 = AMD64_R11;
4929                                 }
4930                                 if (!nregs)
4931                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
4932                                 else
4933                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
4934                         }
4935
4936                         amd64_call_reg (code, ins->sreg1);
4937                         ins->flags |= MONO_INST_GC_CALLSITE;
4938                         ins->backend.pc_offset = code - cfg->native_code;
4939                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4940                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4941                         code = emit_move_return_value (cfg, ins, code);
4942                         break;
4943                 case OP_FCALL_MEMBASE:
4944                 case OP_LCALL_MEMBASE:
4945                 case OP_VCALL_MEMBASE:
4946                 case OP_VCALL2_MEMBASE:
4947                 case OP_VOIDCALL_MEMBASE:
4948                 case OP_CALL_MEMBASE:
4949                         call = (MonoCallInst*)ins;
4950
4951                         amd64_call_membase (code, ins->sreg1, ins->inst_offset);
4952                         ins->flags |= MONO_INST_GC_CALLSITE;
4953                         ins->backend.pc_offset = code - cfg->native_code;
4954                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention) && !cfg->arch.no_pushes)
4955                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
4956                         code = emit_move_return_value (cfg, ins, code);
4957                         break;
4958                 case OP_DYN_CALL: {
4959                         int i;
4960                         MonoInst *var = cfg->dyn_call_var;
4961
4962                         g_assert (var->opcode == OP_REGOFFSET);
4963
4964                         /* r11 = args buffer filled by mono_arch_get_dyn_call_args () */
4965                         amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
4966                         /* r10 = ftn */
4967                         amd64_mov_reg_reg (code, AMD64_R10, ins->sreg2, 8);
4968
4969                         /* Save args buffer */
4970                         amd64_mov_membase_reg (code, var->inst_basereg, var->inst_offset, AMD64_R11, 8);
4971
4972                         /* Set argument registers */
4973                         for (i = 0; i < PARAM_REGS; ++i)
4974                                 amd64_mov_reg_membase (code, param_regs [i], AMD64_R11, i * sizeof(mgreg_t), sizeof(mgreg_t));
4975                         
4976                         /* Make the call */
4977                         amd64_call_reg (code, AMD64_R10);
4978
4979                         ins->flags |= MONO_INST_GC_CALLSITE;
4980                         ins->backend.pc_offset = code - cfg->native_code;
4981
4982                         /* Save result */
4983                         amd64_mov_reg_membase (code, AMD64_R11, var->inst_basereg, var->inst_offset, 8);
4984                         amd64_mov_membase_reg (code, AMD64_R11, G_STRUCT_OFFSET (DynCallArgs, res), AMD64_RAX, 8);
4985                         break;
4986                 }
4987                 case OP_AMD64_SAVE_SP_TO_LMF: {
4988                         MonoInst *lmf_var = cfg->arch.lmf_var;
4989                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_var->inst_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
4990                         break;
4991                 }
4992                 case OP_X86_PUSH:
4993                         g_assert (!cfg->arch.no_pushes);
4994                         amd64_push_reg (code, ins->sreg1);
4995                         break;
4996                 case OP_X86_PUSH_IMM:
4997                         g_assert (!cfg->arch.no_pushes);
4998                         g_assert (amd64_is_imm32 (ins->inst_imm));
4999                         amd64_push_imm (code, ins->inst_imm);
5000                         break;
5001                 case OP_X86_PUSH_MEMBASE:
5002                         g_assert (!cfg->arch.no_pushes);
5003                         amd64_push_membase (code, ins->inst_basereg, ins->inst_offset);
5004                         break;
5005                 case OP_X86_PUSH_OBJ: {
5006                         int size = ALIGN_TO (ins->inst_imm, 8);
5007
5008                         g_assert (!cfg->arch.no_pushes);
5009
5010                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5011                         amd64_push_reg (code, AMD64_RDI);
5012                         amd64_push_reg (code, AMD64_RSI);
5013                         amd64_push_reg (code, AMD64_RCX);
5014                         if (ins->inst_offset)
5015                                 amd64_lea_membase (code, AMD64_RSI, ins->inst_basereg, ins->inst_offset);
5016                         else
5017                                 amd64_mov_reg_reg (code, AMD64_RSI, ins->inst_basereg, 8);
5018                         amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, (3 * 8));
5019                         amd64_mov_reg_imm (code, AMD64_RCX, (size >> 3));
5020                         amd64_cld (code);
5021                         amd64_prefix (code, X86_REP_PREFIX);
5022                         amd64_movsd (code);
5023                         amd64_pop_reg (code, AMD64_RCX);
5024                         amd64_pop_reg (code, AMD64_RSI);
5025                         amd64_pop_reg (code, AMD64_RDI);
5026                         break;
5027                 }
5028                 case OP_X86_LEA:
5029                         amd64_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->backend.shift_amount);
5030                         break;
5031                 case OP_X86_LEA_MEMBASE:
5032                         amd64_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
5033                         break;
5034                 case OP_X86_XCHG:
5035                         amd64_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
5036                         break;
5037                 case OP_LOCALLOC:
5038                         /* keep alignment */
5039                         amd64_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
5040                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
5041                         code = mono_emit_stack_alloc (cfg, code, ins);
5042                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5043                         if (cfg->param_area && cfg->arch.no_pushes)
5044                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, cfg->param_area);
5045                         break;
5046                 case OP_LOCALLOC_IMM: {
5047                         guint32 size = ins->inst_imm;
5048                         size = (size + (MONO_ARCH_FRAME_ALIGNMENT - 1)) & ~ (MONO_ARCH_FRAME_ALIGNMENT - 1);
5049
5050                         if (ins->flags & MONO_INST_INIT) {
5051                                 if (size < 64) {
5052                                         int i;
5053
5054                                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5055                                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5056
5057                                         for (i = 0; i < size; i += 8)
5058                                                 amd64_mov_membase_reg (code, AMD64_RSP, i, ins->dreg, 8);
5059                                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);                                      
5060                                 } else {
5061                                         amd64_mov_reg_imm (code, ins->dreg, size);
5062                                         ins->sreg1 = ins->dreg;
5063
5064                                         code = mono_emit_stack_alloc (cfg, code, ins);
5065                                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5066                                 }
5067                         } else {
5068                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, size);
5069                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
5070                         }
5071                         if (cfg->param_area && cfg->arch.no_pushes)
5072                                 amd64_alu_reg_imm (code, X86_ADD, ins->dreg, cfg->param_area);
5073                         break;
5074                 }
5075                 case OP_THROW: {
5076                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
5077                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
5078                                              (gpointer)"mono_arch_throw_exception", FALSE);
5079                         ins->flags |= MONO_INST_GC_CALLSITE;
5080                         ins->backend.pc_offset = code - cfg->native_code;
5081                         break;
5082                 }
5083                 case OP_RETHROW: {
5084                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
5085                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
5086                                              (gpointer)"mono_arch_rethrow_exception", FALSE);
5087                         ins->flags |= MONO_INST_GC_CALLSITE;
5088                         ins->backend.pc_offset = code - cfg->native_code;
5089                         break;
5090                 }
5091                 case OP_CALL_HANDLER: 
5092                         /* Align stack */
5093                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5094                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
5095                         amd64_call_imm (code, 0);
5096                         mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
5097                         /* Restore stack alignment */
5098                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5099                         break;
5100                 case OP_START_HANDLER: {
5101                         /* Even though we're saving RSP, use sizeof */
5102                         /* gpointer because spvar is of type IntPtr */
5103                         /* see: mono_create_spvar_for_region */
5104                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5105                         amd64_mov_membase_reg (code, spvar->inst_basereg, spvar->inst_offset, AMD64_RSP, sizeof(gpointer));
5106
5107                         if ((MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_FINALLY) ||
5108                                  MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_FINALLY)) &&
5109                                 cfg->param_area && cfg->arch.no_pushes) {
5110                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, ALIGN_TO (cfg->param_area, MONO_ARCH_FRAME_ALIGNMENT));
5111                         }
5112                         break;
5113                 }
5114                 case OP_ENDFINALLY: {
5115                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5116                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, sizeof(gpointer));
5117                         amd64_ret (code);
5118                         break;
5119                 }
5120                 case OP_ENDFILTER: {
5121                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
5122                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, sizeof(gpointer));
5123                         /* The local allocator will put the result into RAX */
5124                         amd64_ret (code);
5125                         break;
5126                 }
5127
5128                 case OP_LABEL:
5129                         ins->inst_c0 = code - cfg->native_code;
5130                         break;
5131                 case OP_BR:
5132                         //g_print ("target: %p, next: %p, curr: %p, last: %p\n", ins->inst_target_bb, bb->next_bb, ins, bb->last_ins);
5133                         //if ((ins->inst_target_bb == bb->next_bb) && ins == bb->last_ins)
5134                         //break;
5135                                 if (ins->inst_target_bb->native_offset) {
5136                                         amd64_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
5137                                 } else {
5138                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
5139                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
5140                                             x86_is_imm8 (ins->inst_target_bb->max_offset - offset))
5141                                                 x86_jump8 (code, 0);
5142                                         else 
5143                                                 x86_jump32 (code, 0);
5144                         }
5145                         break;
5146                 case OP_BR_REG:
5147                         amd64_jump_reg (code, ins->sreg1);
5148                         break;
5149                 case OP_CEQ:
5150                 case OP_LCEQ:
5151                 case OP_ICEQ:
5152                 case OP_CLT:
5153                 case OP_LCLT:
5154                 case OP_ICLT:
5155                 case OP_CGT:
5156                 case OP_ICGT:
5157                 case OP_LCGT:
5158                 case OP_CLT_UN:
5159                 case OP_LCLT_UN:
5160                 case OP_ICLT_UN:
5161                 case OP_CGT_UN:
5162                 case OP_LCGT_UN:
5163                 case OP_ICGT_UN:
5164                         amd64_set_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
5165                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
5166                         break;
5167                 case OP_COND_EXC_EQ:
5168                 case OP_COND_EXC_NE_UN:
5169                 case OP_COND_EXC_LT:
5170                 case OP_COND_EXC_LT_UN:
5171                 case OP_COND_EXC_GT:
5172                 case OP_COND_EXC_GT_UN:
5173                 case OP_COND_EXC_GE:
5174                 case OP_COND_EXC_GE_UN:
5175                 case OP_COND_EXC_LE:
5176                 case OP_COND_EXC_LE_UN:
5177                 case OP_COND_EXC_IEQ:
5178                 case OP_COND_EXC_INE_UN:
5179                 case OP_COND_EXC_ILT:
5180                 case OP_COND_EXC_ILT_UN:
5181                 case OP_COND_EXC_IGT:
5182                 case OP_COND_EXC_IGT_UN:
5183                 case OP_COND_EXC_IGE:
5184                 case OP_COND_EXC_IGE_UN:
5185                 case OP_COND_EXC_ILE:
5186                 case OP_COND_EXC_ILE_UN:
5187                         EMIT_COND_SYSTEM_EXCEPTION (cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->inst_p1);
5188                         break;
5189                 case OP_COND_EXC_OV:
5190                 case OP_COND_EXC_NO:
5191                 case OP_COND_EXC_C:
5192                 case OP_COND_EXC_NC:
5193                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
5194                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
5195                         break;
5196                 case OP_COND_EXC_IOV:
5197                 case OP_COND_EXC_INO:
5198                 case OP_COND_EXC_IC:
5199                 case OP_COND_EXC_INC:
5200                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_IEQ], 
5201                                                     (ins->opcode < OP_COND_EXC_INE_UN), ins->inst_p1);
5202                         break;
5203
5204                 /* floating point opcodes */
5205                 case OP_R8CONST: {
5206                         double d = *(double *)ins->inst_p0;
5207
5208                         if ((d == 0.0) && (mono_signbit (d) == 0)) {
5209                                 amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
5210                         }
5211                         else {
5212                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
5213                                 amd64_sse_movsd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5214                         }
5215                         break;
5216                 }
5217                 case OP_R4CONST: {
5218                         float f = *(float *)ins->inst_p0;
5219
5220                         if ((f == 0.0) && (mono_signbit (f) == 0)) {
5221                                 amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
5222                         }
5223                         else {
5224                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
5225                                 amd64_sse_movss_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5226                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
5227                         }
5228                         break;
5229                 }
5230                 case OP_STORER8_MEMBASE_REG:
5231                         amd64_sse_movsd_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1);
5232                         break;
5233                 case OP_LOADR8_MEMBASE:
5234                         amd64_sse_movsd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
5235                         break;
5236                 case OP_STORER4_MEMBASE_REG:
5237                         /* This requires a double->single conversion */
5238                         amd64_sse_cvtsd2ss_reg_reg (code, AMD64_XMM15, ins->sreg1);
5239                         amd64_sse_movss_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, AMD64_XMM15);
5240                         break;
5241                 case OP_LOADR4_MEMBASE:
5242                         amd64_sse_movss_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
5243                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
5244                         break;
5245                 case OP_ICONV_TO_R4: /* FIXME: change precision */
5246                 case OP_ICONV_TO_R8:
5247                         amd64_sse_cvtsi2sd_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
5248                         break;
5249                 case OP_LCONV_TO_R4: /* FIXME: change precision */
5250                 case OP_LCONV_TO_R8:
5251                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
5252                         break;
5253                 case OP_FCONV_TO_R4:
5254                         /* FIXME: nothing to do ?? */
5255                         break;
5256                 case OP_FCONV_TO_I1:
5257                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE);
5258                         break;
5259                 case OP_FCONV_TO_U1:
5260                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE);
5261                         break;
5262                 case OP_FCONV_TO_I2:
5263                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE);
5264                         break;
5265                 case OP_FCONV_TO_U2:
5266                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE);
5267                         break;
5268                 case OP_FCONV_TO_U4:
5269                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, FALSE);                  
5270                         break;
5271                 case OP_FCONV_TO_I4:
5272                 case OP_FCONV_TO_I:
5273                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE);
5274                         break;
5275                 case OP_FCONV_TO_I8:
5276                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 8, TRUE);
5277                         break;
5278                 case OP_LCONV_TO_R_UN: { 
5279                         guint8 *br [2];
5280
5281                         /* Based on gcc code */
5282                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
5283                         br [0] = code; x86_branch8 (code, X86_CC_S, 0, TRUE);
5284
5285                         /* Positive case */
5286                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
5287                         br [1] = code; x86_jump8 (code, 0);
5288                         amd64_patch (br [0], code);
5289
5290                         /* Negative case */
5291                         /* Save to the red zone */
5292                         amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RAX, 8);
5293                         amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
5294                         amd64_mov_reg_reg (code, AMD64_RCX, ins->sreg1, 8);
5295                         amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
5296                         amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, 1);
5297                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RAX, 1);
5298                         amd64_alu_reg_imm (code, X86_OR, AMD64_RAX, AMD64_RCX);
5299                         amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, AMD64_RAX);
5300                         amd64_sse_addsd_reg_reg (code, ins->dreg, ins->dreg);
5301                         /* Restore */
5302                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
5303                         amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, -8, 8);
5304                         amd64_patch (br [1], code);
5305                         break;
5306                 }
5307                 case OP_LCONV_TO_OVF_U4:
5308                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0);
5309                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_LT, TRUE, "OverflowException");
5310                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
5311                         break;
5312                 case OP_LCONV_TO_OVF_I4_UN:
5313                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0x7fffffff);
5314                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_GT, FALSE, "OverflowException");
5315                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
5316                         break;
5317                 case OP_FMOVE:
5318                         if (ins->dreg != ins->sreg1)
5319                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
5320                         break;
5321                 case OP_FADD:
5322                         amd64_sse_addsd_reg_reg (code, ins->dreg, ins->sreg2);
5323                         break;
5324                 case OP_FSUB:
5325                         amd64_sse_subsd_reg_reg (code, ins->dreg, ins->sreg2);
5326                         break;          
5327                 case OP_FMUL:
5328                         amd64_sse_mulsd_reg_reg (code, ins->dreg, ins->sreg2);
5329                         break;          
5330                 case OP_FDIV:
5331                         amd64_sse_divsd_reg_reg (code, ins->dreg, ins->sreg2);
5332                         break;          
5333                 case OP_FNEG: {
5334                         static double r8_0 = -0.0;
5335
5336                         g_assert (ins->sreg1 == ins->dreg);
5337                                         
5338                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &r8_0);
5339                         amd64_sse_xorpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5340                         break;
5341                 }
5342                 case OP_SIN:
5343                         EMIT_SSE2_FPFUNC (code, fsin, ins->dreg, ins->sreg1);
5344                         break;          
5345                 case OP_COS:
5346                         EMIT_SSE2_FPFUNC (code, fcos, ins->dreg, ins->sreg1);
5347                         break;          
5348                 case OP_ABS: {
5349                         static guint64 d = 0x7fffffffffffffffUL;
5350
5351                         g_assert (ins->sreg1 == ins->dreg);
5352                                         
5353                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &d);
5354                         amd64_sse_andpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
5355                         break;          
5356                 }
5357                 case OP_SQRT:
5358                         EMIT_SSE2_FPFUNC (code, fsqrt, ins->dreg, ins->sreg1);
5359                         break;
5360                 case OP_IMIN:
5361                         g_assert (cfg->opt & MONO_OPT_CMOV);
5362                         g_assert (ins->dreg == ins->sreg1);
5363                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5364                         amd64_cmov_reg_size (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2, 4);
5365                         break;
5366                 case OP_IMIN_UN:
5367                         g_assert (cfg->opt & MONO_OPT_CMOV);
5368                         g_assert (ins->dreg == ins->sreg1);
5369                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5370                         amd64_cmov_reg_size (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2, 4);
5371                         break;
5372                 case OP_IMAX:
5373                         g_assert (cfg->opt & MONO_OPT_CMOV);
5374                         g_assert (ins->dreg == ins->sreg1);
5375                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5376                         amd64_cmov_reg_size (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2, 4);
5377                         break;
5378                 case OP_IMAX_UN:
5379                         g_assert (cfg->opt & MONO_OPT_CMOV);
5380                         g_assert (ins->dreg == ins->sreg1);
5381                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
5382                         amd64_cmov_reg_size (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2, 4);
5383                         break;
5384                 case OP_LMIN:
5385                         g_assert (cfg->opt & MONO_OPT_CMOV);
5386                         g_assert (ins->dreg == ins->sreg1);
5387                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5388                         amd64_cmov_reg (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2);
5389                         break;
5390                 case OP_LMIN_UN:
5391                         g_assert (cfg->opt & MONO_OPT_CMOV);
5392                         g_assert (ins->dreg == ins->sreg1);
5393                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5394                         amd64_cmov_reg (code, X86_CC_GT, FALSE, ins->dreg, ins->sreg2);
5395                         break;
5396                 case OP_LMAX:
5397                         g_assert (cfg->opt & MONO_OPT_CMOV);
5398                         g_assert (ins->dreg == ins->sreg1);
5399                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5400                         amd64_cmov_reg (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2);
5401                         break;
5402                 case OP_LMAX_UN:
5403                         g_assert (cfg->opt & MONO_OPT_CMOV);
5404                         g_assert (ins->dreg == ins->sreg1);
5405                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
5406                         amd64_cmov_reg (code, X86_CC_LT, FALSE, ins->dreg, ins->sreg2);
5407                         break;  
5408                 case OP_X86_FPOP:
5409                         break;          
5410                 case OP_FCOMPARE:
5411                         /* 
5412                          * The two arguments are swapped because the fbranch instructions
5413                          * depend on this for the non-sse case to work.
5414                          */
5415                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5416                         break;
5417                 case OP_FCEQ: {
5418                         /* zeroing the register at the start results in 
5419                          * shorter and faster code (we can also remove the widening op)
5420                          */
5421                         guchar *unordered_check;
5422                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5423                         amd64_sse_comisd_reg_reg (code, ins->sreg1, ins->sreg2);
5424                         unordered_check = code;
5425                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5426                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
5427                         amd64_patch (unordered_check, code);
5428                         break;
5429                 }
5430                 case OP_FCLT:
5431                 case OP_FCLT_UN:
5432                         /* zeroing the register at the start results in 
5433                          * shorter and faster code (we can also remove the widening op)
5434                          */
5435                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5436                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5437                         if (ins->opcode == OP_FCLT_UN) {
5438                                 guchar *unordered_check = code;
5439                                 guchar *jump_to_end;
5440                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5441                                 amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
5442                                 jump_to_end = code;
5443                                 x86_jump8 (code, 0);
5444                                 amd64_patch (unordered_check, code);
5445                                 amd64_inc_reg (code, ins->dreg);
5446                                 amd64_patch (jump_to_end, code);
5447                         } else {
5448                                 amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
5449                         }
5450                         break;
5451                 case OP_FCGT:
5452                 case OP_FCGT_UN: {
5453                         /* zeroing the register at the start results in 
5454                          * shorter and faster code (we can also remove the widening op)
5455                          */
5456                         guchar *unordered_check;
5457                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5458                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
5459                         if (ins->opcode == OP_FCGT) {
5460                                 unordered_check = code;
5461                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5462                                 amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
5463                                 amd64_patch (unordered_check, code);
5464                         } else {
5465                                 amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
5466                         }
5467                         break;
5468                 }
5469                 case OP_FCLT_MEMBASE:
5470                 case OP_FCGT_MEMBASE:
5471                 case OP_FCLT_UN_MEMBASE:
5472                 case OP_FCGT_UN_MEMBASE:
5473                 case OP_FCEQ_MEMBASE: {
5474                         guchar *unordered_check, *jump_to_end;
5475                         int x86_cond;
5476
5477                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
5478                         amd64_sse_comisd_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
5479
5480                         switch (ins->opcode) {
5481                         case OP_FCEQ_MEMBASE:
5482                                 x86_cond = X86_CC_EQ;
5483                                 break;
5484                         case OP_FCLT_MEMBASE:
5485                         case OP_FCLT_UN_MEMBASE:
5486                                 x86_cond = X86_CC_LT;
5487                                 break;
5488                         case OP_FCGT_MEMBASE:
5489                         case OP_FCGT_UN_MEMBASE:
5490                                 x86_cond = X86_CC_GT;
5491                                 break;
5492                         default:
5493                                 g_assert_not_reached ();
5494                         }
5495
5496                         unordered_check = code;
5497                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5498                         amd64_set_reg (code, x86_cond, ins->dreg, FALSE);
5499
5500                         switch (ins->opcode) {
5501                         case OP_FCEQ_MEMBASE:
5502                         case OP_FCLT_MEMBASE:
5503                         case OP_FCGT_MEMBASE:
5504                                 amd64_patch (unordered_check, code);
5505                                 break;
5506                         case OP_FCLT_UN_MEMBASE:
5507                         case OP_FCGT_UN_MEMBASE:
5508                                 jump_to_end = code;
5509                                 x86_jump8 (code, 0);
5510                                 amd64_patch (unordered_check, code);
5511                                 amd64_inc_reg (code, ins->dreg);
5512                                 amd64_patch (jump_to_end, code);
5513                                 break;
5514                         default:
5515                                 break;
5516                         }
5517                         break;
5518                 }
5519                 case OP_FBEQ: {
5520                         guchar *jump = code;
5521                         x86_branch8 (code, X86_CC_P, 0, TRUE);
5522                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
5523                         amd64_patch (jump, code);
5524                         break;
5525                 }
5526                 case OP_FBNE_UN:
5527                         /* Branch if C013 != 100 */
5528                         /* branch if !ZF or (PF|CF) */
5529                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
5530                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5531                         EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
5532                         break;
5533                 case OP_FBLT:
5534                         EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
5535                         break;
5536                 case OP_FBLT_UN:
5537                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5538                         EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
5539                         break;
5540                 case OP_FBGT:
5541                 case OP_FBGT_UN:
5542                         if (ins->opcode == OP_FBGT) {
5543                                 guchar *br1;
5544
5545                                 /* skip branch if C1=1 */
5546                                 br1 = code;
5547                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
5548                                 /* branch if (C0 | C3) = 1 */
5549                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
5550                                 amd64_patch (br1, code);
5551                                 break;
5552                         } else {
5553                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
5554                         }
5555                         break;
5556                 case OP_FBGE: {
5557                         /* Branch if C013 == 100 or 001 */
5558                         guchar *br1;
5559
5560                         /* skip branch if C1=1 */
5561                         br1 = code;
5562                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5563                         /* branch if (C0 | C3) = 1 */
5564                         EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
5565                         amd64_patch (br1, code);
5566                         break;
5567                 }
5568                 case OP_FBGE_UN:
5569                         /* Branch if C013 == 000 */
5570                         EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
5571                         break;
5572                 case OP_FBLE: {
5573                         /* Branch if C013=000 or 100 */
5574                         guchar *br1;
5575
5576                         /* skip branch if C1=1 */
5577                         br1 = code;
5578                         x86_branch8 (code, X86_CC_P, 0, FALSE);
5579                         /* branch if C0=0 */
5580                         EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
5581                         amd64_patch (br1, code);
5582                         break;
5583                 }
5584                 case OP_FBLE_UN:
5585                         /* Branch if C013 != 001 */
5586                         EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
5587                         EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
5588                         break;
5589                 case OP_CKFINITE:
5590                         /* Transfer value to the fp stack */
5591                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
5592                         amd64_movsd_membase_reg (code, AMD64_RSP, 0, ins->sreg1);
5593                         amd64_fld_membase (code, AMD64_RSP, 0, TRUE);
5594
5595                         amd64_push_reg (code, AMD64_RAX);
5596                         amd64_fxam (code);
5597                         amd64_fnstsw (code);
5598                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0x4100);
5599                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
5600                         amd64_pop_reg (code, AMD64_RAX);
5601                         amd64_fstp (code, 0);
5602                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
5603                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
5604                         break;
5605                 case OP_TLS_GET: {
5606                         code = mono_amd64_emit_tls_get (code, ins->dreg, ins->inst_offset);
5607                         break;
5608                 }
5609                 case OP_TLS_GET_REG:
5610                         code = emit_tls_get_reg (code, ins->dreg, ins->sreg1);
5611                         break;
5612                         break;
5613                 case OP_MEMORY_BARRIER: {
5614                         switch (ins->backend.memory_barrier_kind) {
5615                         case StoreLoadBarrier:
5616                         case FullBarrier:
5617                                 /* http://blogs.sun.com/dave/resource/NHM-Pipeline-Blog-V2.txt */
5618                                 x86_prefix (code, X86_LOCK_PREFIX);
5619                                 amd64_alu_membase_imm (code, X86_ADD, AMD64_RSP, 0, 0);
5620                                 break;
5621                         }
5622                         break;
5623                 }
5624                 case OP_ATOMIC_ADD_I4:
5625                 case OP_ATOMIC_ADD_I8: {
5626                         int dreg = ins->dreg;
5627                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_I4) ? 4 : 8;
5628
5629                         if (dreg == ins->inst_basereg)
5630                                 dreg = AMD64_R11;
5631                         
5632                         if (dreg != ins->sreg2)
5633                                 amd64_mov_reg_reg (code, ins->dreg, ins->sreg2, size);
5634
5635                         x86_prefix (code, X86_LOCK_PREFIX);
5636                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
5637
5638                         if (dreg != ins->dreg)
5639                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
5640
5641                         break;
5642                 }
5643                 case OP_ATOMIC_ADD_NEW_I4:
5644                 case OP_ATOMIC_ADD_NEW_I8: {
5645                         int dreg = ins->dreg;
5646                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_NEW_I4) ? 4 : 8;
5647
5648                         if ((dreg == ins->sreg2) || (dreg == ins->inst_basereg))
5649                                 dreg = AMD64_R11;
5650
5651                         amd64_mov_reg_reg (code, dreg, ins->sreg2, size);
5652                         amd64_prefix (code, X86_LOCK_PREFIX);
5653                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
5654                         /* dreg contains the old value, add with sreg2 value */
5655                         amd64_alu_reg_reg_size (code, X86_ADD, dreg, ins->sreg2, size);
5656                         
5657                         if (ins->dreg != dreg)
5658                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
5659
5660                         break;
5661                 }
5662                 case OP_ATOMIC_EXCHANGE_I4:
5663                 case OP_ATOMIC_EXCHANGE_I8: {
5664                         guchar *br[2];
5665                         int sreg2 = ins->sreg2;
5666                         int breg = ins->inst_basereg;
5667                         guint32 size;
5668                         gboolean need_push = FALSE, rdx_pushed = FALSE;
5669
5670                         if (ins->opcode == OP_ATOMIC_EXCHANGE_I8)
5671                                 size = 8;
5672                         else
5673                                 size = 4;
5674
5675                         /* 
5676                          * See http://msdn.microsoft.com/en-us/magazine/cc302329.aspx for
5677                          * an explanation of how this works.
5678                          */
5679
5680                         /* cmpxchg uses eax as comperand, need to make sure we can use it
5681                          * hack to overcome limits in x86 reg allocator 
5682                          * (req: dreg == eax and sreg2 != eax and breg != eax) 
5683                          */
5684                         g_assert (ins->dreg == AMD64_RAX);
5685
5686                         if (breg == AMD64_RAX && ins->sreg2 == AMD64_RAX)
5687                                 /* Highly unlikely, but possible */
5688                                 need_push = TRUE;
5689
5690                         /* The pushes invalidate rsp */
5691                         if ((breg == AMD64_RAX) || need_push) {
5692                                 amd64_mov_reg_reg (code, AMD64_R11, breg, 8);
5693                                 breg = AMD64_R11;
5694                         }
5695
5696                         /* We need the EAX reg for the comparand */
5697                         if (ins->sreg2 == AMD64_RAX) {
5698                                 if (breg != AMD64_R11) {
5699                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
5700                                         sreg2 = AMD64_R11;
5701                                 } else {
5702                                         g_assert (need_push);
5703                                         amd64_push_reg (code, AMD64_RDX);
5704                                         amd64_mov_reg_reg (code, AMD64_RDX, AMD64_RAX, size);
5705                                         sreg2 = AMD64_RDX;
5706                                         rdx_pushed = TRUE;
5707                                 }
5708                         }
5709
5710                         amd64_mov_reg_membase (code, AMD64_RAX, breg, ins->inst_offset, size);
5711
5712                         br [0] = code; amd64_prefix (code, X86_LOCK_PREFIX);
5713                         amd64_cmpxchg_membase_reg_size (code, breg, ins->inst_offset, sreg2, size);
5714                         br [1] = code; amd64_branch8 (code, X86_CC_NE, -1, FALSE);
5715                         amd64_patch (br [1], br [0]);
5716
5717                         if (rdx_pushed)
5718                                 amd64_pop_reg (code, AMD64_RDX);
5719
5720                         break;
5721                 }
5722                 case OP_ATOMIC_CAS_I4:
5723                 case OP_ATOMIC_CAS_I8: {
5724                         guint32 size;
5725
5726                         if (ins->opcode == OP_ATOMIC_CAS_I8)
5727                                 size = 8;
5728                         else
5729                                 size = 4;
5730
5731                         /* 
5732                          * See http://msdn.microsoft.com/en-us/magazine/cc302329.aspx for
5733                          * an explanation of how this works.
5734                          */
5735                         g_assert (ins->sreg3 == AMD64_RAX);
5736                         g_assert (ins->sreg1 != AMD64_RAX);
5737                         g_assert (ins->sreg1 != ins->sreg2);
5738
5739                         amd64_prefix (code, X86_LOCK_PREFIX);
5740                         amd64_cmpxchg_membase_reg_size (code, ins->sreg1, ins->inst_offset, ins->sreg2, size);
5741
5742                         if (ins->dreg != AMD64_RAX)
5743                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RAX, size);
5744                         break;
5745                 }
5746                 case OP_CARD_TABLE_WBARRIER: {
5747                         int ptr = ins->sreg1;
5748                         int value = ins->sreg2;
5749                         guchar *br = 0;
5750                         int nursery_shift, card_table_shift;
5751                         gpointer card_table_mask;
5752                         size_t nursery_size;
5753
5754                         gpointer card_table = mono_gc_get_card_table (&card_table_shift, &card_table_mask);
5755                         guint64 nursery_start = (guint64)mono_gc_get_nursery (&nursery_shift, &nursery_size);
5756                         guint64 shifted_nursery_start = nursery_start >> nursery_shift;
5757
5758                         /*If either point to the stack we can simply avoid the WB. This happens due to
5759                          * optimizations revealing a stack store that was not visible when op_cardtable was emited.
5760                          */
5761                         if (ins->sreg1 == AMD64_RSP || ins->sreg2 == AMD64_RSP)
5762                                 continue;
5763
5764                         /*
5765                          * We need one register we can clobber, we choose EDX and make sreg1
5766                          * fixed EAX to work around limitations in the local register allocator.
5767                          * sreg2 might get allocated to EDX, but that is not a problem since
5768                          * we use it before clobbering EDX.
5769                          */
5770                         g_assert (ins->sreg1 == AMD64_RAX);
5771
5772                         /*
5773                          * This is the code we produce:
5774                          *
5775                          *   edx = value
5776                          *   edx >>= nursery_shift
5777                          *   cmp edx, (nursery_start >> nursery_shift)
5778                          *   jne done
5779                          *   edx = ptr
5780                          *   edx >>= card_table_shift
5781                          *   edx += cardtable
5782                          *   [edx] = 1
5783                          * done:
5784                          */
5785
5786                         if (mono_gc_card_table_nursery_check ()) {
5787                                 if (value != AMD64_RDX)
5788                                         amd64_mov_reg_reg (code, AMD64_RDX, value, 8);
5789                                 amd64_shift_reg_imm (code, X86_SHR, AMD64_RDX, nursery_shift);
5790                                 if (shifted_nursery_start >> 31) {
5791                                         /*
5792                                          * The value we need to compare against is 64 bits, so we need
5793                                          * another spare register.  We use RBX, which we save and
5794                                          * restore.
5795                                          */
5796                                         amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RBX, 8);
5797                                         amd64_mov_reg_imm (code, AMD64_RBX, shifted_nursery_start);
5798                                         amd64_alu_reg_reg (code, X86_CMP, AMD64_RDX, AMD64_RBX);
5799                                         amd64_mov_reg_membase (code, AMD64_RBX, AMD64_RSP, -8, 8);
5800                                 } else {
5801                                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RDX, shifted_nursery_start);
5802                                 }
5803                                 br = code; x86_branch8 (code, X86_CC_NE, -1, FALSE);
5804                         }
5805                         amd64_mov_reg_reg (code, AMD64_RDX, ptr, 8);
5806                         amd64_shift_reg_imm (code, X86_SHR, AMD64_RDX, card_table_shift);
5807                         if (card_table_mask)
5808                                 amd64_alu_reg_imm (code, X86_AND, AMD64_RDX, (guint32)(guint64)card_table_mask);
5809
5810                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, card_table);
5811                         amd64_alu_reg_membase (code, X86_ADD, AMD64_RDX, AMD64_RIP, 0);
5812
5813                         amd64_mov_membase_imm (code, AMD64_RDX, 0, 1, 1);
5814
5815                         if (mono_gc_card_table_nursery_check ())
5816                                 x86_patch (br, code);
5817                         break;
5818                 }
5819 #ifdef MONO_ARCH_SIMD_INTRINSICS
5820                 /* TODO: Some of these IR opcodes are marked as no clobber when they indeed do. */
5821                 case OP_ADDPS:
5822                         amd64_sse_addps_reg_reg (code, ins->sreg1, ins->sreg2);
5823                         break;
5824                 case OP_DIVPS:
5825                         amd64_sse_divps_reg_reg (code, ins->sreg1, ins->sreg2);
5826                         break;
5827                 case OP_MULPS:
5828                         amd64_sse_mulps_reg_reg (code, ins->sreg1, ins->sreg2);
5829                         break;
5830                 case OP_SUBPS:
5831                         amd64_sse_subps_reg_reg (code, ins->sreg1, ins->sreg2);
5832                         break;
5833                 case OP_MAXPS:
5834                         amd64_sse_maxps_reg_reg (code, ins->sreg1, ins->sreg2);
5835                         break;
5836                 case OP_MINPS:
5837                         amd64_sse_minps_reg_reg (code, ins->sreg1, ins->sreg2);
5838                         break;
5839                 case OP_COMPPS:
5840                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7);
5841                         amd64_sse_cmpps_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5842                         break;
5843                 case OP_ANDPS:
5844                         amd64_sse_andps_reg_reg (code, ins->sreg1, ins->sreg2);
5845                         break;
5846                 case OP_ANDNPS:
5847                         amd64_sse_andnps_reg_reg (code, ins->sreg1, ins->sreg2);
5848                         break;
5849                 case OP_ORPS:
5850                         amd64_sse_orps_reg_reg (code, ins->sreg1, ins->sreg2);
5851                         break;
5852                 case OP_XORPS:
5853                         amd64_sse_xorps_reg_reg (code, ins->sreg1, ins->sreg2);
5854                         break;
5855                 case OP_SQRTPS:
5856                         amd64_sse_sqrtps_reg_reg (code, ins->dreg, ins->sreg1);
5857                         break;
5858                 case OP_RSQRTPS:
5859                         amd64_sse_rsqrtps_reg_reg (code, ins->dreg, ins->sreg1);
5860                         break;
5861                 case OP_RCPPS:
5862                         amd64_sse_rcpps_reg_reg (code, ins->dreg, ins->sreg1);
5863                         break;
5864                 case OP_ADDSUBPS:
5865                         amd64_sse_addsubps_reg_reg (code, ins->sreg1, ins->sreg2);
5866                         break;
5867                 case OP_HADDPS:
5868                         amd64_sse_haddps_reg_reg (code, ins->sreg1, ins->sreg2);
5869                         break;
5870                 case OP_HSUBPS:
5871                         amd64_sse_hsubps_reg_reg (code, ins->sreg1, ins->sreg2);
5872                         break;
5873                 case OP_DUPPS_HIGH:
5874                         amd64_sse_movshdup_reg_reg (code, ins->dreg, ins->sreg1);
5875                         break;
5876                 case OP_DUPPS_LOW:
5877                         amd64_sse_movsldup_reg_reg (code, ins->dreg, ins->sreg1);
5878                         break;
5879
5880                 case OP_PSHUFLEW_HIGH:
5881                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5882                         amd64_sse_pshufhw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5883                         break;
5884                 case OP_PSHUFLEW_LOW:
5885                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5886                         amd64_sse_pshuflw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5887                         break;
5888                 case OP_PSHUFLED:
5889                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5890                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
5891                         break;
5892                 case OP_SHUFPS:
5893                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0xFF);
5894                         amd64_sse_shufps_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5895                         break;
5896                 case OP_SHUFPD:
5897                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 0x3);
5898                         amd64_sse_shufpd_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5899                         break;
5900
5901                 case OP_ADDPD:
5902                         amd64_sse_addpd_reg_reg (code, ins->sreg1, ins->sreg2);
5903                         break;
5904                 case OP_DIVPD:
5905                         amd64_sse_divpd_reg_reg (code, ins->sreg1, ins->sreg2);
5906                         break;
5907                 case OP_MULPD:
5908                         amd64_sse_mulpd_reg_reg (code, ins->sreg1, ins->sreg2);
5909                         break;
5910                 case OP_SUBPD:
5911                         amd64_sse_subpd_reg_reg (code, ins->sreg1, ins->sreg2);
5912                         break;
5913                 case OP_MAXPD:
5914                         amd64_sse_maxpd_reg_reg (code, ins->sreg1, ins->sreg2);
5915                         break;
5916                 case OP_MINPD:
5917                         amd64_sse_minpd_reg_reg (code, ins->sreg1, ins->sreg2);
5918                         break;
5919                 case OP_COMPPD:
5920                         g_assert (ins->inst_c0 >= 0 && ins->inst_c0 <= 7);
5921                         amd64_sse_cmppd_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
5922                         break;
5923                 case OP_ANDPD:
5924                         amd64_sse_andpd_reg_reg (code, ins->sreg1, ins->sreg2);
5925                         break;
5926                 case OP_ANDNPD:
5927                         amd64_sse_andnpd_reg_reg (code, ins->sreg1, ins->sreg2);
5928                         break;
5929                 case OP_ORPD:
5930                         amd64_sse_orpd_reg_reg (code, ins->sreg1, ins->sreg2);
5931                         break;
5932                 case OP_XORPD:
5933                         amd64_sse_xorpd_reg_reg (code, ins->sreg1, ins->sreg2);
5934                         break;
5935                 case OP_SQRTPD:
5936                         amd64_sse_sqrtpd_reg_reg (code, ins->dreg, ins->sreg1);
5937                         break;
5938                 case OP_ADDSUBPD:
5939                         amd64_sse_addsubpd_reg_reg (code, ins->sreg1, ins->sreg2);
5940                         break;
5941                 case OP_HADDPD:
5942                         amd64_sse_haddpd_reg_reg (code, ins->sreg1, ins->sreg2);
5943                         break;
5944                 case OP_HSUBPD:
5945                         amd64_sse_hsubpd_reg_reg (code, ins->sreg1, ins->sreg2);
5946                         break;
5947                 case OP_DUPPD:
5948                         amd64_sse_movddup_reg_reg (code, ins->dreg, ins->sreg1);
5949                         break;
5950
5951                 case OP_EXTRACT_MASK:
5952                         amd64_sse_pmovmskb_reg_reg (code, ins->dreg, ins->sreg1);
5953                         break;
5954
5955                 case OP_PAND:
5956                         amd64_sse_pand_reg_reg (code, ins->sreg1, ins->sreg2);
5957                         break;
5958                 case OP_POR:
5959                         amd64_sse_por_reg_reg (code, ins->sreg1, ins->sreg2);
5960                         break;
5961                 case OP_PXOR:
5962                         amd64_sse_pxor_reg_reg (code, ins->sreg1, ins->sreg2);
5963                         break;
5964
5965                 case OP_PADDB:
5966                         amd64_sse_paddb_reg_reg (code, ins->sreg1, ins->sreg2);
5967                         break;
5968                 case OP_PADDW:
5969                         amd64_sse_paddw_reg_reg (code, ins->sreg1, ins->sreg2);
5970                         break;
5971                 case OP_PADDD:
5972                         amd64_sse_paddd_reg_reg (code, ins->sreg1, ins->sreg2);
5973                         break;
5974                 case OP_PADDQ:
5975                         amd64_sse_paddq_reg_reg (code, ins->sreg1, ins->sreg2);
5976                         break;
5977
5978                 case OP_PSUBB:
5979                         amd64_sse_psubb_reg_reg (code, ins->sreg1, ins->sreg2);
5980                         break;
5981                 case OP_PSUBW:
5982                         amd64_sse_psubw_reg_reg (code, ins->sreg1, ins->sreg2);
5983                         break;
5984                 case OP_PSUBD:
5985                         amd64_sse_psubd_reg_reg (code, ins->sreg1, ins->sreg2);
5986                         break;
5987                 case OP_PSUBQ:
5988                         amd64_sse_psubq_reg_reg (code, ins->sreg1, ins->sreg2);
5989                         break;
5990
5991                 case OP_PMAXB_UN:
5992                         amd64_sse_pmaxub_reg_reg (code, ins->sreg1, ins->sreg2);
5993                         break;
5994                 case OP_PMAXW_UN:
5995                         amd64_sse_pmaxuw_reg_reg (code, ins->sreg1, ins->sreg2);
5996                         break;
5997                 case OP_PMAXD_UN:
5998                         amd64_sse_pmaxud_reg_reg (code, ins->sreg1, ins->sreg2);
5999                         break;
6000                 
6001                 case OP_PMAXB:
6002                         amd64_sse_pmaxsb_reg_reg (code, ins->sreg1, ins->sreg2);
6003                         break;
6004                 case OP_PMAXW:
6005                         amd64_sse_pmaxsw_reg_reg (code, ins->sreg1, ins->sreg2);
6006                         break;
6007                 case OP_PMAXD:
6008                         amd64_sse_pmaxsd_reg_reg (code, ins->sreg1, ins->sreg2);
6009                         break;
6010
6011                 case OP_PAVGB_UN:
6012                         amd64_sse_pavgb_reg_reg (code, ins->sreg1, ins->sreg2);
6013                         break;
6014                 case OP_PAVGW_UN:
6015                         amd64_sse_pavgw_reg_reg (code, ins->sreg1, ins->sreg2);
6016                         break;
6017
6018                 case OP_PMINB_UN:
6019                         amd64_sse_pminub_reg_reg (code, ins->sreg1, ins->sreg2);
6020                         break;
6021                 case OP_PMINW_UN:
6022                         amd64_sse_pminuw_reg_reg (code, ins->sreg1, ins->sreg2);
6023                         break;
6024                 case OP_PMIND_UN:
6025                         amd64_sse_pminud_reg_reg (code, ins->sreg1, ins->sreg2);
6026                         break;
6027
6028                 case OP_PMINB:
6029                         amd64_sse_pminsb_reg_reg (code, ins->sreg1, ins->sreg2);
6030                         break;
6031                 case OP_PMINW:
6032                         amd64_sse_pminsw_reg_reg (code, ins->sreg1, ins->sreg2);
6033                         break;
6034                 case OP_PMIND:
6035                         amd64_sse_pminsd_reg_reg (code, ins->sreg1, ins->sreg2);
6036                         break;
6037
6038                 case OP_PCMPEQB:
6039                         amd64_sse_pcmpeqb_reg_reg (code, ins->sreg1, ins->sreg2);
6040                         break;
6041                 case OP_PCMPEQW:
6042                         amd64_sse_pcmpeqw_reg_reg (code, ins->sreg1, ins->sreg2);
6043                         break;
6044                 case OP_PCMPEQD:
6045                         amd64_sse_pcmpeqd_reg_reg (code, ins->sreg1, ins->sreg2);
6046                         break;
6047                 case OP_PCMPEQQ:
6048                         amd64_sse_pcmpeqq_reg_reg (code, ins->sreg1, ins->sreg2);
6049                         break;
6050
6051                 case OP_PCMPGTB:
6052                         amd64_sse_pcmpgtb_reg_reg (code, ins->sreg1, ins->sreg2);
6053                         break;
6054                 case OP_PCMPGTW:
6055                         amd64_sse_pcmpgtw_reg_reg (code, ins->sreg1, ins->sreg2);
6056                         break;
6057                 case OP_PCMPGTD:
6058                         amd64_sse_pcmpgtd_reg_reg (code, ins->sreg1, ins->sreg2);
6059                         break;
6060                 case OP_PCMPGTQ:
6061                         amd64_sse_pcmpgtq_reg_reg (code, ins->sreg1, ins->sreg2);
6062                         break;
6063
6064                 case OP_PSUM_ABS_DIFF:
6065                         amd64_sse_psadbw_reg_reg (code, ins->sreg1, ins->sreg2);
6066                         break;
6067
6068                 case OP_UNPACK_LOWB:
6069                         amd64_sse_punpcklbw_reg_reg (code, ins->sreg1, ins->sreg2);
6070                         break;
6071                 case OP_UNPACK_LOWW:
6072                         amd64_sse_punpcklwd_reg_reg (code, ins->sreg1, ins->sreg2);
6073                         break;
6074                 case OP_UNPACK_LOWD:
6075                         amd64_sse_punpckldq_reg_reg (code, ins->sreg1, ins->sreg2);
6076                         break;
6077                 case OP_UNPACK_LOWQ:
6078                         amd64_sse_punpcklqdq_reg_reg (code, ins->sreg1, ins->sreg2);
6079                         break;
6080                 case OP_UNPACK_LOWPS:
6081                         amd64_sse_unpcklps_reg_reg (code, ins->sreg1, ins->sreg2);
6082                         break;
6083                 case OP_UNPACK_LOWPD:
6084                         amd64_sse_unpcklpd_reg_reg (code, ins->sreg1, ins->sreg2);
6085                         break;
6086
6087                 case OP_UNPACK_HIGHB:
6088                         amd64_sse_punpckhbw_reg_reg (code, ins->sreg1, ins->sreg2);
6089                         break;
6090                 case OP_UNPACK_HIGHW:
6091                         amd64_sse_punpckhwd_reg_reg (code, ins->sreg1, ins->sreg2);
6092                         break;
6093                 case OP_UNPACK_HIGHD:
6094                         amd64_sse_punpckhdq_reg_reg (code, ins->sreg1, ins->sreg2);
6095                         break;
6096                 case OP_UNPACK_HIGHQ:
6097                         amd64_sse_punpckhqdq_reg_reg (code, ins->sreg1, ins->sreg2);
6098                         break;
6099                 case OP_UNPACK_HIGHPS:
6100                         amd64_sse_unpckhps_reg_reg (code, ins->sreg1, ins->sreg2);
6101                         break;
6102                 case OP_UNPACK_HIGHPD:
6103                         amd64_sse_unpckhpd_reg_reg (code, ins->sreg1, ins->sreg2);
6104                         break;
6105
6106                 case OP_PACKW:
6107                         amd64_sse_packsswb_reg_reg (code, ins->sreg1, ins->sreg2);
6108                         break;
6109                 case OP_PACKD:
6110                         amd64_sse_packssdw_reg_reg (code, ins->sreg1, ins->sreg2);
6111                         break;
6112                 case OP_PACKW_UN:
6113                         amd64_sse_packuswb_reg_reg (code, ins->sreg1, ins->sreg2);
6114                         break;
6115                 case OP_PACKD_UN:
6116                         amd64_sse_packusdw_reg_reg (code, ins->sreg1, ins->sreg2);
6117                         break;
6118
6119                 case OP_PADDB_SAT_UN:
6120                         amd64_sse_paddusb_reg_reg (code, ins->sreg1, ins->sreg2);
6121                         break;
6122                 case OP_PSUBB_SAT_UN:
6123                         amd64_sse_psubusb_reg_reg (code, ins->sreg1, ins->sreg2);
6124                         break;
6125                 case OP_PADDW_SAT_UN:
6126                         amd64_sse_paddusw_reg_reg (code, ins->sreg1, ins->sreg2);
6127                         break;
6128                 case OP_PSUBW_SAT_UN:
6129                         amd64_sse_psubusw_reg_reg (code, ins->sreg1, ins->sreg2);
6130                         break;
6131
6132                 case OP_PADDB_SAT:
6133                         amd64_sse_paddsb_reg_reg (code, ins->sreg1, ins->sreg2);
6134                         break;
6135                 case OP_PSUBB_SAT:
6136                         amd64_sse_psubsb_reg_reg (code, ins->sreg1, ins->sreg2);
6137                         break;
6138                 case OP_PADDW_SAT:
6139                         amd64_sse_paddsw_reg_reg (code, ins->sreg1, ins->sreg2);
6140                         break;
6141                 case OP_PSUBW_SAT:
6142                         amd64_sse_psubsw_reg_reg (code, ins->sreg1, ins->sreg2);
6143                         break;
6144                         
6145                 case OP_PMULW:
6146                         amd64_sse_pmullw_reg_reg (code, ins->sreg1, ins->sreg2);
6147                         break;
6148                 case OP_PMULD:
6149                         amd64_sse_pmulld_reg_reg (code, ins->sreg1, ins->sreg2);
6150                         break;
6151                 case OP_PMULQ:
6152                         amd64_sse_pmuludq_reg_reg (code, ins->sreg1, ins->sreg2);
6153                         break;
6154                 case OP_PMULW_HIGH_UN:
6155                         amd64_sse_pmulhuw_reg_reg (code, ins->sreg1, ins->sreg2);
6156                         break;
6157                 case OP_PMULW_HIGH:
6158                         amd64_sse_pmulhw_reg_reg (code, ins->sreg1, ins->sreg2);
6159                         break;
6160
6161                 case OP_PSHRW:
6162                         amd64_sse_psrlw_reg_imm (code, ins->dreg, ins->inst_imm);
6163                         break;
6164                 case OP_PSHRW_REG:
6165                         amd64_sse_psrlw_reg_reg (code, ins->dreg, ins->sreg2);
6166                         break;
6167
6168                 case OP_PSARW:
6169                         amd64_sse_psraw_reg_imm (code, ins->dreg, ins->inst_imm);
6170                         break;
6171                 case OP_PSARW_REG:
6172                         amd64_sse_psraw_reg_reg (code, ins->dreg, ins->sreg2);
6173                         break;
6174
6175                 case OP_PSHLW:
6176                         amd64_sse_psllw_reg_imm (code, ins->dreg, ins->inst_imm);
6177                         break;
6178                 case OP_PSHLW_REG:
6179                         amd64_sse_psllw_reg_reg (code, ins->dreg, ins->sreg2);
6180                         break;
6181
6182                 case OP_PSHRD:
6183                         amd64_sse_psrld_reg_imm (code, ins->dreg, ins->inst_imm);
6184                         break;
6185                 case OP_PSHRD_REG:
6186                         amd64_sse_psrld_reg_reg (code, ins->dreg, ins->sreg2);
6187                         break;
6188
6189                 case OP_PSARD:
6190                         amd64_sse_psrad_reg_imm (code, ins->dreg, ins->inst_imm);
6191                         break;
6192                 case OP_PSARD_REG:
6193                         amd64_sse_psrad_reg_reg (code, ins->dreg, ins->sreg2);
6194                         break;
6195
6196                 case OP_PSHLD:
6197                         amd64_sse_pslld_reg_imm (code, ins->dreg, ins->inst_imm);
6198                         break;
6199                 case OP_PSHLD_REG:
6200                         amd64_sse_pslld_reg_reg (code, ins->dreg, ins->sreg2);
6201                         break;
6202
6203                 case OP_PSHRQ:
6204                         amd64_sse_psrlq_reg_imm (code, ins->dreg, ins->inst_imm);
6205                         break;
6206                 case OP_PSHRQ_REG:
6207                         amd64_sse_psrlq_reg_reg (code, ins->dreg, ins->sreg2);
6208                         break;
6209                 
6210                 /*TODO: This is appart of the sse spec but not added
6211                 case OP_PSARQ:
6212                         amd64_sse_psraq_reg_imm (code, ins->dreg, ins->inst_imm);
6213                         break;
6214                 case OP_PSARQ_REG:
6215                         amd64_sse_psraq_reg_reg (code, ins->dreg, ins->sreg2);
6216                         break;  
6217                 */
6218         
6219                 case OP_PSHLQ:
6220                         amd64_sse_psllq_reg_imm (code, ins->dreg, ins->inst_imm);
6221                         break;
6222                 case OP_PSHLQ_REG:
6223                         amd64_sse_psllq_reg_reg (code, ins->dreg, ins->sreg2);
6224                         break;  
6225                 case OP_CVTDQ2PD:
6226                         amd64_sse_cvtdq2pd_reg_reg (code, ins->dreg, ins->sreg1);
6227                         break;
6228                 case OP_CVTDQ2PS:
6229                         amd64_sse_cvtdq2ps_reg_reg (code, ins->dreg, ins->sreg1);
6230                         break;
6231                 case OP_CVTPD2DQ:
6232                         amd64_sse_cvtpd2dq_reg_reg (code, ins->dreg, ins->sreg1);
6233                         break;
6234                 case OP_CVTPD2PS:
6235                         amd64_sse_cvtpd2ps_reg_reg (code, ins->dreg, ins->sreg1);
6236                         break;
6237                 case OP_CVTPS2DQ:
6238                         amd64_sse_cvtps2dq_reg_reg (code, ins->dreg, ins->sreg1);
6239                         break;
6240                 case OP_CVTPS2PD:
6241                         amd64_sse_cvtps2pd_reg_reg (code, ins->dreg, ins->sreg1);
6242                         break;
6243                 case OP_CVTTPD2DQ:
6244                         amd64_sse_cvttpd2dq_reg_reg (code, ins->dreg, ins->sreg1);
6245                         break;
6246                 case OP_CVTTPS2DQ:
6247                         amd64_sse_cvttps2dq_reg_reg (code, ins->dreg, ins->sreg1);
6248                         break;
6249
6250                 case OP_ICONV_TO_X:
6251                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6252                         break;
6253                 case OP_EXTRACT_I4:
6254                         amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6255                         break;
6256                 case OP_EXTRACT_I8:
6257                         if (ins->inst_c0) {
6258                                 amd64_movhlps_reg_reg (code, AMD64_XMM15, ins->sreg1);
6259                                 amd64_movd_reg_xreg_size (code, ins->dreg, AMD64_XMM15, 8);
6260                         } else {
6261                                 amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 8);
6262                         }
6263                         break;
6264                 case OP_EXTRACT_I1:
6265                 case OP_EXTRACT_U1:
6266                         amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6267                         if (ins->inst_c0)
6268                                 amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_c0 * 8);
6269                         amd64_widen_reg (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I1, FALSE);
6270                         break;
6271                 case OP_EXTRACT_I2:
6272                 case OP_EXTRACT_U2:
6273                         /*amd64_movd_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6274                         if (ins->inst_c0)
6275                                 amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, 16, 4);*/
6276                         amd64_sse_pextrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
6277                         amd64_widen_reg_size (code, ins->dreg, ins->dreg, ins->opcode == OP_EXTRACT_I2, TRUE, 4);
6278                         break;
6279                 case OP_EXTRACT_R8:
6280                         if (ins->inst_c0)
6281                                 amd64_movhlps_reg_reg (code, ins->dreg, ins->sreg1);
6282                         else
6283                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6284                         break;
6285                 case OP_INSERT_I2:
6286                         amd64_sse_pinsrw_reg_reg_imm (code, ins->sreg1, ins->sreg2, ins->inst_c0);
6287                         break;
6288                 case OP_EXTRACTX_U2:
6289                         amd64_sse_pextrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0);
6290                         break;
6291                 case OP_INSERTX_U1_SLOW:
6292                         /*sreg1 is the extracted ireg (scratch)
6293                         /sreg2 is the to be inserted ireg (scratch)
6294                         /dreg is the xreg to receive the value*/
6295
6296                         /*clear the bits from the extracted word*/
6297                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_c0 & 1 ? 0x00FF : 0xFF00);
6298                         /*shift the value to insert if needed*/
6299                         if (ins->inst_c0 & 1)
6300                                 amd64_shift_reg_imm_size (code, X86_SHL, ins->sreg2, 8, 4);
6301                         /*join them together*/
6302                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
6303                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_c0 / 2);
6304                         break;
6305                 case OP_INSERTX_I4_SLOW:
6306                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg2, ins->inst_c0 * 2);
6307                         amd64_shift_reg_imm (code, X86_SHR, ins->sreg2, 16);
6308                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg2, ins->inst_c0 * 2 + 1);
6309                         break;
6310                 case OP_INSERTX_I8_SLOW:
6311                         amd64_movd_xreg_reg_size(code, AMD64_XMM15, ins->sreg2, 8);
6312                         if (ins->inst_c0)
6313                                 amd64_movlhps_reg_reg (code, ins->dreg, AMD64_XMM15);
6314                         else
6315                                 amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM15);
6316                         break;
6317
6318                 case OP_INSERTX_R4_SLOW:
6319                         switch (ins->inst_c0) {
6320                         case 0:
6321                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6322                                 break;
6323                         case 1:
6324                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(1, 0, 2, 3));
6325                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6326                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(1, 0, 2, 3));
6327                                 break;
6328                         case 2:
6329                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(2, 1, 0, 3));
6330                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6331                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(2, 1, 0, 3));
6332                                 break;
6333                         case 3:
6334                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(3, 1, 2, 0));
6335                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg2);
6336                                 amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, mono_simd_shuffle_mask(3, 1, 2, 0));
6337                                 break;
6338                         }
6339                         break;
6340                 case OP_INSERTX_R8_SLOW:
6341                         if (ins->inst_c0)
6342                                 amd64_movlhps_reg_reg (code, ins->dreg, ins->sreg2);
6343                         else
6344                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg2);
6345                         break;
6346                 case OP_STOREX_MEMBASE_REG:
6347                 case OP_STOREX_MEMBASE:
6348                         amd64_sse_movups_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1);
6349                         break;
6350                 case OP_LOADX_MEMBASE:
6351                         amd64_sse_movups_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6352                         break;
6353                 case OP_LOADX_ALIGNED_MEMBASE:
6354                         amd64_sse_movaps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6355                         break;
6356                 case OP_STOREX_ALIGNED_MEMBASE_REG:
6357                         amd64_sse_movaps_membase_reg (code, ins->dreg, ins->inst_offset, ins->sreg1);
6358                         break;
6359                 case OP_STOREX_NTA_MEMBASE_REG:
6360                         amd64_sse_movntps_reg_membase (code, ins->dreg, ins->sreg1, ins->inst_offset);
6361                         break;
6362                 case OP_PREFETCH_MEMBASE:
6363                         amd64_sse_prefetch_reg_membase (code, ins->backend.arg_info, ins->sreg1, ins->inst_offset);
6364                         break;
6365
6366                 case OP_XMOVE:
6367                         /*FIXME the peephole pass should have killed this*/
6368                         if (ins->dreg != ins->sreg1)
6369                                 amd64_sse_movaps_reg_reg (code, ins->dreg, ins->sreg1);
6370                         break;          
6371                 case OP_XZERO:
6372                         amd64_sse_pxor_reg_reg (code, ins->dreg, ins->dreg);
6373                         break;
6374                 case OP_ICONV_TO_R8_RAW:
6375                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6376                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
6377                         break;
6378
6379                 case OP_FCONV_TO_R8_X:
6380                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6381                         break;
6382
6383                 case OP_XCONV_R8_TO_I4:
6384                         amd64_sse_cvttsd2si_reg_xreg_size (code, ins->dreg, ins->sreg1, 4);
6385                         switch (ins->backend.source_opcode) {
6386                         case OP_FCONV_TO_I1:
6387                                 amd64_widen_reg (code, ins->dreg, ins->dreg, TRUE, FALSE);
6388                                 break;
6389                         case OP_FCONV_TO_U1:
6390                                 amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
6391                                 break;
6392                         case OP_FCONV_TO_I2:
6393                                 amd64_widen_reg (code, ins->dreg, ins->dreg, TRUE, TRUE);
6394                                 break;
6395                         case OP_FCONV_TO_U2:
6396                                 amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, TRUE);
6397                                 break;
6398                         }                       
6399                         break;
6400
6401                 case OP_EXPAND_I2:
6402                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, 0);
6403                         amd64_sse_pinsrw_reg_reg_imm (code, ins->dreg, ins->sreg1, 1);
6404                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6405                         break;
6406                 case OP_EXPAND_I4:
6407                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 4);
6408                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6409                         break;
6410                 case OP_EXPAND_I8:
6411                         amd64_movd_xreg_reg_size (code, ins->dreg, ins->sreg1, 8);
6412                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0x44);
6413                         break;
6414                 case OP_EXPAND_R4:
6415                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6416                         amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->dreg);
6417                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0);
6418                         break;
6419                 case OP_EXPAND_R8:
6420                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
6421                         amd64_sse_pshufd_reg_reg_imm (code, ins->dreg, ins->dreg, 0x44);
6422                         break;
6423 #endif
6424                 case OP_LIVERANGE_START: {
6425                         if (cfg->verbose_level > 1)
6426                                 printf ("R%d START=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code));
6427                         MONO_VARINFO (cfg, ins->inst_c0)->live_range_start = code - cfg->native_code;
6428                         break;
6429                 }
6430                 case OP_LIVERANGE_END: {
6431                         if (cfg->verbose_level > 1)
6432                                 printf ("R%d END=0x%x\n", MONO_VARINFO (cfg, ins->inst_c0)->vreg, (int)(code - cfg->native_code));
6433                         MONO_VARINFO (cfg, ins->inst_c0)->live_range_end = code - cfg->native_code;
6434                         break;
6435                 }
6436                 case OP_NACL_GC_SAFE_POINT: {
6437 #if defined(__native_client_codegen__) && defined(__native_client_gc__)
6438                         if (cfg->compile_aot)
6439                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)mono_nacl_gc, TRUE);
6440                         else {
6441                                 guint8 *br [1];
6442
6443                                 amd64_mov_reg_imm_size (code, AMD64_R11, (gpointer)&__nacl_thread_suspension_needed, 4);
6444                                 amd64_test_membase_imm_size (code, AMD64_R11, 0, 0xFFFFFFFF, 4);
6445                                 br[0] = code; x86_branch8 (code, X86_CC_EQ, 0, FALSE);
6446                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)mono_nacl_gc, TRUE);
6447                                 amd64_patch (br[0], code);
6448                         }
6449 #endif
6450                         break;
6451                 }
6452                 case OP_GC_LIVENESS_DEF:
6453                 case OP_GC_LIVENESS_USE:
6454                 case OP_GC_PARAM_SLOT_LIVENESS_DEF:
6455                         ins->backend.pc_offset = code - cfg->native_code;
6456                         break;
6457                 case OP_GC_SPILL_SLOT_LIVENESS_DEF:
6458                         ins->backend.pc_offset = code - cfg->native_code;
6459                         bb->spill_slot_defs = g_slist_prepend_mempool (cfg->mempool, bb->spill_slot_defs, ins);
6460                         break;
6461                 default:
6462                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
6463                         g_assert_not_reached ();
6464                 }
6465
6466                 if ((code - cfg->native_code - offset) > max_len) {
6467 #if !defined(__native_client_codegen__)
6468                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %ld)",
6469                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
6470                         g_assert_not_reached ();
6471 #endif
6472                 }
6473                
6474                 last_ins = ins;
6475                 last_offset = offset;
6476         }
6477
6478         cfg->code_len = code - cfg->native_code;
6479 }
6480
6481 #endif /* DISABLE_JIT */
6482
6483 void
6484 mono_arch_register_lowlevel_calls (void)
6485 {
6486         /* The signature doesn't matter */
6487         mono_register_jit_icall (mono_amd64_throw_exception, "mono_amd64_throw_exception", mono_create_icall_signature ("void"), TRUE);
6488 }
6489
6490 void
6491 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, MonoCodeManager *dyn_code_mp, gboolean run_cctors)
6492 {
6493         MonoJumpInfo *patch_info;
6494         gboolean compile_aot = !run_cctors;
6495
6496         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
6497                 unsigned char *ip = patch_info->ip.i + code;
6498                 unsigned char *target;
6499
6500                 if (compile_aot) {
6501                         switch (patch_info->type) {
6502                         case MONO_PATCH_INFO_BB:
6503                         case MONO_PATCH_INFO_LABEL:
6504                                 break;
6505                         default:
6506                                 /* No need to patch these */
6507                                 continue;
6508                         }
6509                 }
6510
6511                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
6512
6513                 switch (patch_info->type) {
6514                 case MONO_PATCH_INFO_NONE:
6515                         continue;
6516                 case MONO_PATCH_INFO_METHOD_REL:
6517                 case MONO_PATCH_INFO_R8:
6518                 case MONO_PATCH_INFO_R4:
6519                         g_assert_not_reached ();
6520                         continue;
6521                 case MONO_PATCH_INFO_BB:
6522                         break;
6523                 default:
6524                         break;
6525                 }
6526
6527                 /* 
6528                  * Debug code to help track down problems where the target of a near call is
6529                  * is not valid.
6530                  */
6531                 if (amd64_is_near_call (ip)) {
6532                         gint64 disp = (guint8*)target - (guint8*)ip;
6533
6534                         if (!amd64_is_imm32 (disp)) {
6535                                 printf ("TYPE: %d\n", patch_info->type);
6536                                 switch (patch_info->type) {
6537                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
6538                                         printf ("V: %s\n", patch_info->data.name);
6539                                         break;
6540                                 case MONO_PATCH_INFO_METHOD_JUMP:
6541                                 case MONO_PATCH_INFO_METHOD:
6542                                         printf ("V: %s\n", patch_info->data.method->name);
6543                                         break;
6544                                 default:
6545                                         break;
6546                                 }
6547                         }
6548                 }
6549
6550                 amd64_patch (ip, (gpointer)target);
6551         }
6552 }
6553
6554 #ifndef DISABLE_JIT
6555
6556 static int
6557 get_max_epilog_size (MonoCompile *cfg)
6558 {
6559         int max_epilog_size = 16;
6560         
6561         if (cfg->method->save_lmf)
6562                 max_epilog_size += 256;
6563         
6564         if (mono_jit_trace_calls != NULL)
6565                 max_epilog_size += 50;
6566
6567         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
6568                 max_epilog_size += 50;
6569
6570         max_epilog_size += (AMD64_NREG * 2);
6571
6572         return max_epilog_size;
6573 }
6574
6575 /*
6576  * This macro is used for testing whenever the unwinder works correctly at every point
6577  * where an async exception can happen.
6578  */
6579 /* This will generate a SIGSEGV at the given point in the code */
6580 #define async_exc_point(code) do { \
6581     if (mono_inject_async_exc_method && mono_method_desc_full_match (mono_inject_async_exc_method, cfg->method)) { \
6582          if (cfg->arch.async_point_count == mono_inject_async_exc_pos) \
6583              amd64_mov_reg_mem (code, AMD64_RAX, 0, 4); \
6584          cfg->arch.async_point_count ++; \
6585     } \
6586 } while (0)
6587
6588 guint8 *
6589 mono_arch_emit_prolog (MonoCompile *cfg)
6590 {
6591         MonoMethod *method = cfg->method;
6592         MonoBasicBlock *bb;
6593         MonoMethodSignature *sig;
6594         MonoInst *ins;
6595         int alloc_size, pos, i, cfa_offset, quad, max_epilog_size;
6596         guint8 *code;
6597         CallInfo *cinfo;
6598         MonoInst *lmf_var = cfg->arch.lmf_var;
6599         gboolean args_clobbered = FALSE;
6600         gboolean trace = FALSE;
6601 #ifdef __native_client_codegen__
6602         guint alignment_check;
6603 #endif
6604
6605         cfg->code_size =  MAX (cfg->header->code_size * 4, 10240);
6606
6607 #if defined(__default_codegen__)
6608         code = cfg->native_code = g_malloc (cfg->code_size);
6609 #elif defined(__native_client_codegen__)
6610         /* native_code_alloc is not 32-byte aligned, native_code is. */
6611         cfg->native_code_alloc = g_malloc (cfg->code_size + kNaClAlignment);
6612
6613         /* Align native_code to next nearest kNaclAlignment byte. */
6614         cfg->native_code = (uintptr_t)cfg->native_code_alloc + kNaClAlignment;
6615         cfg->native_code = (uintptr_t)cfg->native_code & ~kNaClAlignmentMask;
6616
6617         code = cfg->native_code;
6618
6619         alignment_check = (guint)cfg->native_code & kNaClAlignmentMask;
6620         g_assert (alignment_check == 0);
6621 #endif
6622
6623         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
6624                 trace = TRUE;
6625
6626         /* Amount of stack space allocated by register saving code */
6627         pos = 0;
6628
6629         /* Offset between RSP and the CFA */
6630         cfa_offset = 0;
6631
6632         /* 
6633          * The prolog consists of the following parts:
6634          * FP present:
6635          * - push rbp, mov rbp, rsp
6636          * - save callee saved regs using pushes
6637          * - allocate frame
6638          * - save rgctx if needed
6639          * - save lmf if needed
6640          * FP not present:
6641          * - allocate frame
6642          * - save rgctx if needed
6643          * - save lmf if needed
6644          * - save callee saved regs using moves
6645          */
6646
6647         // CFA = sp + 8
6648         cfa_offset = 8;
6649         mono_emit_unwind_op_def_cfa (cfg, code, AMD64_RSP, 8);
6650         // IP saved at CFA - 8
6651         mono_emit_unwind_op_offset (cfg, code, AMD64_RIP, -cfa_offset);
6652         async_exc_point (code);
6653         mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF);
6654
6655         if (!cfg->arch.omit_fp) {
6656                 amd64_push_reg (code, AMD64_RBP);
6657                 cfa_offset += 8;
6658                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6659                 mono_emit_unwind_op_offset (cfg, code, AMD64_RBP, - cfa_offset);
6660                 async_exc_point (code);
6661 #ifdef HOST_WIN32
6662                 mono_arch_unwindinfo_add_push_nonvol (&cfg->arch.unwindinfo, cfg->native_code, code, AMD64_RBP);
6663 #endif
6664                 /* These are handled automatically by the stack marking code */
6665                 mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset, SLOT_NOREF);
6666                 
6667                 amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof(mgreg_t));
6668                 mono_emit_unwind_op_def_cfa_reg (cfg, code, AMD64_RBP);
6669                 async_exc_point (code);
6670 #ifdef HOST_WIN32
6671                 mono_arch_unwindinfo_add_set_fpreg (&cfg->arch.unwindinfo, cfg->native_code, code, AMD64_RBP);
6672 #endif
6673         }
6674
6675         /* Save callee saved registers */
6676         if (!cfg->arch.omit_fp && !method->save_lmf) {
6677                 int offset = cfa_offset;
6678
6679                 for (i = 0; i < AMD64_NREG; ++i)
6680                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
6681                                 amd64_push_reg (code, i);
6682                                 pos += 8; /* AMD64 push inst is always 8 bytes, no way to change it */
6683                                 offset += 8;
6684                                 mono_emit_unwind_op_offset (cfg, code, i, - offset);
6685                                 async_exc_point (code);
6686
6687                                 /* These are handled automatically by the stack marking code */
6688                                 mini_gc_set_slot_type_from_cfa (cfg, - offset, SLOT_NOREF);
6689                         }
6690         }
6691
6692         /* The param area is always at offset 0 from sp */
6693         /* This needs to be allocated here, since it has to come after the spill area */
6694         if (cfg->arch.no_pushes && cfg->param_area) {
6695                 if (cfg->arch.omit_fp)
6696                         // FIXME:
6697                         g_assert_not_reached ();
6698                 cfg->stack_offset += ALIGN_TO (cfg->param_area, sizeof(mgreg_t));
6699         }
6700
6701         if (cfg->arch.omit_fp) {
6702                 /* 
6703                  * On enter, the stack is misaligned by the pushing of the return
6704                  * address. It is either made aligned by the pushing of %rbp, or by
6705                  * this.
6706                  */
6707                 alloc_size = ALIGN_TO (cfg->stack_offset, 8);
6708                 if ((alloc_size % 16) == 0) {
6709                         alloc_size += 8;
6710                         /* Mark the padding slot as NOREF */
6711                         mini_gc_set_slot_type_from_cfa (cfg, -cfa_offset - sizeof (mgreg_t), SLOT_NOREF);
6712                 }
6713         } else {
6714                 alloc_size = ALIGN_TO (cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT);
6715                 if (cfg->stack_offset != alloc_size) {
6716                         /* Mark the padding slot as NOREF */
6717                         mini_gc_set_slot_type_from_fp (cfg, -alloc_size + cfg->param_area, SLOT_NOREF);
6718                 }
6719                 cfg->arch.sp_fp_offset = alloc_size;
6720                 alloc_size -= pos;
6721         }
6722
6723         cfg->arch.stack_alloc_size = alloc_size;
6724
6725         /* Allocate stack frame */
6726         if (alloc_size) {
6727                 /* See mono_emit_stack_alloc */
6728 #if defined(HOST_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
6729                 guint32 remaining_size = alloc_size;
6730                 /*FIXME handle unbounded code expansion, we should use a loop in case of more than X interactions*/
6731                 guint32 required_code_size = ((remaining_size / 0x1000) + 1) * 10; /*10 is the max size of amd64_alu_reg_imm + amd64_test_membase_reg*/
6732                 guint32 offset = code - cfg->native_code;
6733                 if (G_UNLIKELY (required_code_size >= (cfg->code_size - offset))) {
6734                         while (required_code_size >= (cfg->code_size - offset))
6735                                 cfg->code_size *= 2;
6736                         cfg->native_code = mono_realloc_native_code (cfg);
6737                         code = cfg->native_code + offset;
6738                         cfg->stat_code_reallocs++;
6739                 }
6740
6741                 while (remaining_size >= 0x1000) {
6742                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
6743                         if (cfg->arch.omit_fp) {
6744                                 cfa_offset += 0x1000;
6745                                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6746                         }
6747                         async_exc_point (code);
6748 #ifdef HOST_WIN32
6749                         if (cfg->arch.omit_fp) 
6750                                 mono_arch_unwindinfo_add_alloc_stack (&cfg->arch.unwindinfo, cfg->native_code, code, 0x1000);
6751 #endif
6752
6753                         amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
6754                         remaining_size -= 0x1000;
6755                 }
6756                 if (remaining_size) {
6757                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, remaining_size);
6758                         if (cfg->arch.omit_fp) {
6759                                 cfa_offset += remaining_size;
6760                                 mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6761                                 async_exc_point (code);
6762                         }
6763 #ifdef HOST_WIN32
6764                         if (cfg->arch.omit_fp) 
6765                                 mono_arch_unwindinfo_add_alloc_stack (&cfg->arch.unwindinfo, cfg->native_code, code, remaining_size);
6766 #endif
6767                 }
6768 #else
6769                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, alloc_size);
6770                 if (cfg->arch.omit_fp) {
6771                         cfa_offset += alloc_size;
6772                         mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset);
6773                         async_exc_point (code);
6774                 }
6775 #endif
6776         }
6777
6778         /* Stack alignment check */
6779 #if 0
6780         {
6781                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_RSP, 8);
6782                 amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0xf);
6783                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
6784                 x86_branch8 (code, X86_CC_EQ, 2, FALSE);
6785                 amd64_breakpoint (code);
6786         }
6787 #endif
6788
6789 #ifndef TARGET_WIN32
6790         if (mini_get_debug_options ()->init_stacks) {
6791                 /* Fill the stack frame with a dummy value to force deterministic behavior */
6792         
6793                 /* Save registers to the red zone */
6794                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDI, 8);
6795                 amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
6796
6797                 amd64_mov_reg_imm (code, AMD64_RAX, 0x2a2a2a2a2a2a2a2a);
6798                 amd64_mov_reg_imm (code, AMD64_RCX, alloc_size / 8);
6799                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RSP, 8);
6800
6801                 amd64_cld (code);
6802 #if defined(__default_codegen__)
6803                 amd64_prefix (code, X86_REP_PREFIX);
6804                 amd64_stosl (code);
6805 #elif defined(__native_client_codegen__)
6806                 /* NaCl stos pseudo-instruction */
6807                 amd64_codegen_pre (code);
6808                 /* First, clear the upper 32 bits of RDI (mov %edi, %edi)  */
6809                 amd64_mov_reg_reg (code, AMD64_RDI, AMD64_RDI, 4);
6810                 /* Add %r15 to %rdi using lea, condition flags unaffected. */
6811                 amd64_lea_memindex_size (code, AMD64_RDI, AMD64_R15, 0, AMD64_RDI, 0, 8);
6812                 amd64_prefix (code, X86_REP_PREFIX);
6813                 amd64_stosl (code);
6814                 amd64_codegen_post (code);
6815 #endif /* __native_client_codegen__ */
6816
6817                 amd64_mov_reg_membase (code, AMD64_RDI, AMD64_RSP, -8, 8);
6818                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
6819         }
6820 #endif  
6821
6822         /* Save LMF */
6823         if (method->save_lmf) {
6824                 code = emit_setup_lmf (cfg, code, lmf_var->inst_offset, cfa_offset);
6825         }
6826
6827         /* Save callee saved registers */
6828         if (cfg->arch.omit_fp && !method->save_lmf) {
6829                 gint32 save_area_offset = cfg->arch.reg_save_area_offset;
6830
6831                 /* Save caller saved registers after sp is adjusted */
6832                 /* The registers are saved at the bottom of the frame */
6833                 /* FIXME: Optimize this so the regs are saved at the end of the frame in increasing order */
6834                 for (i = 0; i < AMD64_NREG; ++i)
6835                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
6836                                 amd64_mov_membase_reg (code, AMD64_RSP, save_area_offset, i, 8);
6837                                 mono_emit_unwind_op_offset (cfg, code, i, - (cfa_offset - save_area_offset));
6838
6839                                 /* These are handled automatically by the stack marking code */
6840                                 mini_gc_set_slot_type_from_cfa (cfg, - (cfa_offset - save_area_offset), SLOT_NOREF);
6841
6842                                 save_area_offset += 8;
6843                                 async_exc_point (code);
6844                         }
6845         }
6846
6847         /* store runtime generic context */
6848         if (cfg->rgctx_var) {
6849                 g_assert (cfg->rgctx_var->opcode == OP_REGOFFSET &&
6850                                 (cfg->rgctx_var->inst_basereg == AMD64_RBP || cfg->rgctx_var->inst_basereg == AMD64_RSP));
6851
6852                 amd64_mov_membase_reg (code, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, MONO_ARCH_RGCTX_REG, sizeof(gpointer));
6853
6854                 mono_add_var_location (cfg, cfg->rgctx_var, TRUE, MONO_ARCH_RGCTX_REG, 0, 0, code - cfg->native_code);
6855                 mono_add_var_location (cfg, cfg->rgctx_var, FALSE, cfg->rgctx_var->inst_basereg, cfg->rgctx_var->inst_offset, code - cfg->native_code, 0);
6856         }
6857
6858         /* compute max_length in order to use short forward jumps */
6859         max_epilog_size = get_max_epilog_size (cfg);
6860         if (cfg->opt & MONO_OPT_BRANCH) {
6861                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6862                         MonoInst *ins;
6863                         int max_length = 0;
6864
6865                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
6866                                 max_length += 6;
6867                         /* max alignment for loops */
6868                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
6869                                 max_length += LOOP_ALIGNMENT;
6870 #ifdef __native_client_codegen__
6871                         /* max alignment for native client */
6872                         max_length += kNaClAlignment;
6873 #endif
6874
6875                         MONO_BB_FOR_EACH_INS (bb, ins) {
6876 #ifdef __native_client_codegen__
6877                                 {
6878                                         int space_in_block = kNaClAlignment -
6879                                                 ((max_length + cfg->code_len) & kNaClAlignmentMask);
6880                                         int max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6881                                         if (space_in_block < max_len && max_len < kNaClAlignment) {
6882                                                 max_length += space_in_block;
6883                                         }
6884                                 }
6885 #endif  /*__native_client_codegen__*/
6886                                 max_length += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
6887                         }
6888
6889                         /* Take prolog and epilog instrumentation into account */
6890                         if (bb == cfg->bb_entry || bb == cfg->bb_exit)
6891                                 max_length += max_epilog_size;
6892                         
6893                         bb->max_length = max_length;
6894                 }
6895         }
6896
6897         sig = mono_method_signature (method);
6898         pos = 0;
6899
6900         cinfo = cfg->arch.cinfo;
6901
6902         if (sig->ret->type != MONO_TYPE_VOID) {
6903                 /* Save volatile arguments to the stack */
6904                 if (cfg->vret_addr && (cfg->vret_addr->opcode != OP_REGVAR))
6905                         amd64_mov_membase_reg (code, cfg->vret_addr->inst_basereg, cfg->vret_addr->inst_offset, cinfo->ret.reg, 8);
6906         }
6907
6908         /* Keep this in sync with emit_load_volatile_arguments */
6909         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6910                 ArgInfo *ainfo = cinfo->args + i;
6911                 gint32 stack_offset;
6912                 MonoType *arg_type;
6913
6914                 ins = cfg->args [i];
6915
6916                 if ((ins->flags & MONO_INST_IS_DEAD) && !trace)
6917                         /* Unused arguments */
6918                         continue;
6919
6920                 if (sig->hasthis && (i == 0))
6921                         arg_type = &mono_defaults.object_class->byval_arg;
6922                 else
6923                         arg_type = sig->params [i - sig->hasthis];
6924
6925                 stack_offset = ainfo->offset + ARGS_OFFSET;
6926
6927                 if (cfg->globalra) {
6928                         /* All the other moves are done by the register allocator */
6929                         switch (ainfo->storage) {
6930                         case ArgInFloatSSEReg:
6931                                 amd64_sse_cvtss2sd_reg_reg (code, ainfo->reg, ainfo->reg);
6932                                 break;
6933                         case ArgValuetypeInReg:
6934                                 for (quad = 0; quad < 2; quad ++) {
6935                                         switch (ainfo->pair_storage [quad]) {
6936                                         case ArgInIReg:
6937                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
6938                                                 break;
6939                                         case ArgInFloatSSEReg:
6940                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6941                                                 break;
6942                                         case ArgInDoubleSSEReg:
6943                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
6944                                                 break;
6945                                         case ArgNone:
6946                                                 break;
6947                                         default:
6948                                                 g_assert_not_reached ();
6949                                         }
6950                                 }
6951                                 break;
6952                         default:
6953                                 break;
6954                         }
6955
6956                         continue;
6957                 }
6958
6959                 /* Save volatile arguments to the stack */
6960                 if (ins->opcode != OP_REGVAR) {
6961                         switch (ainfo->storage) {
6962                         case ArgInIReg: {
6963                                 guint32 size = 8;
6964
6965                                 /* FIXME: I1 etc */
6966                                 /*
6967                                 if (stack_offset & 0x1)
6968                                         size = 1;
6969                                 else if (stack_offset & 0x2)
6970                                         size = 2;
6971                                 else if (stack_offset & 0x4)
6972                                         size = 4;
6973                                 else
6974                                         size = 8;
6975                                 */
6976                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg, size);
6977
6978                                 /*
6979                                  * Save the original location of 'this',
6980                                  * get_generic_info_from_stack_frame () needs this to properly look up
6981                                  * the argument value during the handling of async exceptions.
6982                                  */
6983                                 if (ins == cfg->args [0]) {
6984                                         mono_add_var_location (cfg, ins, TRUE, ainfo->reg, 0, 0, code - cfg->native_code);
6985                                         mono_add_var_location (cfg, ins, FALSE, ins->inst_basereg, ins->inst_offset, code - cfg->native_code, 0);
6986                                 }
6987                                 break;
6988                         }
6989                         case ArgInFloatSSEReg:
6990                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6991                                 break;
6992                         case ArgInDoubleSSEReg:
6993                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
6994                                 break;
6995                         case ArgValuetypeInReg:
6996                                 for (quad = 0; quad < 2; quad ++) {
6997                                         switch (ainfo->pair_storage [quad]) {
6998                                         case ArgInIReg:
6999                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad], sizeof(mgreg_t));
7000                                                 break;
7001                                         case ArgInFloatSSEReg:
7002                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
7003                                                 break;
7004                                         case ArgInDoubleSSEReg:
7005                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof(mgreg_t)), ainfo->pair_regs [quad]);
7006                                                 break;
7007                                         case ArgNone:
7008                                                 break;
7009                                         default:
7010                                                 g_assert_not_reached ();
7011                                         }
7012                                 }
7013                                 break;
7014                         case ArgValuetypeAddrInIReg:
7015                                 if (ainfo->pair_storage [0] == ArgInIReg)
7016                                         amd64_mov_membase_reg (code, ins->inst_left->inst_basereg, ins->inst_left->inst_offset, ainfo->pair_regs [0],  sizeof (gpointer));
7017                                 break;
7018                         default:
7019                                 break;
7020                         }
7021                 } else {
7022                         /* Argument allocated to (non-volatile) register */
7023                         switch (ainfo->storage) {
7024                         case ArgInIReg:
7025                                 amd64_mov_reg_reg (code, ins->dreg, ainfo->reg, 8);
7026                                 break;
7027                         case ArgOnStack:
7028                                 amd64_mov_reg_membase (code, ins->dreg, AMD64_RBP, ARGS_OFFSET + ainfo->offset, 8);
7029                                 break;
7030                         default:
7031                                 g_assert_not_reached ();
7032                         }
7033
7034                         if (ins == cfg->args [0]) {
7035                                 mono_add_var_location (cfg, ins, TRUE, ainfo->reg, 0, 0, code - cfg->native_code);
7036                                 mono_add_var_location (cfg, ins, TRUE, ins->dreg, 0, code - cfg->native_code, 0);
7037                         }
7038                 }
7039         }
7040
7041         if (method->save_lmf) {
7042                 code = emit_save_lmf (cfg, code, lmf_var->inst_offset, &args_clobbered);
7043         }
7044
7045         if (trace) {
7046                 args_clobbered = TRUE;
7047                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
7048         }
7049
7050         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7051                 args_clobbered = TRUE;
7052
7053         /*
7054          * Optimize the common case of the first bblock making a call with the same
7055          * arguments as the method. This works because the arguments are still in their
7056          * original argument registers.
7057          * FIXME: Generalize this
7058          */
7059         if (!args_clobbered) {
7060                 MonoBasicBlock *first_bb = cfg->bb_entry;
7061                 MonoInst *next;
7062
7063                 next = mono_bb_first_ins (first_bb);
7064                 if (!next && first_bb->next_bb) {
7065                         first_bb = first_bb->next_bb;
7066                         next = mono_bb_first_ins (first_bb);
7067                 }
7068
7069                 if (first_bb->in_count > 1)
7070                         next = NULL;
7071
7072                 for (i = 0; next && i < sig->param_count + sig->hasthis; ++i) {
7073                         ArgInfo *ainfo = cinfo->args + i;
7074                         gboolean match = FALSE;
7075                         
7076                         ins = cfg->args [i];
7077                         if (ins->opcode != OP_REGVAR) {
7078                                 switch (ainfo->storage) {
7079                                 case ArgInIReg: {
7080                                         if (((next->opcode == OP_LOAD_MEMBASE) || (next->opcode == OP_LOADI4_MEMBASE)) && next->inst_basereg == ins->inst_basereg && next->inst_offset == ins->inst_offset) {
7081                                                 if (next->dreg == ainfo->reg) {
7082                                                         NULLIFY_INS (next);
7083                                                         match = TRUE;
7084                                                 } else {
7085                                                         next->opcode = OP_MOVE;
7086                                                         next->sreg1 = ainfo->reg;
7087                                                         /* Only continue if the instruction doesn't change argument regs */
7088                                                         if (next->dreg == ainfo->reg || next->dreg == AMD64_RAX)
7089                                                                 match = TRUE;
7090                                                 }
7091                                         }
7092                                         break;
7093                                 }
7094                                 default:
7095                                         break;
7096                                 }
7097                         } else {
7098                                 /* Argument allocated to (non-volatile) register */
7099                                 switch (ainfo->storage) {
7100                                 case ArgInIReg:
7101                                         if (next->opcode == OP_MOVE && next->sreg1 == ins->dreg && next->dreg == ainfo->reg) {
7102                                                 NULLIFY_INS (next);
7103                                                 match = TRUE;
7104                                         }
7105                                         break;
7106                                 default:
7107                                         break;
7108                                 }
7109                         }
7110
7111                         if (match) {
7112                                 next = next->next;
7113                                 //next = mono_inst_list_next (&next->node, &first_bb->ins_list);
7114                                 if (!next)
7115                                         break;
7116                         }
7117                 }
7118         }
7119
7120         if (cfg->gen_seq_points) {
7121                 MonoInst *info_var = cfg->arch.seq_point_info_var;
7122
7123                 /* Initialize seq_point_info_var */
7124                 if (cfg->compile_aot) {
7125                         /* Initialize the variable from a GOT slot */
7126                         /* Same as OP_AOTCONST */
7127                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_SEQ_POINT_INFO, cfg->method);
7128                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, sizeof(gpointer));
7129                         g_assert (info_var->opcode == OP_REGOFFSET);
7130                         amd64_mov_membase_reg (code, info_var->inst_basereg, info_var->inst_offset, AMD64_R11, 8);
7131                 }
7132
7133                 /* Initialize ss_trigger_page_var */
7134                 ins = cfg->arch.ss_trigger_page_var;
7135
7136                 g_assert (ins->opcode == OP_REGOFFSET);
7137
7138                 if (cfg->compile_aot) {
7139                         amd64_mov_reg_membase (code, AMD64_R11, info_var->inst_basereg, info_var->inst_offset, 8);
7140                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, G_STRUCT_OFFSET (SeqPointInfo, ss_trigger_page), 8);
7141                 } else {
7142                         amd64_mov_reg_imm (code, AMD64_R11, (guint64)ss_trigger_page);
7143                 }
7144                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, AMD64_R11, 8);
7145         }
7146
7147         cfg->code_len = code - cfg->native_code;
7148
7149         g_assert (cfg->code_len < cfg->code_size);
7150
7151         return code;
7152 }
7153
7154 void
7155 mono_arch_emit_epilog (MonoCompile *cfg)
7156 {
7157         MonoMethod *method = cfg->method;
7158         int quad, pos, i;
7159         guint8 *code;
7160         int max_epilog_size;
7161         CallInfo *cinfo;
7162         gint32 lmf_offset = cfg->arch.lmf_var ? ((MonoInst*)cfg->arch.lmf_var)->inst_offset : -1;
7163         
7164         max_epilog_size = get_max_epilog_size (cfg);
7165
7166         while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
7167                 cfg->code_size *= 2;
7168                 cfg->native_code = mono_realloc_native_code (cfg);
7169                 cfg->stat_code_reallocs++;
7170         }
7171
7172         code = cfg->native_code + cfg->code_len;
7173
7174         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
7175                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
7176
7177         /* the code restoring the registers must be kept in sync with OP_TAILCALL */
7178         pos = 0;
7179         
7180         if (method->save_lmf) {
7181                 /* check if we need to restore protection of the stack after a stack overflow */
7182                 if (mono_get_jit_tls_offset () != -1) {
7183                         guint8 *patch;
7184                         code = mono_amd64_emit_tls_get (code, AMD64_RCX, mono_get_jit_tls_offset ());
7185                         /* we load the value in a separate instruction: this mechanism may be
7186                          * used later as a safer way to do thread interruption
7187                          */
7188                         amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RCX, G_STRUCT_OFFSET (MonoJitTlsData, restore_stack_prot), 8);
7189                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 0);
7190                         patch = code;
7191                         x86_branch8 (code, X86_CC_Z, 0, FALSE);
7192                         /* note that the call trampoline will preserve eax/edx */
7193                         x86_call_reg (code, X86_ECX);
7194                         x86_patch (patch, code);
7195                 } else {
7196                         /* FIXME: maybe save the jit tls in the prolog */
7197                 }
7198
7199                 code = emit_restore_lmf (cfg, code, lmf_offset);
7200
7201                 /* Restore caller saved regs */
7202                 if (cfg->used_int_regs & (1 << AMD64_RBP)) {
7203                         amd64_mov_reg_membase (code, AMD64_RBP, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), 8);
7204                 }
7205                 if (cfg->used_int_regs & (1 << AMD64_RBX)) {
7206                         amd64_mov_reg_membase (code, AMD64_RBX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), 8);
7207                 }
7208                 if (cfg->used_int_regs & (1 << AMD64_R12)) {
7209                         amd64_mov_reg_membase (code, AMD64_R12, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), 8);
7210                 }
7211                 if (cfg->used_int_regs & (1 << AMD64_R13)) {
7212                         amd64_mov_reg_membase (code, AMD64_R13, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), 8);
7213                 }
7214                 if (cfg->used_int_regs & (1 << AMD64_R14)) {
7215                         amd64_mov_reg_membase (code, AMD64_R14, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), 8);
7216                 }
7217                 if (cfg->used_int_regs & (1 << AMD64_R15)) {
7218 #if defined(__default_codegen__)
7219                         amd64_mov_reg_membase (code, AMD64_R15, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), 8);
7220 #elif defined(__native_client_codegen__)
7221                         g_assert_not_reached();
7222 #endif
7223                 }
7224 #ifdef HOST_WIN32
7225                 if (cfg->used_int_regs & (1 << AMD64_RDI)) {
7226                         amd64_mov_reg_membase (code, AMD64_RDI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rdi), 8);
7227                 }
7228                 if (cfg->used_int_regs & (1 << AMD64_RSI)) {
7229                         amd64_mov_reg_membase (code, AMD64_RSI, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsi), 8);
7230                 }
7231 #endif
7232         } else {
7233
7234                 if (cfg->arch.omit_fp) {
7235                         gint32 save_area_offset = cfg->arch.reg_save_area_offset;
7236
7237                         for (i = 0; i < AMD64_NREG; ++i)
7238                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7239                                         amd64_mov_reg_membase (code, i, AMD64_RSP, save_area_offset, 8);
7240                                         save_area_offset += 8;
7241                                 }
7242                 }
7243                 else {
7244                         for (i = 0; i < AMD64_NREG; ++i)
7245                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
7246                                         pos -= sizeof(mgreg_t);
7247
7248                         if (pos) {
7249                                 if (pos == - sizeof(mgreg_t)) {
7250                                         /* Only one register, so avoid lea */
7251                                         for (i = AMD64_NREG - 1; i > 0; --i)
7252                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7253                                                         amd64_mov_reg_membase (code, i, AMD64_RBP, pos, 8);
7254                                                 }
7255                                 }
7256                                 else {
7257                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
7258
7259                                         /* Pop registers in reverse order */
7260                                         for (i = AMD64_NREG - 1; i > 0; --i)
7261                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
7262                                                         amd64_pop_reg (code, i);
7263                                                 }
7264                                 }
7265                         }
7266                 }
7267         }
7268
7269         /* Load returned vtypes into registers if needed */
7270         cinfo = cfg->arch.cinfo;
7271         if (cinfo->ret.storage == ArgValuetypeInReg) {
7272                 ArgInfo *ainfo = &cinfo->ret;
7273                 MonoInst *inst = cfg->ret;
7274
7275                 for (quad = 0; quad < 2; quad ++) {
7276                         switch (ainfo->pair_storage [quad]) {
7277                         case ArgInIReg:
7278                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)), sizeof(mgreg_t));
7279                                 break;
7280                         case ArgInFloatSSEReg:
7281                                 amd64_movss_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7282                                 break;
7283                         case ArgInDoubleSSEReg:
7284                                 amd64_movsd_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof(mgreg_t)));
7285                                 break;
7286                         case ArgNone:
7287                                 break;
7288                         default:
7289                                 g_assert_not_reached ();
7290                         }
7291                 }
7292         }
7293
7294         if (cfg->arch.omit_fp) {
7295                 if (cfg->arch.stack_alloc_size)
7296                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
7297         } else {
7298                 amd64_leave (code);
7299         }
7300         async_exc_point (code);
7301         amd64_ret (code);
7302
7303         cfg->code_len = code - cfg->native_code;
7304
7305         g_assert (cfg->code_len < cfg->code_size);
7306 }
7307
7308 void
7309 mono_arch_emit_exceptions (MonoCompile *cfg)
7310 {
7311         MonoJumpInfo *patch_info;
7312         int nthrows, i;
7313         guint8 *code;
7314         MonoClass *exc_classes [16];
7315         guint8 *exc_throw_start [16], *exc_throw_end [16];
7316         guint32 code_size = 0;
7317
7318         /* Compute needed space */
7319         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7320                 if (patch_info->type == MONO_PATCH_INFO_EXC)
7321                         code_size += 40;
7322                 if (patch_info->type == MONO_PATCH_INFO_R8)
7323                         code_size += 8 + 15; /* sizeof (double) + alignment */
7324                 if (patch_info->type == MONO_PATCH_INFO_R4)
7325                         code_size += 4 + 15; /* sizeof (float) + alignment */
7326                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR)
7327                         code_size += 8 + 7; /*sizeof (void*) + alignment */
7328         }
7329
7330 #ifdef __native_client_codegen__
7331         /* Give us extra room on Native Client.  This could be   */
7332         /* more carefully calculated, but bundle alignment makes */
7333         /* it much trickier, so *2 like other places is good.    */
7334         code_size *= 2;
7335 #endif
7336
7337         while (cfg->code_len + code_size > (cfg->code_size - 16)) {
7338                 cfg->code_size *= 2;
7339                 cfg->native_code = mono_realloc_native_code (cfg);
7340                 cfg->stat_code_reallocs++;
7341         }
7342
7343         code = cfg->native_code + cfg->code_len;
7344
7345         /* add code to raise exceptions */
7346         nthrows = 0;
7347         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7348                 switch (patch_info->type) {
7349                 case MONO_PATCH_INFO_EXC: {
7350                         MonoClass *exc_class;
7351                         guint8 *buf, *buf2;
7352                         guint32 throw_ip;
7353
7354                         amd64_patch (patch_info->ip.i + cfg->native_code, code);
7355
7356                         exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name);
7357                         g_assert (exc_class);
7358                         throw_ip = patch_info->ip.i;
7359
7360                         //x86_breakpoint (code);
7361                         /* Find a throw sequence for the same exception class */
7362                         for (i = 0; i < nthrows; ++i)
7363                                 if (exc_classes [i] == exc_class)
7364                                         break;
7365                         if (i < nthrows) {
7366                                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, (exc_throw_end [i] - cfg->native_code) - throw_ip);
7367                                 x86_jump_code (code, exc_throw_start [i]);
7368                                 patch_info->type = MONO_PATCH_INFO_NONE;
7369                         }
7370                         else {
7371                                 buf = code;
7372                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG2, 0xf0f0f0f0, 4);
7373                                 buf2 = code;
7374
7375                                 if (nthrows < 16) {
7376                                         exc_classes [nthrows] = exc_class;
7377                                         exc_throw_start [nthrows] = code;
7378                                 }
7379                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, exc_class->type_token - MONO_TOKEN_TYPE_DEF);
7380
7381                                 patch_info->type = MONO_PATCH_INFO_NONE;
7382
7383                                 code = emit_call_body (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, "mono_arch_throw_corlib_exception");
7384
7385                                 amd64_mov_reg_imm (buf, AMD64_ARG_REG2, (code - cfg->native_code) - throw_ip);
7386                                 while (buf < buf2)
7387                                         x86_nop (buf);
7388
7389                                 if (nthrows < 16) {
7390                                         exc_throw_end [nthrows] = code;
7391                                         nthrows ++;
7392                                 }
7393                         }
7394                         break;
7395                 }
7396                 default:
7397                         /* do nothing */
7398                         break;
7399                 }
7400                 g_assert(code < cfg->native_code + cfg->code_size);
7401         }
7402
7403         /* Handle relocations with RIP relative addressing */
7404         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7405                 gboolean remove = FALSE;
7406                 guint8 *orig_code = code;
7407
7408                 switch (patch_info->type) {
7409                 case MONO_PATCH_INFO_R8:
7410                 case MONO_PATCH_INFO_R4: {
7411                         guint8 *pos, *patch_pos;
7412                         guint32 target_pos;
7413
7414                         /* The SSE opcodes require a 16 byte alignment */
7415 #if defined(__default_codegen__)
7416                         code = (guint8*)ALIGN_TO (code, 16);
7417 #elif defined(__native_client_codegen__)
7418                         {
7419                                 /* Pad this out with HLT instructions  */
7420                                 /* or we can get garbage bytes emitted */
7421                                 /* which will fail validation          */
7422                                 guint8 *aligned_code;
7423                                 /* extra align to make room for  */
7424                                 /* mov/push below                      */
7425                                 int extra_align = patch_info->type == MONO_PATCH_INFO_R8 ? 2 : 1;
7426                                 aligned_code = (guint8*)ALIGN_TO (code + extra_align, 16);
7427                                 /* The technique of hiding data in an  */
7428                                 /* instruction has a problem here: we  */
7429                                 /* need the data aligned to a 16-byte  */
7430                                 /* boundary but the instruction cannot */
7431                                 /* cross the bundle boundary. so only  */
7432                                 /* odd multiples of 16 can be used     */
7433                                 if ((intptr_t)aligned_code % kNaClAlignment == 0) {
7434                                         aligned_code += 16;
7435                                 }
7436                                 while (code < aligned_code) {
7437                                         *(code++) = 0xf4; /* hlt */
7438                                 }
7439                         }       
7440 #endif
7441
7442                         pos = cfg->native_code + patch_info->ip.i;
7443                         if (IS_REX (pos [1])) {
7444                                 patch_pos = pos + 5;
7445                                 target_pos = code - pos - 9;
7446                         }
7447                         else {
7448                                 patch_pos = pos + 4;
7449                                 target_pos = code - pos - 8;
7450                         }
7451
7452                         if (patch_info->type == MONO_PATCH_INFO_R8) {
7453 #ifdef __native_client_codegen__
7454                                 /* Hide 64-bit data in a         */
7455                                 /* "mov imm64, r11" instruction. */
7456                                 /* write it before the start of  */
7457                                 /* the data*/
7458                                 *(code-2) = 0x49; /* prefix      */
7459                                 *(code-1) = 0xbb; /* mov X, %r11 */
7460 #endif
7461                                 *(double*)code = *(double*)patch_info->data.target;
7462                                 code += sizeof (double);
7463                         } else {
7464 #ifdef __native_client_codegen__
7465                                 /* Hide 32-bit data in a        */
7466                                 /* "push imm32" instruction.    */
7467                                 *(code-1) = 0x68; /* push */
7468 #endif
7469                                 *(float*)code = *(float*)patch_info->data.target;
7470                                 code += sizeof (float);
7471                         }
7472
7473                         *(guint32*)(patch_pos) = target_pos;
7474
7475                         remove = TRUE;
7476                         break;
7477                 }
7478                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
7479                         guint8 *pos;
7480
7481                         if (cfg->compile_aot)
7482                                 continue;
7483
7484                         /*loading is faster against aligned addresses.*/
7485                         code = (guint8*)ALIGN_TO (code, 8);
7486                         memset (orig_code, 0, code - orig_code);
7487
7488                         pos = cfg->native_code + patch_info->ip.i;
7489
7490                         /*alu_op [rex] modr/m imm32 - 7 or 8 bytes */
7491                         if (IS_REX (pos [1]))
7492                                 *(guint32*)(pos + 4) = (guint8*)code - pos - 8;
7493                         else
7494                                 *(guint32*)(pos + 3) = (guint8*)code - pos - 7;
7495
7496                         *(gpointer*)code = (gpointer)patch_info->data.target;
7497                         code += sizeof (gpointer);
7498
7499                         remove = TRUE;
7500                         break;
7501                 }
7502                 default:
7503                         break;
7504                 }
7505
7506                 if (remove) {
7507                         if (patch_info == cfg->patch_info)
7508                                 cfg->patch_info = patch_info->next;
7509                         else {
7510                                 MonoJumpInfo *tmp;
7511
7512                                 for (tmp = cfg->patch_info; tmp->next != patch_info; tmp = tmp->next)
7513                                         ;
7514                                 tmp->next = patch_info->next;
7515                         }
7516                 }
7517                 g_assert (code < cfg->native_code + cfg->code_size);
7518         }
7519
7520         cfg->code_len = code - cfg->native_code;
7521
7522         g_assert (cfg->code_len < cfg->code_size);
7523
7524 }
7525
7526 #endif /* DISABLE_JIT */
7527
7528 void*
7529 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
7530 {
7531         guchar *code = p;
7532         CallInfo *cinfo = NULL;
7533         MonoMethodSignature *sig;
7534         MonoInst *inst;
7535         int i, n, stack_area = 0;
7536
7537         /* Keep this in sync with mono_arch_get_argument_info */
7538
7539         if (enable_arguments) {
7540                 /* Allocate a new area on the stack and save arguments there */
7541                 sig = mono_method_signature (cfg->method);
7542
7543                 cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig);
7544
7545                 n = sig->param_count + sig->hasthis;
7546
7547                 stack_area = ALIGN_TO (n * 8, 16);
7548
7549                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_area);
7550
7551                 for (i = 0; i < n; ++i) {
7552                         inst = cfg->args [i];
7553
7554                         if (inst->opcode == OP_REGVAR)
7555                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), inst->dreg, 8);
7556                         else {
7557                                 amd64_mov_reg_membase (code, AMD64_R11, inst->inst_basereg, inst->inst_offset, 8);
7558                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), AMD64_R11, 8);
7559                         }
7560                 }
7561         }
7562
7563         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
7564         amd64_set_reg_template (code, AMD64_ARG_REG1);
7565         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RSP, 8);
7566         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7567
7568         if (enable_arguments)
7569                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, stack_area);
7570
7571         return code;
7572 }
7573
7574 enum {
7575         SAVE_NONE,
7576         SAVE_STRUCT,
7577         SAVE_EAX,
7578         SAVE_EAX_EDX,
7579         SAVE_XMM
7580 };
7581
7582 void*
7583 mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers)
7584 {
7585         guchar *code = p;
7586         int save_mode = SAVE_NONE;
7587         MonoMethod *method = cfg->method;
7588         MonoType *ret_type = mini_type_get_underlying_type (NULL, mono_method_signature (method)->ret);
7589         int i;
7590         
7591         switch (ret_type->type) {
7592         case MONO_TYPE_VOID:
7593                 /* special case string .ctor icall */
7594                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
7595                         save_mode = SAVE_EAX;
7596                 else
7597                         save_mode = SAVE_NONE;
7598                 break;
7599         case MONO_TYPE_I8:
7600         case MONO_TYPE_U8:
7601                 save_mode = SAVE_EAX;
7602                 break;
7603         case MONO_TYPE_R4:
7604         case MONO_TYPE_R8:
7605                 save_mode = SAVE_XMM;
7606                 break;
7607         case MONO_TYPE_GENERICINST:
7608                 if (!mono_type_generic_inst_is_valuetype (ret_type)) {
7609                         save_mode = SAVE_EAX;
7610                         break;
7611                 }
7612                 /* Fall through */
7613         case MONO_TYPE_VALUETYPE:
7614                 save_mode = SAVE_STRUCT;
7615                 break;
7616         default:
7617                 save_mode = SAVE_EAX;
7618                 break;
7619         }
7620
7621         /* Save the result and copy it into the proper argument register */
7622         switch (save_mode) {
7623         case SAVE_EAX:
7624                 amd64_push_reg (code, AMD64_RAX);
7625                 /* Align stack */
7626                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7627                 if (enable_arguments)
7628                         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RAX, 8);
7629                 break;
7630         case SAVE_STRUCT:
7631                 /* FIXME: */
7632                 if (enable_arguments)
7633                         amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
7634                 break;
7635         case SAVE_XMM:
7636                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7637                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
7638                 /* Align stack */
7639                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
7640                 /* 
7641                  * The result is already in the proper argument register so no copying
7642                  * needed.
7643                  */
7644                 break;
7645         case SAVE_NONE:
7646                 break;
7647         default:
7648                 g_assert_not_reached ();
7649         }
7650
7651         /* Set %al since this is a varargs call */
7652         if (save_mode == SAVE_XMM)
7653                 amd64_mov_reg_imm (code, AMD64_RAX, 1);
7654         else
7655                 amd64_mov_reg_imm (code, AMD64_RAX, 0);
7656
7657         if (preserve_argument_registers) {
7658                 for (i = 0; i < PARAM_REGS; ++i)
7659                         amd64_push_reg (code, param_regs [i]);
7660         }
7661
7662         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
7663         amd64_set_reg_template (code, AMD64_ARG_REG1);
7664         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func, TRUE);
7665
7666         if (preserve_argument_registers) {
7667                 for (i = PARAM_REGS - 1; i >= 0; --i)
7668                         amd64_pop_reg (code, param_regs [i]);
7669         }
7670
7671         /* Restore result */
7672         switch (save_mode) {
7673         case SAVE_EAX:
7674                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7675                 amd64_pop_reg (code, AMD64_RAX);
7676                 break;
7677         case SAVE_STRUCT:
7678                 /* FIXME: */
7679                 break;
7680         case SAVE_XMM:
7681                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7682                 amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
7683                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
7684                 break;
7685         case SAVE_NONE:
7686                 break;
7687         default:
7688                 g_assert_not_reached ();
7689         }
7690
7691         return code;
7692 }
7693
7694 void
7695 mono_arch_flush_icache (guint8 *code, gint size)
7696 {
7697         /* Not needed */
7698 }
7699
7700 void
7701 mono_arch_flush_register_windows (void)
7702 {
7703 }
7704
7705 gboolean 
7706 mono_arch_is_inst_imm (gint64 imm)
7707 {
7708         return amd64_is_imm32 (imm);
7709 }
7710
7711 /*
7712  * Determine whenever the trap whose info is in SIGINFO is caused by
7713  * integer overflow.
7714  */
7715 gboolean
7716 mono_arch_is_int_overflow (void *sigctx, void *info)
7717 {
7718         MonoContext ctx;
7719         guint8* rip;
7720         int reg;
7721         gint64 value;
7722
7723         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
7724
7725         rip = (guint8*)ctx.rip;
7726
7727         if (IS_REX (rip [0])) {
7728                 reg = amd64_rex_b (rip [0]);
7729                 rip ++;
7730         }
7731         else
7732                 reg = 0;
7733
7734         if ((rip [0] == 0xf7) && (x86_modrm_mod (rip [1]) == 0x3) && (x86_modrm_reg (rip [1]) == 0x7)) {
7735                 /* idiv REG */
7736                 reg += x86_modrm_rm (rip [1]);
7737
7738                 switch (reg) {
7739                 case AMD64_RAX:
7740                         value = ctx.rax;
7741                         break;
7742                 case AMD64_RBX:
7743                         value = ctx.rbx;
7744                         break;
7745                 case AMD64_RCX:
7746                         value = ctx.rcx;
7747                         break;
7748                 case AMD64_RDX:
7749                         value = ctx.rdx;
7750                         break;
7751                 case AMD64_RBP:
7752                         value = ctx.rbp;
7753                         break;
7754                 case AMD64_RSP:
7755                         value = ctx.rsp;
7756                         break;
7757                 case AMD64_RSI:
7758                         value = ctx.rsi;
7759                         break;
7760                 case AMD64_RDI:
7761                         value = ctx.rdi;
7762                         break;
7763                 case AMD64_R12:
7764                         value = ctx.r12;
7765                         break;
7766                 case AMD64_R13:
7767                         value = ctx.r13;
7768                         break;
7769                 case AMD64_R14:
7770                         value = ctx.r14;
7771                         break;
7772                 case AMD64_R15:
7773                         value = ctx.r15;
7774                         break;
7775                 default:
7776                         g_assert_not_reached ();
7777                         reg = -1;
7778                 }                       
7779
7780                 if (value == -1)
7781                         return TRUE;
7782         }
7783
7784         return FALSE;
7785 }
7786
7787 guint32
7788 mono_arch_get_patch_offset (guint8 *code)
7789 {
7790         return 3;
7791 }
7792
7793 /**
7794  * mono_breakpoint_clean_code:
7795  *
7796  * Copy @size bytes from @code - @offset to the buffer @buf. If the debugger inserted software
7797  * breakpoints in the original code, they are removed in the copy.
7798  *
7799  * Returns TRUE if no sw breakpoint was present.
7800  */
7801 gboolean
7802 mono_breakpoint_clean_code (guint8 *method_start, guint8 *code, int offset, guint8 *buf, int size)
7803 {
7804         int i;
7805         gboolean can_write = TRUE;
7806         /*
7807          * If method_start is non-NULL we need to perform bound checks, since we access memory
7808          * at code - offset we could go before the start of the method and end up in a different
7809          * page of memory that is not mapped or read incorrect data anyway. We zero-fill the bytes
7810          * instead.
7811          */
7812         if (!method_start || code - offset >= method_start) {
7813                 memcpy (buf, code - offset, size);
7814         } else {
7815                 int diff = code - method_start;
7816                 memset (buf, 0, size);
7817                 memcpy (buf + offset - diff, method_start, diff + size - offset);
7818         }
7819         code -= offset;
7820         for (i = 0; i < MONO_BREAKPOINT_ARRAY_SIZE; ++i) {
7821                 int idx = mono_breakpoint_info_index [i];
7822                 guint8 *ptr;
7823                 if (idx < 1)
7824                         continue;
7825                 ptr = mono_breakpoint_info [idx].address;
7826                 if (ptr >= code && ptr < code + size) {
7827                         guint8 saved_byte = mono_breakpoint_info [idx].saved_byte;
7828                         can_write = FALSE;
7829                         /*g_print ("patching %p with 0x%02x (was: 0x%02x)\n", ptr, saved_byte, buf [ptr - code]);*/
7830                         buf [ptr - code] = saved_byte;
7831                 }
7832         }
7833         return can_write;
7834 }
7835
7836 #if defined(__native_client_codegen__)
7837 /* For membase calls, we want the base register. for Native Client,  */
7838 /* all indirect calls have the following sequence with the given sizes: */
7839 /* mov %eXX,%eXX                                [2-3]   */
7840 /* mov disp(%r15,%rXX,scale),%r11d              [4-8]   */
7841 /* and $0xffffffffffffffe0,%r11d                [4]     */
7842 /* add %r15,%r11                                [3]     */
7843 /* callq *%r11                                  [3]     */
7844
7845
7846 /* Determine if code points to a NaCl call-through-register sequence, */
7847 /* (i.e., the last 3 instructions listed above) */
7848 int
7849 is_nacl_call_reg_sequence(guint8* code)
7850 {
7851         const char *sequence = "\x41\x83\xe3\xe0" /* and */
7852                                "\x4d\x03\xdf"     /* add */
7853                                "\x41\xff\xd3";   /* call */
7854         return memcmp(code, sequence, 10) == 0;
7855 }
7856
7857 /* Determine if code points to the first opcode of the mov membase component */
7858 /* of an indirect call sequence (i.e. the first 2 instructions listed above) */
7859 /* (there could be a REX prefix before the opcode but it is ignored) */
7860 static int
7861 is_nacl_indirect_call_membase_sequence(guint8* code)
7862 {
7863                /* Check for mov opcode, reg-reg addressing mode (mod = 3), */
7864         return code[0] == 0x8b && amd64_modrm_mod(code[1]) == 3 &&
7865                /* and that src reg = dest reg */
7866                amd64_modrm_reg(code[1]) == amd64_modrm_rm(code[1]) &&
7867                /* Check that next inst is mov, uses SIB byte (rm = 4), */
7868                IS_REX(code[2]) &&
7869                code[3] == 0x8b && amd64_modrm_rm(code[4]) == 4 &&
7870                /* and has dst of r11 and base of r15 */
7871                (amd64_modrm_reg(code[4]) + amd64_rex_r(code[2])) == AMD64_R11 &&
7872                (amd64_sib_base(code[5]) + amd64_rex_b(code[2])) == AMD64_R15;
7873 }
7874 #endif /* __native_client_codegen__ */
7875
7876 int
7877 mono_arch_get_this_arg_reg (guint8 *code)
7878 {
7879         return AMD64_ARG_REG1;
7880 }
7881
7882 gpointer
7883 mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code)
7884 {
7885         return (gpointer)regs [mono_arch_get_this_arg_reg (code)];
7886 }
7887
7888 #define MAX_ARCH_DELEGATE_PARAMS 10
7889
7890 static gpointer
7891 get_delegate_invoke_impl (gboolean has_target, guint32 param_count, guint32 *code_len)
7892 {
7893         guint8 *code, *start;
7894         int i;
7895
7896         if (has_target) {
7897                 start = code = mono_global_codeman_reserve (64);
7898
7899                 /* Replace the this argument with the target */
7900                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7901                 amd64_mov_reg_membase (code, AMD64_ARG_REG1, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, target), 8);
7902                 amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7903
7904                 g_assert ((code - start) < 64);
7905         } else {
7906                 start = code = mono_global_codeman_reserve (64);
7907
7908                 if (param_count == 0) {
7909                         amd64_jump_membase (code, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7910                 } else {
7911                         /* We have to shift the arguments left */
7912                         amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
7913                         for (i = 0; i < param_count; ++i) {
7914 #ifdef HOST_WIN32
7915                                 if (i < 3)
7916                                         amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7917                                 else
7918                                         amd64_mov_reg_membase (code, param_regs [i], AMD64_RSP, 0x28, 8);
7919 #else
7920                                 amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
7921 #endif
7922                         }
7923
7924                         amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
7925                 }
7926                 g_assert ((code - start) < 64);
7927         }
7928
7929         nacl_global_codeman_validate(&start, 64, &code);
7930
7931         mono_debug_add_delegate_trampoline (start, code - start);
7932
7933         if (code_len)
7934                 *code_len = code - start;
7935
7936
7937         if (mono_jit_map_is_enabled ()) {
7938                 char *buff;
7939                 if (has_target)
7940                         buff = (char*)"delegate_invoke_has_target";
7941                 else
7942                         buff = g_strdup_printf ("delegate_invoke_no_target_%d", param_count);
7943                 mono_emit_jit_tramp (start, code - start, buff);
7944                 if (!has_target)
7945                         g_free (buff);
7946         }
7947
7948         return start;
7949 }
7950
7951 /*
7952  * mono_arch_get_delegate_invoke_impls:
7953  *
7954  *   Return a list of MonoTrampInfo structures for the delegate invoke impl
7955  * trampolines.
7956  */
7957 GSList*
7958 mono_arch_get_delegate_invoke_impls (void)
7959 {
7960         GSList *res = NULL;
7961         guint8 *code;
7962         guint32 code_len;
7963         int i;
7964         char *tramp_name;
7965
7966         code = get_delegate_invoke_impl (TRUE, 0, &code_len);
7967         res = g_slist_prepend (res, mono_tramp_info_create ("delegate_invoke_impl_has_target", code, code_len, NULL, NULL));
7968
7969         for (i = 0; i < MAX_ARCH_DELEGATE_PARAMS; ++i) {
7970                 code = get_delegate_invoke_impl (FALSE, i, &code_len);
7971                 tramp_name = g_strdup_printf ("delegate_invoke_impl_target_%d", i);
7972                 res = g_slist_prepend (res, mono_tramp_info_create (tramp_name, code, code_len, NULL, NULL));
7973                 g_free (tramp_name);
7974         }
7975
7976         return res;
7977 }
7978
7979 gpointer
7980 mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
7981 {
7982         guint8 *code, *start;
7983         int i;
7984
7985         if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
7986                 return NULL;
7987
7988         /* FIXME: Support more cases */
7989         if (MONO_TYPE_ISSTRUCT (sig->ret))
7990                 return NULL;
7991
7992         if (has_target) {
7993                 static guint8* cached = NULL;
7994
7995                 if (cached)
7996                         return cached;
7997
7998                 if (mono_aot_only)
7999                         start = mono_aot_get_trampoline ("delegate_invoke_impl_has_target");
8000                 else
8001                         start = get_delegate_invoke_impl (TRUE, 0, NULL);
8002
8003                 mono_memory_barrier ();
8004
8005                 cached = start;
8006         } else {
8007                 static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
8008                 for (i = 0; i < sig->param_count; ++i)
8009                         if (!mono_is_regsize_var (sig->params [i]))
8010                                 return NULL;
8011                 if (sig->param_count > 4)
8012                         return NULL;
8013
8014                 code = cache [sig->param_count];
8015                 if (code)
8016                         return code;
8017
8018                 if (mono_aot_only) {
8019                         char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count);
8020                         start = mono_aot_get_trampoline (name);
8021                         g_free (name);
8022                 } else {
8023                         start = get_delegate_invoke_impl (FALSE, sig->param_count, NULL);
8024                 }
8025
8026                 mono_memory_barrier ();
8027
8028                 cache [sig->param_count] = start;
8029         }
8030
8031         return start;
8032 }
8033 void
8034 mono_arch_finish_init (void)
8035 {
8036 #ifdef HOST_WIN32
8037         /* 
8038          * We need to init this multiple times, since when we are first called, the key might not
8039          * be initialized yet.
8040          */
8041         appdomain_tls_offset = mono_domain_get_tls_key ();
8042         lmf_tls_offset = mono_get_jit_tls_key ();
8043         lmf_addr_tls_offset = mono_get_jit_tls_key ();
8044
8045         /* Only 64 tls entries can be accessed using inline code */
8046         if (appdomain_tls_offset >= 64)
8047                 appdomain_tls_offset = -1;
8048         if (lmf_tls_offset >= 64)
8049                 lmf_tls_offset = -1;
8050         if (lmf_addr_tls_offset >= 64)
8051                 lmf_addr_tls_offset = -1;
8052 #else
8053 #ifdef MONO_XEN_OPT
8054         optimize_for_xen = access ("/proc/xen", F_OK) == 0;
8055 #endif
8056         appdomain_tls_offset = mono_domain_get_tls_offset ();
8057         lmf_tls_offset = mono_get_lmf_tls_offset ();
8058         lmf_addr_tls_offset = mono_get_lmf_addr_tls_offset ();
8059 #endif
8060 }
8061
8062 void
8063 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
8064 {
8065 }
8066
8067 #ifdef MONO_ARCH_HAVE_IMT
8068
8069 #if defined(__default_codegen__)
8070 #define CMP_SIZE (6 + 1)
8071 #define CMP_REG_REG_SIZE (4 + 1)
8072 #define BR_SMALL_SIZE 2
8073 #define BR_LARGE_SIZE 6
8074 #define MOV_REG_IMM_SIZE 10
8075 #define MOV_REG_IMM_32BIT_SIZE 6
8076 #define JUMP_REG_SIZE (2 + 1)
8077 #elif defined(__native_client_codegen__)
8078 /* NaCl N-byte instructions can be padded up to N-1 bytes */
8079 #define CMP_SIZE ((6 + 1) * 2 - 1)
8080 #define CMP_REG_REG_SIZE ((4 + 1) * 2 - 1)
8081 #define BR_SMALL_SIZE (2 * 2 - 1)
8082 #define BR_LARGE_SIZE (6 * 2 - 1)
8083 #define MOV_REG_IMM_SIZE (10 * 2 - 1)
8084 #define MOV_REG_IMM_32BIT_SIZE (6 * 2 - 1)
8085 /* Jump reg for NaCl adds a mask (+4) and add (+3) */
8086 #define JUMP_REG_SIZE ((2 + 1 + 4 + 3) * 2 - 1)
8087 /* Jump membase's size is large and unpredictable    */
8088 /* in native client, just pad it out a whole bundle. */
8089 #define JUMP_MEMBASE_SIZE (kNaClAlignment)
8090 #endif
8091
8092 static int
8093 imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target)
8094 {
8095         int i, distance = 0;
8096         for (i = start; i < target; ++i)
8097                 distance += imt_entries [i]->chunk_size;
8098         return distance;
8099 }
8100
8101 /*
8102  * LOCKING: called with the domain lock held
8103  */
8104 gpointer
8105 mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count,
8106         gpointer fail_tramp)
8107 {
8108         int i;
8109         int size = 0;
8110         guint8 *code, *start;
8111         gboolean vtable_is_32bit = ((gsize)(vtable) == (gsize)(int)(gsize)(vtable));
8112
8113         for (i = 0; i < count; ++i) {
8114                 MonoIMTCheckItem *item = imt_entries [i];
8115                 if (item->is_equals) {
8116                         if (item->check_target_idx) {
8117                                 if (!item->compare_done) {
8118                                         if (amd64_is_imm32 (item->key))
8119                                                 item->chunk_size += CMP_SIZE;
8120                                         else
8121                                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8122                                 }
8123                                 if (item->has_target_code) {
8124                                         item->chunk_size += MOV_REG_IMM_SIZE;
8125                                 } else {
8126                                         if (vtable_is_32bit)
8127                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8128                                         else
8129                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8130 #ifdef __native_client_codegen__
8131                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8132 #endif
8133                                 }
8134                                 item->chunk_size += BR_SMALL_SIZE + JUMP_REG_SIZE;
8135                         } else {
8136                                 if (fail_tramp) {
8137                                         item->chunk_size += MOV_REG_IMM_SIZE * 3 + CMP_REG_REG_SIZE +
8138                                                 BR_SMALL_SIZE + JUMP_REG_SIZE * 2;
8139                                 } else {
8140                                         if (vtable_is_32bit)
8141                                                 item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
8142                                         else
8143                                                 item->chunk_size += MOV_REG_IMM_SIZE;
8144                                         item->chunk_size += JUMP_REG_SIZE;
8145                                         /* with assert below:
8146                                          * item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1;
8147                                          */
8148 #ifdef __native_client_codegen__
8149                                         item->chunk_size += JUMP_MEMBASE_SIZE;
8150 #endif
8151                                 }
8152                         }
8153                 } else {
8154                         if (amd64_is_imm32 (item->key))
8155                                 item->chunk_size += CMP_SIZE;
8156                         else
8157                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
8158                         item->chunk_size += BR_LARGE_SIZE;
8159                         imt_entries [item->check_target_idx]->compare_done = TRUE;
8160                 }
8161                 size += item->chunk_size;
8162         }
8163 #if defined(__native_client__) && defined(__native_client_codegen__)
8164         /* In Native Client, we don't re-use thunks, allocate from the */
8165         /* normal code manager paths. */
8166         code = mono_domain_code_reserve (domain, size);
8167 #else
8168         if (fail_tramp)
8169                 code = mono_method_alloc_generic_virtual_thunk (domain, size);
8170         else
8171                 code = mono_domain_code_reserve (domain, size);
8172 #endif
8173         start = code;
8174         for (i = 0; i < count; ++i) {
8175                 MonoIMTCheckItem *item = imt_entries [i];
8176                 item->code_target = code;
8177                 if (item->is_equals) {
8178                         gboolean fail_case = !item->check_target_idx && fail_tramp;
8179
8180                         if (item->check_target_idx || fail_case) {
8181                                 if (!item->compare_done || fail_case) {
8182                                         if (amd64_is_imm32 (item->key))
8183                                                 amd64_alu_reg_imm_size (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key, sizeof(gpointer));
8184                                         else {
8185                                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8186                                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8187                                         }
8188                                 }
8189                                 item->jmp_code = code;
8190                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8191                                 if (item->has_target_code) {
8192                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->value.target_code);
8193                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8194                                 } else {
8195                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8196                                         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8197                                 }
8198
8199                                 if (fail_case) {
8200                                         amd64_patch (item->jmp_code, code);
8201                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, fail_tramp);
8202                                         amd64_jump_reg (code, MONO_ARCH_IMT_SCRATCH_REG);
8203                                         item->jmp_code = NULL;
8204                                 }
8205                         } else {
8206                                 /* enable the commented code to assert on wrong method */
8207 #if 0
8208                                 if (amd64_is_imm32 (item->key))
8209                                         amd64_alu_reg_imm_size (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key, sizeof(gpointer));
8210                                 else {
8211                                         amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8212                                         amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8213                                 }
8214                                 item->jmp_code = code;
8215                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
8216                                 /* See the comment below about R10 */
8217                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8218                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8219                                 amd64_patch (item->jmp_code, code);
8220                                 amd64_breakpoint (code);
8221                                 item->jmp_code = NULL;
8222 #else
8223                                 /* We're using R10 (MONO_ARCH_IMT_SCRATCH_REG) here because R11 (MONO_ARCH_IMT_REG)
8224                                    needs to be preserved.  R10 needs
8225                                    to be preserved for calls which
8226                                    require a runtime generic context,
8227                                    but interface calls don't. */
8228                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, & (vtable->vtable [item->value.vtable_slot]));
8229                                 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
8230 #endif
8231                         }
8232                 } else {
8233                         if (amd64_is_imm32 (item->key))
8234                                 amd64_alu_reg_imm_size (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->key, sizeof (gpointer));
8235                         else {
8236                                 amd64_mov_reg_imm (code, MONO_ARCH_IMT_SCRATCH_REG, item->key);
8237                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, MONO_ARCH_IMT_SCRATCH_REG);
8238                         }
8239                         item->jmp_code = code;
8240                         if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx)))
8241                                 x86_branch8 (code, X86_CC_GE, 0, FALSE);
8242                         else
8243                                 x86_branch32 (code, X86_CC_GE, 0, FALSE);
8244                 }
8245                 g_assert (code - item->code_target <= item->chunk_size);
8246         }
8247         /* patch the branches to get to the target items */
8248         for (i = 0; i < count; ++i) {
8249                 MonoIMTCheckItem *item = imt_entries [i];
8250                 if (item->jmp_code) {
8251                         if (item->check_target_idx) {
8252                                 amd64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
8253                         }
8254                 }
8255         }
8256
8257         if (!fail_tramp)
8258                 mono_stats.imt_thunks_size += code - start;
8259         g_assert (code - start <= size);
8260
8261         nacl_domain_code_validate(domain, &start, size, &code);
8262
8263         return start;
8264 }
8265
8266 MonoMethod*
8267 mono_arch_find_imt_method (mgreg_t *regs, guint8 *code)
8268 {
8269         return (MonoMethod*)regs [MONO_ARCH_IMT_REG];
8270 }
8271 #endif
8272
8273 MonoVTable*
8274 mono_arch_find_static_call_vtable (mgreg_t *regs, guint8 *code)
8275 {
8276         return (MonoVTable*) regs [MONO_ARCH_RGCTX_REG];
8277 }
8278
8279 GSList*
8280 mono_arch_get_cie_program (void)
8281 {
8282         GSList *l = NULL;
8283
8284         mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
8285         mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
8286
8287         return l;
8288 }
8289
8290 MonoInst*
8291 mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
8292 {
8293         MonoInst *ins = NULL;
8294         int opcode = 0;
8295
8296         if (cmethod->klass == mono_defaults.math_class) {
8297                 if (strcmp (cmethod->name, "Sin") == 0) {
8298                         opcode = OP_SIN;
8299                 } else if (strcmp (cmethod->name, "Cos") == 0) {
8300                         opcode = OP_COS;
8301                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
8302                         opcode = OP_SQRT;
8303                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
8304                         opcode = OP_ABS;
8305                 }
8306                 
8307                 if (opcode) {
8308                         MONO_INST_NEW (cfg, ins, opcode);
8309                         ins->type = STACK_R8;
8310                         ins->dreg = mono_alloc_freg (cfg);
8311                         ins->sreg1 = args [0]->dreg;
8312                         MONO_ADD_INS (cfg->cbb, ins);
8313                 }
8314
8315                 opcode = 0;
8316                 if (cfg->opt & MONO_OPT_CMOV) {
8317                         if (strcmp (cmethod->name, "Min") == 0) {
8318                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8319                                         opcode = OP_IMIN;
8320                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8321                                         opcode = OP_IMIN_UN;
8322                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8323                                         opcode = OP_LMIN;
8324                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8325                                         opcode = OP_LMIN_UN;
8326                         } else if (strcmp (cmethod->name, "Max") == 0) {
8327                                 if (fsig->params [0]->type == MONO_TYPE_I4)
8328                                         opcode = OP_IMAX;
8329                                 if (fsig->params [0]->type == MONO_TYPE_U4)
8330                                         opcode = OP_IMAX_UN;
8331                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
8332                                         opcode = OP_LMAX;
8333                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
8334                                         opcode = OP_LMAX_UN;
8335                         }
8336                 }
8337                 
8338                 if (opcode) {
8339                         MONO_INST_NEW (cfg, ins, opcode);
8340                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
8341                         ins->dreg = mono_alloc_ireg (cfg);
8342                         ins->sreg1 = args [0]->dreg;
8343                         ins->sreg2 = args [1]->dreg;
8344                         MONO_ADD_INS (cfg->cbb, ins);
8345                 }
8346
8347 #if 0
8348                 /* OP_FREM is not IEEE compatible */
8349                 else if (strcmp (cmethod->name, "IEEERemainder") == 0) {
8350                         MONO_INST_NEW (cfg, ins, OP_FREM);
8351                         ins->inst_i0 = args [0];
8352                         ins->inst_i1 = args [1];
8353                 }
8354 #endif
8355         }
8356
8357         /* 
8358          * Can't implement CompareExchange methods this way since they have
8359          * three arguments.
8360          */
8361
8362         return ins;
8363 }
8364
8365 gboolean
8366 mono_arch_print_tree (MonoInst *tree, int arity)
8367 {
8368         return 0;
8369 }
8370
8371 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
8372 {
8373         MonoInst* ins;
8374         
8375         if (appdomain_tls_offset == -1)
8376                 return NULL;
8377         
8378         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8379         ins->inst_offset = appdomain_tls_offset;
8380         return ins;
8381 }
8382
8383 #define _CTX_REG(ctx,fld,i) ((&ctx->fld)[i])
8384
8385 mgreg_t
8386 mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
8387 {
8388         switch (reg) {
8389         case AMD64_RCX: return ctx->rcx;
8390         case AMD64_RDX: return ctx->rdx;
8391         case AMD64_RBX: return ctx->rbx;
8392         case AMD64_RBP: return ctx->rbp;
8393         case AMD64_RSP: return ctx->rsp;
8394         default:
8395                 return _CTX_REG (ctx, rax, reg);
8396         }
8397 }
8398
8399 void
8400 mono_arch_context_set_int_reg (MonoContext *ctx, int reg, mgreg_t val)
8401 {
8402         switch (reg) {
8403         case AMD64_RCX:
8404                 ctx->rcx = val;
8405                 break;
8406         case AMD64_RDX: 
8407                 ctx->rdx = val;
8408                 break;
8409         case AMD64_RBX:
8410                 ctx->rbx = val;
8411                 break;
8412         case AMD64_RBP:
8413                 ctx->rbp = val;
8414                 break;
8415         case AMD64_RSP:
8416                 ctx->rsp = val;
8417                 break;
8418         default:
8419                 _CTX_REG (ctx, rax, reg) = val;
8420         }
8421 }
8422
8423 /*MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD*/
8424 gpointer
8425 mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value)
8426 {
8427         int offset;
8428         gpointer *sp, old_value;
8429         char *bp;
8430         const unsigned char *handler;
8431
8432         /*Decode the first instruction to figure out where did we store the spvar*/
8433         /*Our jit MUST generate the following:
8434          mov    %rsp, ?(%rbp)
8435
8436          Which is encoded as: REX.W 0x89 mod_rm
8437          mod_rm (rsp, rbp, imm) which can be: (imm will never be zero)
8438                 mod (reg + imm8):  01 reg(rsp): 100 rm(rbp): 101 -> 01100101 (0x65)
8439                 mod (reg + imm32): 10 reg(rsp): 100 rm(rbp): 101 -> 10100101 (0xA5)
8440
8441         FIXME can we generate frameless methods on this case?
8442
8443         */
8444         handler = clause->handler_start;
8445
8446         /*REX.W*/
8447         if (*handler != 0x48)
8448                 return NULL;
8449         ++handler;
8450
8451         /*mov r, r/m */
8452         if (*handler != 0x89)
8453                 return NULL;
8454         ++handler;
8455
8456         if (*handler == 0x65)
8457                 offset = *(signed char*)(handler + 1);
8458         else if (*handler == 0xA5)
8459                 offset = *(int*)(handler + 1);
8460         else
8461                 return NULL;
8462
8463         /*Load the spvar*/
8464         bp = MONO_CONTEXT_GET_BP (ctx);
8465         sp = *(gpointer*)(bp + offset);
8466
8467         old_value = *sp;
8468         if (old_value < ji->code_start || (char*)old_value > ((char*)ji->code_start + ji->code_size))
8469                 return old_value;
8470
8471         *sp = new_value;
8472
8473         return old_value;
8474 }
8475
8476 /*
8477  * mono_arch_emit_load_aotconst:
8478  *
8479  *   Emit code to load the contents of the GOT slot identified by TRAMP_TYPE and
8480  * TARGET from the mscorlib GOT in full-aot code.
8481  * On AMD64, the result is placed into R11.
8482  */
8483 guint8*
8484 mono_arch_emit_load_aotconst (guint8 *start, guint8 *code, MonoJumpInfo **ji, int tramp_type, gconstpointer target)
8485 {
8486         *ji = mono_patch_info_list_prepend (*ji, code - start, tramp_type, target);
8487         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
8488
8489         return code;
8490 }
8491
8492 /*
8493  * mono_arch_get_trampolines:
8494  *
8495  *   Return a list of MonoTrampInfo structures describing arch specific trampolines
8496  * for AOT.
8497  */
8498 GSList *
8499 mono_arch_get_trampolines (gboolean aot)
8500 {
8501         return mono_amd64_get_exception_trampolines (aot);
8502 }
8503
8504 /* Soft Debug support */
8505 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
8506
8507 /*
8508  * mono_arch_set_breakpoint:
8509  *
8510  *   Set a breakpoint at the native code corresponding to JI at NATIVE_OFFSET.
8511  * The location should contain code emitted by OP_SEQ_POINT.
8512  */
8513 void
8514 mono_arch_set_breakpoint (MonoJitInfo *ji, guint8 *ip)
8515 {
8516         guint8 *code = ip;
8517         guint8 *orig_code = code;
8518
8519         if (ji->from_aot) {
8520                 guint32 native_offset = ip - (guint8*)ji->code_start;
8521                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8522
8523                 g_assert (info->bp_addrs [native_offset] == 0);
8524                 info->bp_addrs [native_offset] = bp_trigger_page;
8525         } else {
8526                 /* 
8527                  * In production, we will use int3 (has to fix the size in the md 
8528                  * file). But that could confuse gdb, so during development, we emit a SIGSEGV
8529                  * instead.
8530                  */
8531                 g_assert (code [0] == 0x90);
8532                 if (breakpoint_size == 8) {
8533                         amd64_mov_reg_mem (code, AMD64_R11, (guint64)bp_trigger_page, 4);
8534                 } else {
8535                         amd64_mov_reg_imm_size (code, AMD64_R11, (guint64)bp_trigger_page, 8);
8536                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 4);
8537                 }
8538
8539                 g_assert (code - orig_code == breakpoint_size);
8540         }
8541 }
8542
8543 /*
8544  * mono_arch_clear_breakpoint:
8545  *
8546  *   Clear the breakpoint at IP.
8547  */
8548 void
8549 mono_arch_clear_breakpoint (MonoJitInfo *ji, guint8 *ip)
8550 {
8551         guint8 *code = ip;
8552         int i;
8553
8554         if (ji->from_aot) {
8555                 guint32 native_offset = ip - (guint8*)ji->code_start;
8556                 SeqPointInfo *info = mono_arch_get_seq_point_info (mono_domain_get (), ji->code_start);
8557
8558                 g_assert (info->bp_addrs [native_offset] == 0);
8559                 info->bp_addrs [native_offset] = info;
8560         } else {
8561                 for (i = 0; i < breakpoint_size; ++i)
8562                         x86_nop (code);
8563         }
8564 }
8565
8566 gboolean
8567 mono_arch_is_breakpoint_event (void *info, void *sigctx)
8568 {
8569 #ifdef HOST_WIN32
8570         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8571         return FALSE;
8572 #else
8573         siginfo_t* sinfo = (siginfo_t*) info;
8574         /* Sometimes the address is off by 4 */
8575         if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128)
8576                 return TRUE;
8577         else
8578                 return FALSE;
8579 #endif
8580 }
8581
8582 /*
8583  * mono_arch_skip_breakpoint:
8584  *
8585  *   Modify CTX so the ip is placed after the breakpoint instruction, so when
8586  * we resume, the instruction is not executed again.
8587  */
8588 void
8589 mono_arch_skip_breakpoint (MonoContext *ctx, MonoJitInfo *ji)
8590 {
8591         if (ji->from_aot) {
8592                 /* amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, 0, 8) */
8593                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + 3);
8594         } else {
8595                 MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + breakpoint_fault_size);
8596         }
8597 }
8598         
8599 /*
8600  * mono_arch_start_single_stepping:
8601  *
8602  *   Start single stepping.
8603  */
8604 void
8605 mono_arch_start_single_stepping (void)
8606 {
8607         mono_mprotect (ss_trigger_page, mono_pagesize (), 0);
8608 }
8609         
8610 /*
8611  * mono_arch_stop_single_stepping:
8612  *
8613  *   Stop single stepping.
8614  */
8615 void
8616 mono_arch_stop_single_stepping (void)
8617 {
8618         mono_mprotect (ss_trigger_page, mono_pagesize (), MONO_MMAP_READ);
8619 }
8620
8621 /*
8622  * mono_arch_is_single_step_event:
8623  *
8624  *   Return whenever the machine state in SIGCTX corresponds to a single
8625  * step event.
8626  */
8627 gboolean
8628 mono_arch_is_single_step_event (void *info, void *sigctx)
8629 {
8630 #ifdef HOST_WIN32
8631         EXCEPTION_RECORD* einfo = (EXCEPTION_RECORD*)info;
8632         return FALSE;
8633 #else
8634         siginfo_t* sinfo = (siginfo_t*) info;
8635         /* Sometimes the address is off by 4 */
8636         if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128)
8637                 return TRUE;
8638         else
8639                 return FALSE;
8640 #endif
8641 }
8642
8643 /*
8644  * mono_arch_skip_single_step:
8645  *
8646  *   Modify CTX so the ip is placed after the single step trigger instruction,
8647  * we resume, the instruction is not executed again.
8648  */
8649 void
8650 mono_arch_skip_single_step (MonoContext *ctx)
8651 {
8652         MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + single_step_fault_size);
8653 }
8654
8655 /*
8656  * mono_arch_create_seq_point_info:
8657  *
8658  *   Return a pointer to a data structure which is used by the sequence
8659  * point implementation in AOTed code.
8660  */
8661 gpointer
8662 mono_arch_get_seq_point_info (MonoDomain *domain, guint8 *code)
8663 {
8664         SeqPointInfo *info;
8665         MonoJitInfo *ji;
8666         int i;
8667
8668         // FIXME: Add a free function
8669
8670         mono_domain_lock (domain);
8671         info = g_hash_table_lookup (domain_jit_info (domain)->arch_seq_points,
8672                                                                 code);
8673         mono_domain_unlock (domain);
8674
8675         if (!info) {
8676                 ji = mono_jit_info_table_find (domain, (char*)code);
8677                 g_assert (ji);
8678
8679                 // FIXME: Optimize the size
8680                 info = g_malloc0 (sizeof (SeqPointInfo) + (ji->code_size * sizeof (gpointer)));
8681
8682                 info->ss_trigger_page = ss_trigger_page;
8683                 info->bp_trigger_page = bp_trigger_page;
8684                 /* Initialize to a valid address */
8685                 for (i = 0; i < ji->code_size; ++i)
8686                         info->bp_addrs [i] = info;
8687
8688                 mono_domain_lock (domain);
8689                 g_hash_table_insert (domain_jit_info (domain)->arch_seq_points,
8690                                                          code, info);
8691                 mono_domain_unlock (domain);
8692         }
8693
8694         return info;
8695 }
8696
8697 #endif