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