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