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