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