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