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