2008-02-06 Zoltan Varga <vargaz@gmail.com>
[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/utils/mono-math.h>
27
28 #include "trace.h"
29 #include "mini-amd64.h"
30 #include "inssel.h"
31 #include "cpu-amd64.h"
32
33 static gint lmf_tls_offset = -1;
34 static gint lmf_addr_tls_offset = -1;
35 static gint appdomain_tls_offset = -1;
36 static gint thread_tls_offset = -1;
37
38 #ifdef MONO_XEN_OPT
39 static gboolean optimize_for_xen = TRUE;
40 #else
41 #define optimize_for_xen 0
42 #endif
43
44 static gboolean use_sse2 = !MONO_ARCH_USE_FPSTACK;
45
46 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
47
48 #define IS_IMM32(val) ((((guint64)val) >> 32) == 0)
49
50 #define IS_REX(inst) (((inst) >= 0x40) && ((inst) <= 0x4f))
51
52 #ifdef PLATFORM_WIN32
53 /* Under windows, the default pinvoke calling convention is stdcall */
54 #define CALLCONV_IS_STDCALL(call_conv) (((call_conv) == MONO_CALL_STDCALL) || ((call_conv) == MONO_CALL_DEFAULT))
55 #else
56 #define CALLCONV_IS_STDCALL(call_conv) ((call_conv) == MONO_CALL_STDCALL)
57 #endif
58
59 /* This mutex protects architecture specific caches */
60 #define mono_mini_arch_lock() EnterCriticalSection (&mini_arch_mutex)
61 #define mono_mini_arch_unlock() LeaveCriticalSection (&mini_arch_mutex)
62 static CRITICAL_SECTION mini_arch_mutex;
63
64 MonoBreakpointInfo
65 mono_breakpoint_info [MONO_BREAKPOINT_ARRAY_SIZE];
66
67 #define ARGS_OFFSET 16
68 #define GP_SCRATCH_REG AMD64_R11
69
70 /*
71  * AMD64 register usage:
72  * - callee saved registers are used for global register allocation
73  * - %r11 is used for materializing 64 bit constants in opcodes
74  * - the rest is used for local allocation
75  */
76
77 /*
78  * Floating point comparison results:
79  *                  ZF PF CF
80  * A > B            0  0  0
81  * A < B            0  0  1
82  * A = B            1  0  0
83  * A > B            0  0  0
84  * UNORDERED        1  1  1
85  */
86
87 const char*
88 mono_arch_regname (int reg) {
89         switch (reg) {
90         case AMD64_RAX: return "%rax";
91         case AMD64_RBX: return "%rbx";
92         case AMD64_RCX: return "%rcx";
93         case AMD64_RDX: return "%rdx";
94         case AMD64_RSP: return "%rsp";  
95         case AMD64_RBP: return "%rbp";
96         case AMD64_RDI: return "%rdi";
97         case AMD64_RSI: return "%rsi";
98         case AMD64_R8: return "%r8";
99         case AMD64_R9: return "%r9";
100         case AMD64_R10: return "%r10";
101         case AMD64_R11: return "%r11";
102         case AMD64_R12: return "%r12";
103         case AMD64_R13: return "%r13";
104         case AMD64_R14: return "%r14";
105         case AMD64_R15: return "%r15";
106         }
107         return "unknown";
108 }
109
110 static const char * xmmregs [] = {
111         "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8",
112         "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"
113 };
114
115 const char*
116 mono_arch_fregname (int reg)
117 {
118         if (reg < AMD64_XMM_NREG)
119                 return xmmregs [reg];
120         else
121                 return "unknown";
122 }
123
124 G_GNUC_UNUSED static void
125 break_count (void)
126 {
127 }
128
129 G_GNUC_UNUSED static gboolean
130 debug_count (void)
131 {
132         static int count = 0;
133         count ++;
134
135         if (!getenv ("COUNT"))
136                 return TRUE;
137
138         if (count == atoi (getenv ("COUNT"))) {
139                 break_count ();
140         }
141
142         if (count > atoi (getenv ("COUNT"))) {
143                 return FALSE;
144         }
145
146         return TRUE;
147 }
148
149 static gboolean
150 debug_omit_fp (void)
151 {
152 #if 0
153         return debug_count ();
154 #else
155         return TRUE;
156 #endif
157 }
158
159 static inline gboolean
160 amd64_is_near_call (guint8 *code)
161 {
162         /* Skip REX */
163         if ((code [0] >= 0x40) && (code [0] <= 0x4f))
164                 code += 1;
165
166         return code [0] == 0xe8;
167 }
168
169 static inline void 
170 amd64_patch (unsigned char* code, gpointer target)
171 {
172         /* Skip REX */
173         if ((code [0] >= 0x40) && (code [0] <= 0x4f))
174                 code += 1;
175
176         if ((code [0] & 0xf8) == 0xb8) {
177                 /* amd64_set_reg_template */
178                 *(guint64*)(code + 1) = (guint64)target;
179         }
180         else if (code [0] == 0x8b) {
181                 /* mov 0(%rip), %dreg */
182                 *(guint32*)(code + 2) = (guint32)(guint64)target - 7;
183         }
184         else if ((code [0] == 0xff) && (code [1] == 0x15)) {
185                 /* call *<OFFSET>(%rip) */
186                 *(guint32*)(code + 2) = ((guint32)(guint64)target) - 7;
187         }
188         else if ((code [0] == 0xe8)) {
189                 /* call <DISP> */
190                 gint64 disp = (guint8*)target - (guint8*)code;
191                 g_assert (amd64_is_imm32 (disp));
192                 x86_patch (code, (unsigned char*)target);
193         }
194         else
195                 x86_patch (code, (unsigned char*)target);
196 }
197
198 void 
199 mono_amd64_patch (unsigned char* code, gpointer target)
200 {
201         amd64_patch (code, target);
202 }
203
204 typedef enum {
205         ArgInIReg,
206         ArgInFloatSSEReg,
207         ArgInDoubleSSEReg,
208         ArgOnStack,
209         ArgValuetypeInReg,
210         ArgNone /* only in pair_storage */
211 } ArgStorage;
212
213 typedef struct {
214         gint16 offset;
215         gint8  reg;
216         ArgStorage storage;
217
218         /* Only if storage == ArgValuetypeInReg */
219         ArgStorage pair_storage [2];
220         gint8 pair_regs [2];
221 } ArgInfo;
222
223 typedef struct {
224         int nargs;
225         guint32 stack_usage;
226         guint32 reg_usage;
227         guint32 freg_usage;
228         gboolean need_stack_align;
229         ArgInfo ret;
230         ArgInfo sig_cookie;
231         ArgInfo args [1];
232 } CallInfo;
233
234 #define DEBUG(a) if (cfg->verbose_level > 1) a
235
236 #define NEW_ICONST(cfg,dest,val) do {   \
237                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
238                 (dest)->opcode = OP_ICONST;     \
239                 (dest)->inst_c0 = (val);        \
240                 (dest)->type = STACK_I4;        \
241         } while (0)
242
243 #ifdef PLATFORM_WIN32
244 #define PARAM_REGS 4
245
246 static AMD64_Reg_No param_regs [] = { AMD64_RCX, AMD64_RDX, AMD64_R8, AMD64_R9 };
247
248 static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
249 #else
250 #define PARAM_REGS 6
251  
252 static AMD64_Reg_No param_regs [] = { AMD64_RDI, AMD64_RSI, AMD64_RDX, AMD64_RCX, AMD64_R8, AMD64_R9 };
253
254  static AMD64_Reg_No return_regs [] = { AMD64_RAX, AMD64_RDX };
255 #endif
256
257 static void inline
258 add_general (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo)
259 {
260     ainfo->offset = *stack_size;
261
262     if (*gr >= PARAM_REGS) {
263                 ainfo->storage = ArgOnStack;
264                 (*stack_size) += sizeof (gpointer);
265     }
266     else {
267                 ainfo->storage = ArgInIReg;
268                 ainfo->reg = param_regs [*gr];
269                 (*gr) ++;
270     }
271 }
272
273 #ifdef PLATFORM_WIN32
274 #define FLOAT_PARAM_REGS 4
275 #else
276 #define FLOAT_PARAM_REGS 8
277 #endif
278
279 static void inline
280 add_float (guint32 *gr, guint32 *stack_size, ArgInfo *ainfo, gboolean is_double)
281 {
282     ainfo->offset = *stack_size;
283
284     if (*gr >= FLOAT_PARAM_REGS) {
285                 ainfo->storage = ArgOnStack;
286                 (*stack_size) += sizeof (gpointer);
287     }
288     else {
289                 /* A double register */
290                 if (is_double)
291                         ainfo->storage = ArgInDoubleSSEReg;
292                 else
293                         ainfo->storage = ArgInFloatSSEReg;
294                 ainfo->reg = *gr;
295                 (*gr) += 1;
296     }
297 }
298
299 typedef enum ArgumentClass {
300         ARG_CLASS_NO_CLASS,
301         ARG_CLASS_MEMORY,
302         ARG_CLASS_INTEGER,
303         ARG_CLASS_SSE
304 } ArgumentClass;
305
306 static ArgumentClass
307 merge_argument_class_from_type (MonoType *type, ArgumentClass class1)
308 {
309         ArgumentClass class2 = ARG_CLASS_NO_CLASS;
310         MonoType *ptype;
311
312         ptype = mono_type_get_underlying_type (type);
313         switch (ptype->type) {
314         case MONO_TYPE_BOOLEAN:
315         case MONO_TYPE_CHAR:
316         case MONO_TYPE_I1:
317         case MONO_TYPE_U1:
318         case MONO_TYPE_I2:
319         case MONO_TYPE_U2:
320         case MONO_TYPE_I4:
321         case MONO_TYPE_U4:
322         case MONO_TYPE_I:
323         case MONO_TYPE_U:
324         case MONO_TYPE_STRING:
325         case MONO_TYPE_OBJECT:
326         case MONO_TYPE_CLASS:
327         case MONO_TYPE_SZARRAY:
328         case MONO_TYPE_PTR:
329         case MONO_TYPE_FNPTR:
330         case MONO_TYPE_ARRAY:
331         case MONO_TYPE_I8:
332         case MONO_TYPE_U8:
333                 class2 = ARG_CLASS_INTEGER;
334                 break;
335         case MONO_TYPE_R4:
336         case MONO_TYPE_R8:
337                 class2 = ARG_CLASS_SSE;
338                 break;
339
340         case MONO_TYPE_TYPEDBYREF:
341                 g_assert_not_reached ();
342
343         case MONO_TYPE_GENERICINST:
344                 if (!mono_type_generic_inst_is_valuetype (ptype)) {
345                         class2 = ARG_CLASS_INTEGER;
346                         break;
347                 }
348                 /* fall through */
349         case MONO_TYPE_VALUETYPE: {
350                 MonoMarshalType *info = mono_marshal_load_type_info (ptype->data.klass);
351                 int i;
352
353                 for (i = 0; i < info->num_fields; ++i) {
354                         class2 = class1;
355                         class2 = merge_argument_class_from_type (info->fields [i].field->type, class2);
356                 }
357                 break;
358         }
359         default:
360                 g_assert_not_reached ();
361         }
362
363         /* Merge */
364         if (class1 == class2)
365                 ;
366         else if (class1 == ARG_CLASS_NO_CLASS)
367                 class1 = class2;
368         else if ((class1 == ARG_CLASS_MEMORY) || (class2 == ARG_CLASS_MEMORY))
369                 class1 = ARG_CLASS_MEMORY;
370         else if ((class1 == ARG_CLASS_INTEGER) || (class2 == ARG_CLASS_INTEGER))
371                 class1 = ARG_CLASS_INTEGER;
372         else
373                 class1 = ARG_CLASS_SSE;
374
375         return class1;
376 }
377
378 static void
379 add_valuetype (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig, ArgInfo *ainfo, MonoType *type,
380                gboolean is_return,
381                guint32 *gr, guint32 *fr, guint32 *stack_size)
382 {
383         guint32 size, quad, nquads, i;
384         ArgumentClass args [2];
385         MonoMarshalType *info;
386         MonoClass *klass;
387
388         klass = mono_class_from_mono_type (type);
389         if (sig->pinvoke) 
390                 size = mono_type_native_stack_size (&klass->byval_arg, NULL);
391         else 
392                 size = mini_type_stack_size (gsctx, &klass->byval_arg, NULL);
393
394         if (!sig->pinvoke || (size == 0) || (size > 16)) {
395                 /* Allways pass in memory */
396                 ainfo->offset = *stack_size;
397                 *stack_size += ALIGN_TO (size, 8);
398                 ainfo->storage = ArgOnStack;
399
400                 return;
401         }
402
403         /* FIXME: Handle structs smaller than 8 bytes */
404         //if ((size % 8) != 0)
405         //      NOT_IMPLEMENTED;
406
407         if (size > 8)
408                 nquads = 2;
409         else
410                 nquads = 1;
411
412         /*
413          * Implement the algorithm from section 3.2.3 of the X86_64 ABI.
414          * The X87 and SSEUP stuff is left out since there are no such types in
415          * the CLR.
416          */
417         info = mono_marshal_load_type_info (klass);
418         g_assert (info);
419         if (info->native_size > 16) {
420                 ainfo->offset = *stack_size;
421                 *stack_size += ALIGN_TO (info->native_size, 8);
422                 ainfo->storage = ArgOnStack;
423
424                 return;
425         }
426
427         args [0] = ARG_CLASS_NO_CLASS;
428         args [1] = ARG_CLASS_NO_CLASS;
429         for (quad = 0; quad < nquads; ++quad) {
430                 int size;
431                 guint32 align;
432                 ArgumentClass class1;
433                 
434                 class1 = ARG_CLASS_NO_CLASS;
435                 for (i = 0; i < info->num_fields; ++i) {
436                         size = mono_marshal_type_size (info->fields [i].field->type, 
437                                                                                    info->fields [i].mspec, 
438                                                                                    &align, TRUE, klass->unicode);
439                         if ((info->fields [i].offset < 8) && (info->fields [i].offset + size) > 8) {
440                                 /* Unaligned field */
441                                 NOT_IMPLEMENTED;
442                         }
443
444                         /* Skip fields in other quad */
445                         if ((quad == 0) && (info->fields [i].offset >= 8))
446                                 continue;
447                         if ((quad == 1) && (info->fields [i].offset < 8))
448                                 continue;
449
450                         class1 = merge_argument_class_from_type (info->fields [i].field->type, class1);
451                 }
452                 g_assert (class1 != ARG_CLASS_NO_CLASS);
453                 args [quad] = class1;
454         }
455
456         /* Post merger cleanup */
457         if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY))
458                 args [0] = args [1] = ARG_CLASS_MEMORY;
459
460         /* Allocate registers */
461         {
462                 int orig_gr = *gr;
463                 int orig_fr = *fr;
464
465                 ainfo->storage = ArgValuetypeInReg;
466                 ainfo->pair_storage [0] = ainfo->pair_storage [1] = ArgNone;
467                 for (quad = 0; quad < nquads; ++quad) {
468                         switch (args [quad]) {
469                         case ARG_CLASS_INTEGER:
470                                 if (*gr >= PARAM_REGS)
471                                         args [quad] = ARG_CLASS_MEMORY;
472                                 else {
473                                         ainfo->pair_storage [quad] = ArgInIReg;
474                                         if (is_return)
475                                                 ainfo->pair_regs [quad] = return_regs [*gr];
476                                         else
477                                                 ainfo->pair_regs [quad] = param_regs [*gr];
478                                         (*gr) ++;
479                                 }
480                                 break;
481                         case ARG_CLASS_SSE:
482                                 if (*fr >= FLOAT_PARAM_REGS)
483                                         args [quad] = ARG_CLASS_MEMORY;
484                                 else {
485                                         ainfo->pair_storage [quad] = ArgInDoubleSSEReg;
486                                         ainfo->pair_regs [quad] = *fr;
487                                         (*fr) ++;
488                                 }
489                                 break;
490                         case ARG_CLASS_MEMORY:
491                                 break;
492                         default:
493                                 g_assert_not_reached ();
494                         }
495                 }
496
497                 if ((args [0] == ARG_CLASS_MEMORY) || (args [1] == ARG_CLASS_MEMORY)) {
498                         /* Revert possible register assignments */
499                         *gr = orig_gr;
500                         *fr = orig_fr;
501
502                         ainfo->offset = *stack_size;
503                         *stack_size += ALIGN_TO (info->native_size, 8);
504                         ainfo->storage = ArgOnStack;
505                 }
506         }
507 }
508
509 /*
510  * get_call_info:
511  *
512  *  Obtain information about a call according to the calling convention.
513  * For AMD64, see the "System V ABI, x86-64 Architecture Processor Supplement 
514  * Draft Version 0.23" document for more information.
515  */
516 static CallInfo*
517 get_call_info (MonoCompile *cfg, MonoMemPool *mp, MonoMethodSignature *sig, gboolean is_pinvoke)
518 {
519         guint32 i, gr, fr;
520         MonoType *ret_type;
521         int n = sig->hasthis + sig->param_count;
522         guint32 stack_size = 0;
523         CallInfo *cinfo;
524         MonoGenericSharingContext *gsctx = cfg ? cfg->generic_sharing_context : NULL;
525
526         if (mp)
527                 cinfo = mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n));
528         else
529                 cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n));
530
531         gr = 0;
532         fr = 0;
533
534         /* return value */
535         {
536                 ret_type = mono_type_get_underlying_type (sig->ret);
537                 ret_type = mini_get_basic_type_from_generic (gsctx, ret_type);
538                 switch (ret_type->type) {
539                 case MONO_TYPE_BOOLEAN:
540                 case MONO_TYPE_I1:
541                 case MONO_TYPE_U1:
542                 case MONO_TYPE_I2:
543                 case MONO_TYPE_U2:
544                 case MONO_TYPE_CHAR:
545                 case MONO_TYPE_I4:
546                 case MONO_TYPE_U4:
547                 case MONO_TYPE_I:
548                 case MONO_TYPE_U:
549                 case MONO_TYPE_PTR:
550                 case MONO_TYPE_FNPTR:
551                 case MONO_TYPE_CLASS:
552                 case MONO_TYPE_OBJECT:
553                 case MONO_TYPE_SZARRAY:
554                 case MONO_TYPE_ARRAY:
555                 case MONO_TYPE_STRING:
556                         cinfo->ret.storage = ArgInIReg;
557                         cinfo->ret.reg = AMD64_RAX;
558                         break;
559                 case MONO_TYPE_U8:
560                 case MONO_TYPE_I8:
561                         cinfo->ret.storage = ArgInIReg;
562                         cinfo->ret.reg = AMD64_RAX;
563                         break;
564                 case MONO_TYPE_R4:
565                         cinfo->ret.storage = ArgInFloatSSEReg;
566                         cinfo->ret.reg = AMD64_XMM0;
567                         break;
568                 case MONO_TYPE_R8:
569                         cinfo->ret.storage = ArgInDoubleSSEReg;
570                         cinfo->ret.reg = AMD64_XMM0;
571                         break;
572                 case MONO_TYPE_GENERICINST:
573                         if (!mono_type_generic_inst_is_valuetype (sig->ret)) {
574                                 cinfo->ret.storage = ArgInIReg;
575                                 cinfo->ret.reg = AMD64_RAX;
576                                 break;
577                         }
578                         /* fall through */
579                 case MONO_TYPE_VALUETYPE: {
580                         guint32 tmp_gr = 0, tmp_fr = 0, tmp_stacksize = 0;
581
582                         add_valuetype (gsctx, sig, &cinfo->ret, sig->ret, TRUE, &tmp_gr, &tmp_fr, &tmp_stacksize);
583                         if (cinfo->ret.storage == ArgOnStack)
584                                 /* The caller passes the address where the value is stored */
585                                 add_general (&gr, &stack_size, &cinfo->ret);
586                         break;
587                 }
588                 case MONO_TYPE_TYPEDBYREF:
589                         /* Same as a valuetype with size 24 */
590                         add_general (&gr, &stack_size, &cinfo->ret);
591                         ;
592                         break;
593                 case MONO_TYPE_VOID:
594                         break;
595                 default:
596                         g_error ("Can't handle as return value 0x%x", sig->ret->type);
597                 }
598         }
599
600         /* this */
601         if (sig->hasthis)
602                 add_general (&gr, &stack_size, cinfo->args + 0);
603
604         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == 0)) {
605                 gr = PARAM_REGS;
606                 fr = FLOAT_PARAM_REGS;
607                 
608                 /* Emit the signature cookie just before the implicit arguments */
609                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
610         }
611
612         for (i = 0; i < sig->param_count; ++i) {
613                 ArgInfo *ainfo = &cinfo->args [sig->hasthis + i];
614                 MonoType *ptype;
615
616                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
617                         /* We allways pass the sig cookie on the stack for simplicity */
618                         /* 
619                          * Prevent implicit arguments + the sig cookie from being passed 
620                          * in registers.
621                          */
622                         gr = PARAM_REGS;
623                         fr = FLOAT_PARAM_REGS;
624
625                         /* Emit the signature cookie just before the implicit arguments */
626                         add_general (&gr, &stack_size, &cinfo->sig_cookie);
627                 }
628
629                 if (sig->params [i]->byref) {
630                         add_general (&gr, &stack_size, ainfo);
631                         continue;
632                 }
633                 ptype = mono_type_get_underlying_type (sig->params [i]);
634                 ptype = mini_get_basic_type_from_generic (gsctx, ptype);
635                 switch (ptype->type) {
636                 case MONO_TYPE_BOOLEAN:
637                 case MONO_TYPE_I1:
638                 case MONO_TYPE_U1:
639                         add_general (&gr, &stack_size, ainfo);
640                         break;
641                 case MONO_TYPE_I2:
642                 case MONO_TYPE_U2:
643                 case MONO_TYPE_CHAR:
644                         add_general (&gr, &stack_size, ainfo);
645                         break;
646                 case MONO_TYPE_I4:
647                 case MONO_TYPE_U4:
648                         add_general (&gr, &stack_size, ainfo);
649                         break;
650                 case MONO_TYPE_I:
651                 case MONO_TYPE_U:
652                 case MONO_TYPE_PTR:
653                 case MONO_TYPE_FNPTR:
654                 case MONO_TYPE_CLASS:
655                 case MONO_TYPE_OBJECT:
656                 case MONO_TYPE_STRING:
657                 case MONO_TYPE_SZARRAY:
658                 case MONO_TYPE_ARRAY:
659                         add_general (&gr, &stack_size, ainfo);
660                         break;
661                 case MONO_TYPE_GENERICINST:
662                         if (!mono_type_generic_inst_is_valuetype (ptype)) {
663                                 add_general (&gr, &stack_size, ainfo);
664                                 break;
665                         }
666                         /* fall through */
667                 case MONO_TYPE_VALUETYPE:
668                         add_valuetype (gsctx, sig, ainfo, sig->params [i], FALSE, &gr, &fr, &stack_size);
669                         break;
670                 case MONO_TYPE_TYPEDBYREF:
671                         stack_size += sizeof (MonoTypedRef);
672                         ainfo->storage = ArgOnStack;
673                         break;
674                 case MONO_TYPE_U8:
675                 case MONO_TYPE_I8:
676                         add_general (&gr, &stack_size, ainfo);
677                         break;
678                 case MONO_TYPE_R4:
679                         add_float (&fr, &stack_size, ainfo, FALSE);
680                         break;
681                 case MONO_TYPE_R8:
682                         add_float (&fr, &stack_size, ainfo, TRUE);
683                         break;
684                 default:
685                         g_assert_not_reached ();
686                 }
687         }
688
689         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n > 0) && (sig->sentinelpos == sig->param_count)) {
690                 gr = PARAM_REGS;
691                 fr = FLOAT_PARAM_REGS;
692                 
693                 /* Emit the signature cookie just before the implicit arguments */
694                 add_general (&gr, &stack_size, &cinfo->sig_cookie);
695         }
696
697 #ifdef PLATFORM_WIN32
698         if (stack_size < 32) {
699                 /* The Win64 ABI requires 32 bits  */
700                 stack_size = 32;
701         }
702 #endif
703
704         if (stack_size & 0x8) {
705                 /* The AMD64 ABI requires each stack frame to be 16 byte aligned */
706                 cinfo->need_stack_align = TRUE;
707                 stack_size += 8;
708         }
709
710         cinfo->stack_usage = stack_size;
711         cinfo->reg_usage = gr;
712         cinfo->freg_usage = fr;
713         return cinfo;
714 }
715
716 /*
717  * mono_arch_get_argument_info:
718  * @csig:  a method signature
719  * @param_count: the number of parameters to consider
720  * @arg_info: an array to store the result infos
721  *
722  * Gathers information on parameters such as size, alignment and
723  * padding. arg_info should be large enought to hold param_count + 1 entries. 
724  *
725  * Returns the size of the argument area on the stack.
726  */
727 int
728 mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
729 {
730         int k;
731         CallInfo *cinfo = get_call_info (NULL, NULL, csig, FALSE);
732         guint32 args_size = cinfo->stack_usage;
733
734         /* The arguments are saved to a stack area in mono_arch_instrument_prolog */
735         if (csig->hasthis) {
736                 arg_info [0].offset = 0;
737         }
738
739         for (k = 0; k < param_count; k++) {
740                 arg_info [k + 1].offset = ((k + csig->hasthis) * 8);
741                 /* FIXME: */
742                 arg_info [k + 1].size = 0;
743         }
744
745         g_free (cinfo);
746
747         return args_size;
748 }
749
750 static int 
751 cpuid (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx)
752 {
753         __asm__ __volatile__ ("cpuid"
754                 : "=a" (*p_eax), "=b" (*p_ebx), "=c" (*p_ecx), "=d" (*p_edx)
755                 : "a" (id));
756         return 1;
757 }
758
759 /*
760  * Initialize the cpu to execute managed code.
761  */
762 void
763 mono_arch_cpu_init (void)
764 {
765 #ifndef _MSC_VER
766         guint16 fpcw;
767
768         /* spec compliance requires running with double precision */
769         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
770         fpcw &= ~X86_FPCW_PRECC_MASK;
771         fpcw |= X86_FPCW_PREC_DOUBLE;
772         __asm__  __volatile__ ("fldcw %0\n": : "m" (fpcw));
773         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
774 #else
775         _control87 (_PC_53, MCW_PC);
776 #endif
777 }
778
779 /*
780  * Initialize architecture specific code.
781  */
782 void
783 mono_arch_init (void)
784 {
785         InitializeCriticalSection (&mini_arch_mutex);
786 }
787
788 /*
789  * Cleanup architecture specific code.
790  */
791 void
792 mono_arch_cleanup (void)
793 {
794         DeleteCriticalSection (&mini_arch_mutex);
795 }
796
797 /*
798  * This function returns the optimizations supported on this cpu.
799  */
800 guint32
801 mono_arch_cpu_optimizazions (guint32 *exclude_mask)
802 {
803         int eax, ebx, ecx, edx;
804         guint32 opts = 0;
805
806         /* FIXME: AMD64 */
807
808         *exclude_mask = 0;
809         /* Feature Flags function, flags returned in EDX. */
810         if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
811                 if (edx & (1 << 15)) {
812                         opts |= MONO_OPT_CMOV;
813                         if (edx & 1)
814                                 opts |= MONO_OPT_FCMOV;
815                         else
816                                 *exclude_mask |= MONO_OPT_FCMOV;
817                 } else
818                         *exclude_mask |= MONO_OPT_CMOV;
819         }
820         return opts;
821 }
822
823 gboolean
824 mono_amd64_is_sse2 (void)
825 {
826         return use_sse2;
827 }
828
829 GList *
830 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
831 {
832         GList *vars = NULL;
833         int i;
834
835         for (i = 0; i < cfg->num_varinfo; i++) {
836                 MonoInst *ins = cfg->varinfo [i];
837                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
838
839                 /* unused vars */
840                 if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
841                         continue;
842
843                 if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || 
844                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
845                         continue;
846
847                 if (mono_is_regsize_var (ins->inst_vtype)) {
848                         g_assert (MONO_VARINFO (cfg, i)->reg == -1);
849                         g_assert (i == vmv->idx);
850                         vars = g_list_prepend (vars, vmv);
851                 }
852         }
853
854         vars = mono_varlist_sort (cfg, vars, 0);
855
856         return vars;
857 }
858
859 /**
860  * mono_arch_compute_omit_fp:
861  *
862  *   Determine whenever the frame pointer can be eliminated.
863  */
864 static void
865 mono_arch_compute_omit_fp (MonoCompile *cfg)
866 {
867         MonoMethodSignature *sig;
868         MonoMethodHeader *header;
869         int i, locals_size;
870         CallInfo *cinfo;
871
872         if (cfg->arch.omit_fp_computed)
873                 return;
874
875         header = mono_method_get_header (cfg->method);
876
877         sig = mono_method_signature (cfg->method);
878
879         if (!cfg->arch.cinfo)
880                 cfg->arch.cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
881         cinfo = cfg->arch.cinfo;
882
883         /*
884          * FIXME: Remove some of the restrictions.
885          */
886         cfg->arch.omit_fp = TRUE;
887         cfg->arch.omit_fp_computed = TRUE;
888
889         /* Temporarily disable this when running in the debugger until we have support
890          * for this in the debugger. */
891         if (mono_debug_using_mono_debugger ())
892                 cfg->arch.omit_fp = FALSE;
893
894         if (!debug_omit_fp ())
895                 cfg->arch.omit_fp = FALSE;
896         /*
897         if (cfg->method->save_lmf)
898                 cfg->arch.omit_fp = FALSE;
899         */
900         if (cfg->flags & MONO_CFG_HAS_ALLOCA)
901                 cfg->arch.omit_fp = FALSE;
902         if (header->num_clauses)
903                 cfg->arch.omit_fp = FALSE;
904         if (cfg->param_area)
905                 cfg->arch.omit_fp = FALSE;
906         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG))
907                 cfg->arch.omit_fp = FALSE;
908         if ((mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) ||
909                 (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE))
910                 cfg->arch.omit_fp = FALSE;
911         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
912                 ArgInfo *ainfo = &cinfo->args [i];
913
914                 if (ainfo->storage == ArgOnStack) {
915                         /* 
916                          * The stack offset can only be determined when the frame
917                          * size is known.
918                          */
919                         cfg->arch.omit_fp = FALSE;
920                 }
921         }
922
923         if (cinfo->ret.storage == ArgValuetypeInReg)
924                 cfg->arch.omit_fp = FALSE;
925
926         locals_size = 0;
927         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
928                 MonoInst *ins = cfg->varinfo [i];
929                 int ialign;
930
931                 locals_size += mono_type_size (ins->inst_vtype, &ialign);
932         }
933
934         if ((cfg->num_varinfo > 10000) || (locals_size >= (1 << 15))) {
935                 /* Avoid hitting the stack_alloc_size < (1 << 16) assertion in emit_epilog () */
936                 cfg->arch.omit_fp = FALSE;
937         }
938 }
939
940 GList *
941 mono_arch_get_global_int_regs (MonoCompile *cfg)
942 {
943         GList *regs = NULL;
944
945         mono_arch_compute_omit_fp (cfg);
946
947         if (cfg->arch.omit_fp)
948                 regs = g_list_prepend (regs, (gpointer)AMD64_RBP);
949
950         /* We use the callee saved registers for global allocation */
951         regs = g_list_prepend (regs, (gpointer)AMD64_RBX);
952         regs = g_list_prepend (regs, (gpointer)AMD64_R12);
953         regs = g_list_prepend (regs, (gpointer)AMD64_R13);
954         regs = g_list_prepend (regs, (gpointer)AMD64_R14);
955         regs = g_list_prepend (regs, (gpointer)AMD64_R15);
956
957         return regs;
958 }
959
960 /*
961  * mono_arch_regalloc_cost:
962  *
963  *  Return the cost, in number of memory references, of the action of 
964  * allocating the variable VMV into a register during global register
965  * allocation.
966  */
967 guint32
968 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
969 {
970         MonoInst *ins = cfg->varinfo [vmv->idx];
971
972         if (cfg->method->save_lmf)
973                 /* The register is already saved */
974                 /* substract 1 for the invisible store in the prolog */
975                 return (ins->opcode == OP_ARG) ? 0 : 1;
976         else
977                 /* push+pop */
978                 return (ins->opcode == OP_ARG) ? 1 : 2;
979 }
980  
981 void
982 mono_arch_allocate_vars (MonoCompile *cfg)
983 {
984         MonoMethodSignature *sig;
985         MonoMethodHeader *header;
986         MonoInst *inst;
987         int i, offset;
988         guint32 locals_stack_size, locals_stack_align;
989         gint32 *offsets;
990         CallInfo *cinfo;
991
992         header = mono_method_get_header (cfg->method);
993
994         sig = mono_method_signature (cfg->method);
995
996         cinfo = cfg->arch.cinfo;
997
998         mono_arch_compute_omit_fp (cfg);
999
1000         /*
1001          * We use the ABI calling conventions for managed code as well.
1002          * Exception: valuetypes are never passed or returned in registers.
1003          */
1004
1005         if (cfg->arch.omit_fp) {
1006                 cfg->flags |= MONO_CFG_HAS_SPILLUP;
1007                 cfg->frame_reg = AMD64_RSP;
1008                 offset = 0;
1009         } else {
1010                 /* Locals are allocated backwards from %fp */
1011                 cfg->frame_reg = AMD64_RBP;
1012                 offset = 0;
1013         }
1014
1015         if (cfg->method->save_lmf) {
1016                 /* Reserve stack space for saving LMF */
1017                 /* mono_arch_find_jit_info () expects to find the LMF at a fixed offset */
1018                 g_assert (offset == 0);
1019                 if (cfg->arch.omit_fp) {
1020                         cfg->arch.lmf_offset = offset;
1021                         offset += sizeof (MonoLMF);
1022                 }
1023                 else {
1024                         offset += sizeof (MonoLMF);
1025                         cfg->arch.lmf_offset = -offset;
1026                 }
1027         } else {
1028                 /* Reserve space for caller saved registers */
1029                 for (i = 0; i < AMD64_NREG; ++i)
1030                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
1031                                 offset += sizeof (gpointer);
1032                         }
1033         }
1034
1035         if (sig->ret->type != MONO_TYPE_VOID) {
1036                 switch (cinfo->ret.storage) {
1037                 case ArgInIReg:
1038                 case ArgInFloatSSEReg:
1039                 case ArgInDoubleSSEReg:
1040                         if ((MONO_TYPE_ISSTRUCT (sig->ret) && !mono_class_from_mono_type (sig->ret)->enumtype) || (sig->ret->type == MONO_TYPE_TYPEDBYREF)) {
1041                                 /* The register is volatile */
1042                                 cfg->ret->opcode = OP_REGOFFSET;
1043                                 cfg->ret->inst_basereg = cfg->frame_reg;
1044                                 if (cfg->arch.omit_fp) {
1045                                         cfg->ret->inst_offset = offset;
1046                                         offset += 8;
1047                                 } else {
1048                                         offset += 8;
1049                                         cfg->ret->inst_offset = -offset;
1050                                 }
1051                         }
1052                         else {
1053                                 cfg->ret->opcode = OP_REGVAR;
1054                                 cfg->ret->inst_c0 = cinfo->ret.reg;
1055                         }
1056                         break;
1057                 case ArgValuetypeInReg:
1058                         /* Allocate a local to hold the result, the epilog will copy it to the correct place */
1059                         g_assert (!cfg->arch.omit_fp);
1060                         offset += 16;
1061                         cfg->ret->opcode = OP_REGOFFSET;
1062                         cfg->ret->inst_basereg = cfg->frame_reg;
1063                         cfg->ret->inst_offset = - offset;
1064                         break;
1065                 default:
1066                         g_assert_not_reached ();
1067                 }
1068                 cfg->ret->dreg = cfg->ret->inst_c0;
1069         }
1070
1071         /* Allocate locals */
1072         offsets = mono_allocate_stack_slots_full (cfg, cfg->arch.omit_fp ? FALSE: TRUE, &locals_stack_size, &locals_stack_align);
1073         if (locals_stack_align) {
1074                 offset += (locals_stack_align - 1);
1075                 offset &= ~(locals_stack_align - 1);
1076         }
1077         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1078                 if (offsets [i] != -1) {
1079                         MonoInst *inst = cfg->varinfo [i];
1080                         inst->opcode = OP_REGOFFSET;
1081                         inst->inst_basereg = cfg->frame_reg;
1082                         if (cfg->arch.omit_fp)
1083                                 inst->inst_offset = (offset + offsets [i]);
1084                         else
1085                                 inst->inst_offset = - (offset + offsets [i]);
1086                         //printf ("allocated local %d to ", i); mono_print_tree_nl (inst);
1087                 }
1088         }
1089         offset += locals_stack_size;
1090
1091         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) {
1092                 g_assert (!cfg->arch.omit_fp);
1093                 g_assert (cinfo->sig_cookie.storage == ArgOnStack);
1094                 cfg->sig_cookie = cinfo->sig_cookie.offset + ARGS_OFFSET;
1095         }
1096
1097         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
1098                 inst = cfg->args [i];
1099                 if (inst->opcode != OP_REGVAR) {
1100                         ArgInfo *ainfo = &cinfo->args [i];
1101                         gboolean inreg = TRUE;
1102                         MonoType *arg_type;
1103
1104                         if (sig->hasthis && (i == 0))
1105                                 arg_type = &mono_defaults.object_class->byval_arg;
1106                         else
1107                                 arg_type = sig->params [i - sig->hasthis];
1108
1109                         /* FIXME: Allocate volatile arguments to registers */
1110                         if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1111                                 inreg = FALSE;
1112
1113                         /* 
1114                          * Under AMD64, all registers used to pass arguments to functions
1115                          * are volatile across calls.
1116                          * FIXME: Optimize this.
1117                          */
1118                         if ((ainfo->storage == ArgInIReg) || (ainfo->storage == ArgInFloatSSEReg) || (ainfo->storage == ArgInDoubleSSEReg) || (ainfo->storage == ArgValuetypeInReg))
1119                                 inreg = FALSE;
1120
1121                         inst->opcode = OP_REGOFFSET;
1122
1123                         switch (ainfo->storage) {
1124                         case ArgInIReg:
1125                         case ArgInFloatSSEReg:
1126                         case ArgInDoubleSSEReg:
1127                                 inst->opcode = OP_REGVAR;
1128                                 inst->dreg = ainfo->reg;
1129                                 break;
1130                         case ArgOnStack:
1131                                 g_assert (!cfg->arch.omit_fp);
1132                                 inst->opcode = OP_REGOFFSET;
1133                                 inst->inst_basereg = cfg->frame_reg;
1134                                 inst->inst_offset = ainfo->offset + ARGS_OFFSET;
1135                                 break;
1136                         case ArgValuetypeInReg:
1137                                 break;
1138                         default:
1139                                 NOT_IMPLEMENTED;
1140                         }
1141
1142                         if (!inreg && (ainfo->storage != ArgOnStack)) {
1143                                 inst->opcode = OP_REGOFFSET;
1144                                 inst->inst_basereg = cfg->frame_reg;
1145                                 /* These arguments are saved to the stack in the prolog */
1146                                 offset = ALIGN_TO (offset, sizeof (gpointer));
1147                                 if (cfg->arch.omit_fp) {
1148                                         inst->inst_offset = offset;
1149                                         offset += (ainfo->storage == ArgValuetypeInReg) ? 2 * sizeof (gpointer) : sizeof (gpointer);
1150                                 } else {
1151                                         offset += (ainfo->storage == ArgValuetypeInReg) ? 2 * sizeof (gpointer) : sizeof (gpointer);
1152                                         inst->inst_offset = - offset;
1153                                 }
1154                         }
1155                 }
1156         }
1157
1158         cfg->stack_offset = offset;
1159 }
1160
1161 void
1162 mono_arch_create_vars (MonoCompile *cfg)
1163 {
1164         MonoMethodSignature *sig;
1165         CallInfo *cinfo;
1166
1167         sig = mono_method_signature (cfg->method);
1168
1169         if (!cfg->arch.cinfo)
1170                 cfg->arch.cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
1171         cinfo = cfg->arch.cinfo;
1172
1173         if (cinfo->ret.storage == ArgValuetypeInReg)
1174                 cfg->ret_var_is_local = TRUE;
1175 }
1176
1177 static void
1178 add_outarg_reg (MonoCompile *cfg, MonoCallInst *call, MonoInst *arg, ArgStorage storage, int reg, MonoInst *tree)
1179 {
1180         switch (storage) {
1181         case ArgInIReg:
1182                 arg->opcode = OP_OUTARG_REG;
1183                 arg->inst_left = tree;
1184                 arg->inst_call = call;
1185                 arg->backend.reg3 = reg;
1186                 break;
1187         case ArgInFloatSSEReg:
1188                 arg->opcode = OP_AMD64_OUTARG_XMMREG_R4;
1189                 arg->inst_left = tree;
1190                 arg->inst_call = call;
1191                 arg->backend.reg3 = reg;
1192                 break;
1193         case ArgInDoubleSSEReg:
1194                 arg->opcode = OP_AMD64_OUTARG_XMMREG_R8;
1195                 arg->inst_left = tree;
1196                 arg->inst_call = call;
1197                 arg->backend.reg3 = reg;
1198                 break;
1199         default:
1200                 g_assert_not_reached ();
1201         }
1202 }
1203
1204 /* Fixme: we need an alignment solution for enter_method and mono_arch_call_opcode,
1205  * currently alignment in mono_arch_call_opcode is computed without arch_get_argument_info 
1206  */
1207
1208 static int
1209 arg_storage_to_ldind (ArgStorage storage)
1210 {
1211         switch (storage) {
1212         case ArgInIReg:
1213                 return CEE_LDIND_I;
1214         case ArgInDoubleSSEReg:
1215                 return CEE_LDIND_R8;
1216         case ArgInFloatSSEReg:
1217                 return CEE_LDIND_R4;
1218         default:
1219                 g_assert_not_reached ();
1220         }
1221
1222         return -1;
1223 }
1224
1225 static void
1226 emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo)
1227 {
1228         MonoInst *arg;
1229         MonoMethodSignature *tmp_sig;
1230         MonoInst *sig_arg;
1231                         
1232         /* FIXME: Add support for signature tokens to AOT */
1233         cfg->disable_aot = TRUE;
1234
1235         g_assert (cinfo->sig_cookie.storage == ArgOnStack);
1236
1237         /*
1238          * mono_ArgIterator_Setup assumes the signature cookie is 
1239          * passed first and all the arguments which were before it are
1240          * passed on the stack after the signature. So compensate by 
1241          * passing a different signature.
1242          */
1243         tmp_sig = mono_metadata_signature_dup (call->signature);
1244         tmp_sig->param_count -= call->signature->sentinelpos;
1245         tmp_sig->sentinelpos = 0;
1246         memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*));
1247
1248         MONO_INST_NEW (cfg, sig_arg, OP_ICONST);
1249         sig_arg->inst_p0 = tmp_sig;
1250
1251         MONO_INST_NEW (cfg, arg, OP_OUTARG);
1252         arg->inst_left = sig_arg;
1253         arg->type = STACK_PTR;
1254         MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1255 }
1256
1257 /* 
1258  * take the arguments and generate the arch-specific
1259  * instructions to properly call the function in call.
1260  * This includes pushing, moving arguments to the right register
1261  * etc.
1262  * Issue: who does the spilling if needed, and when?
1263  */
1264 MonoCallInst*
1265 mono_arch_call_opcode (MonoCompile *cfg, MonoBasicBlock* bb, MonoCallInst *call, int is_virtual) {
1266         MonoInst *arg, *in;
1267         MonoMethodSignature *sig;
1268         int i, n, stack_size;
1269         CallInfo *cinfo;
1270         ArgInfo *ainfo;
1271
1272         stack_size = 0;
1273
1274         sig = call->signature;
1275         n = sig->param_count + sig->hasthis;
1276
1277         cinfo = get_call_info (cfg, cfg->mempool, sig, sig->pinvoke);
1278
1279         for (i = 0; i < n; ++i) {
1280                 ainfo = cinfo->args + i;
1281
1282                 if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) {
1283                         /* Emit the signature cookie just before the implicit arguments */
1284                         emit_sig_cookie (cfg, call, cinfo);
1285                 }
1286
1287                 if (is_virtual && i == 0) {
1288                         /* the argument will be attached to the call instruction */
1289                         in = call->args [i];
1290                 } else {
1291                         MONO_INST_NEW (cfg, arg, OP_OUTARG);
1292                         in = call->args [i];
1293                         arg->cil_code = in->cil_code;
1294                         arg->inst_left = in;
1295                         arg->type = in->type;
1296                         if (!cinfo->stack_usage)
1297                                 /* Keep the assignments to the arg registers in order if possible */
1298                                 MONO_INST_LIST_ADD_TAIL (&arg->node, &call->out_args);
1299                         else
1300                                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1301
1302                         if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
1303                                 guint32 align;
1304                                 guint32 size;
1305
1306                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_TYPEDBYREF) {
1307                                         size = sizeof (MonoTypedRef);
1308                                         align = sizeof (gpointer);
1309                                 }
1310                                 else
1311                                 if (sig->pinvoke)
1312                                         size = mono_type_native_stack_size (&in->klass->byval_arg, &align);
1313                                 else {
1314                                         /* 
1315                                          * Other backends use mini_type_stack_size (), but that
1316                                          * aligns the size to 8, which is larger than the size of
1317                                          * the source, leading to reads of invalid memory if the
1318                                          * source is at the end of address space.
1319                                          */
1320                                         size = mono_class_value_size (in->klass, &align);
1321                                 }
1322                                 if (ainfo->storage == ArgValuetypeInReg) {
1323                                         if (ainfo->pair_storage [1] == ArgNone) {
1324                                                 MonoInst *load;
1325
1326                                                 /* Simpler case */
1327
1328                                                 MONO_INST_NEW (cfg, load, arg_storage_to_ldind (ainfo->pair_storage [0]));
1329                                                 load->inst_left = in;
1330
1331                                                 add_outarg_reg (cfg, call, arg, ainfo->pair_storage [0], ainfo->pair_regs [0], load);
1332                                         }
1333                                         else {
1334                                                 /* Trees can't be shared so make a copy */
1335                                                 MonoInst *vtaddr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1336                                                 MonoInst *load, *load2, *offset_ins;
1337
1338                                                 /* Reg1 */
1339                                                 MONO_INST_NEW (cfg, load, CEE_LDIND_I);
1340                                                 load->ssa_op = MONO_SSA_LOAD;
1341                                                 load->inst_i0 = (cfg)->varinfo [vtaddr->inst_c0];
1342
1343                                                 NEW_ICONST (cfg, offset_ins, 0);
1344                                                 MONO_INST_NEW (cfg, load2, CEE_ADD);
1345                                                 load2->inst_left = load;
1346                                                 load2->inst_right = offset_ins;
1347
1348                                                 MONO_INST_NEW (cfg, load, arg_storage_to_ldind (ainfo->pair_storage [0]));
1349                                                 load->inst_left = load2;
1350
1351                                                 add_outarg_reg (cfg, call, arg, ainfo->pair_storage [0], ainfo->pair_regs [0], load);
1352
1353                                                 /* Reg2 */
1354                                                 MONO_INST_NEW (cfg, load, CEE_LDIND_I);
1355                                                 load->ssa_op = MONO_SSA_LOAD;
1356                                                 load->inst_i0 = (cfg)->varinfo [vtaddr->inst_c0];
1357
1358                                                 NEW_ICONST (cfg, offset_ins, 8);
1359                                                 MONO_INST_NEW (cfg, load2, CEE_ADD);
1360                                                 load2->inst_left = load;
1361                                                 load2->inst_right = offset_ins;
1362
1363                                                 MONO_INST_NEW (cfg, load, arg_storage_to_ldind (ainfo->pair_storage [1]));
1364                                                 load->inst_left = load2;
1365
1366                                                 MONO_INST_NEW (cfg, arg, OP_OUTARG);
1367                                                 arg->cil_code = in->cil_code;
1368                                                 arg->type = in->type;
1369                                                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1370
1371                                                 add_outarg_reg (cfg, call, arg, ainfo->pair_storage [1], ainfo->pair_regs [1], load);
1372
1373                                                 /* Prepend a copy inst */
1374                                                 MONO_INST_NEW (cfg, arg, CEE_STIND_I);
1375                                                 arg->cil_code = in->cil_code;
1376                                                 arg->ssa_op = MONO_SSA_STORE;
1377                                                 arg->inst_left = vtaddr;
1378                                                 arg->inst_right = in;
1379                                                 arg->type = in->type;
1380
1381                                                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1382                                         }
1383                                 }
1384                                 else {
1385                                         arg->opcode = OP_OUTARG_VT;
1386                                         arg->klass = in->klass;
1387                                         arg->backend.is_pinvoke = sig->pinvoke;
1388                                         arg->inst_imm = size;
1389                                 }
1390                         }
1391                         else {
1392                                 switch (ainfo->storage) {
1393                                 case ArgInIReg:
1394                                         add_outarg_reg (cfg, call, arg, ainfo->storage, ainfo->reg, in);
1395                                         break;
1396                                 case ArgInFloatSSEReg:
1397                                 case ArgInDoubleSSEReg:
1398                                         add_outarg_reg (cfg, call, arg, ainfo->storage, ainfo->reg, in);
1399                                         break;
1400                                 case ArgOnStack:
1401                                         arg->opcode = OP_OUTARG;
1402                                         if (!sig->params [i - sig->hasthis]->byref) {
1403                                                 if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4)
1404                                                         arg->opcode = OP_OUTARG_R4;
1405                                                 else
1406                                                         if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8)
1407                                                                 arg->opcode = OP_OUTARG_R8;
1408                                         }
1409                                         break;
1410                                 default:
1411                                         g_assert_not_reached ();
1412                                 }
1413                         }
1414                 }
1415         }
1416
1417         /* Handle the case where there are no implicit arguments */
1418         if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sig->sentinelpos)) {
1419                 emit_sig_cookie (cfg, call, cinfo);
1420         }
1421
1422         if (cinfo->need_stack_align) {
1423                 MONO_INST_NEW (cfg, arg, OP_AMD64_OUTARG_ALIGN_STACK);
1424                 MONO_INST_LIST_ADD (&arg->node, &call->out_args);
1425         }
1426
1427         if (cfg->method->save_lmf) {
1428                 MONO_INST_NEW (cfg, arg, OP_AMD64_SAVE_SP_TO_LMF);
1429                 MONO_INST_LIST_ADD_TAIL (&arg->node, &call->out_args);
1430         }
1431
1432         call->stack_usage = cinfo->stack_usage;
1433         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
1434         cfg->flags |= MONO_CFG_HAS_CALLS;
1435
1436         return call;
1437 }
1438
1439 #define EMIT_COND_BRANCH(ins,cond,sign) \
1440 if (ins->flags & MONO_INST_BRLABEL) { \
1441         if (ins->inst_i0->inst_c0) { \
1442                 x86_branch (code, cond, cfg->native_code + ins->inst_i0->inst_c0, sign); \
1443         } else { \
1444                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_LABEL, ins->inst_i0); \
1445                 if ((cfg->opt & MONO_OPT_BRANCH) && \
1446                     x86_is_imm8 (ins->inst_i0->inst_c1 - cpos)) \
1447                         x86_branch8 (code, cond, 0, sign); \
1448                 else \
1449                         x86_branch32 (code, cond, 0, sign); \
1450         } \
1451 } else { \
1452         if (ins->inst_true_bb->native_offset) { \
1453                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
1454         } else { \
1455                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
1456                 if ((cfg->opt & MONO_OPT_BRANCH) && \
1457                     x86_is_imm8 (ins->inst_true_bb->max_offset - cpos)) \
1458                         x86_branch8 (code, cond, 0, sign); \
1459                 else \
1460                         x86_branch32 (code, cond, 0, sign); \
1461         } \
1462 }
1463
1464 /* emit an exception if condition is fail */
1465 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
1466         do {                                                        \
1467                 MonoInst *tins = mono_branch_optimize_exception_target (cfg, bb, exc_name); \
1468                 if (tins == NULL) {                                                                             \
1469                         mono_add_patch_info (cfg, code - cfg->native_code,   \
1470                                         MONO_PATCH_INFO_EXC, exc_name);  \
1471                         x86_branch32 (code, cond, 0, signed);               \
1472                 } else {        \
1473                         EMIT_COND_BRANCH (tins, cond, signed);  \
1474                 }                       \
1475         } while (0); 
1476
1477 #define EMIT_FPCOMPARE(code) do { \
1478         amd64_fcompp (code); \
1479         amd64_fnstsw (code); \
1480 } while (0); 
1481
1482 #define EMIT_SSE2_FPFUNC(code, op, dreg, sreg1) do { \
1483     amd64_movsd_membase_reg (code, AMD64_RSP, -8, (sreg1)); \
1484         amd64_fld_membase (code, AMD64_RSP, -8, TRUE); \
1485         amd64_ ##op (code); \
1486         amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE); \
1487         amd64_movsd_reg_membase (code, (dreg), AMD64_RSP, -8); \
1488 } while (0);
1489
1490 static guint8*
1491 emit_call_body (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
1492 {
1493         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
1494
1495         /* 
1496          * FIXME: Add support for thunks
1497          */
1498         {
1499                 gboolean near_call = FALSE;
1500
1501                 /*
1502                  * Indirect calls are expensive so try to make a near call if possible.
1503                  * The caller memory is allocated by the code manager so it is 
1504                  * guaranteed to be at a 32 bit offset.
1505                  */
1506
1507                 if (patch_type != MONO_PATCH_INFO_ABS) {
1508                         /* The target is in memory allocated using the code manager */
1509                         near_call = TRUE;
1510
1511                         if ((patch_type == MONO_PATCH_INFO_METHOD) || (patch_type == MONO_PATCH_INFO_METHOD_JUMP)) {
1512                                 if (((MonoMethod*)data)->klass->image->assembly->aot_module)
1513                                         /* The callee might be an AOT method */
1514                                         near_call = FALSE;
1515                         }
1516
1517                         if (patch_type == MONO_PATCH_INFO_INTERNAL_METHOD) {
1518                                 /* 
1519                                  * The call might go directly to a native function without
1520                                  * the wrapper.
1521                                  */
1522                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (data);
1523                                 if (mi) {
1524                                         gconstpointer target = mono_icall_get_wrapper (mi);
1525                                         if ((((guint64)target) >> 32) != 0)
1526                                                 near_call = FALSE;
1527                                 }
1528                         }
1529                 }
1530                 else {
1531                         if (mono_find_class_init_trampoline_by_addr (data))
1532                                 near_call = TRUE;
1533                         else {
1534                                 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (data);
1535                                 if (info) {
1536                                         if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
1537                                                 strstr (cfg->method->name, info->name)) {
1538                                                 /* A call to the wrapped function */
1539                                                 if ((((guint64)data) >> 32) == 0)
1540                                                         near_call = TRUE;
1541                                         }
1542                                         else if (info->func == info->wrapper) {
1543                                                 /* No wrapper */
1544                                                 if ((((guint64)info->func) >> 32) == 0)
1545                                                         near_call = TRUE;
1546                                         }
1547                                         else {
1548                                                 /* See the comment in mono_codegen () */
1549                                                 if ((info->name [0] != 'v') || (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL))
1550                                                         near_call = TRUE;
1551                                         }
1552                                 }
1553                                 else if ((((guint64)data) >> 32) == 0)
1554                                         near_call = TRUE;
1555                         }
1556                 }
1557
1558                 if (cfg->method->dynamic)
1559                         /* These methods are allocated using malloc */
1560                         near_call = FALSE;
1561
1562                 if (cfg->compile_aot)
1563                         near_call = TRUE;
1564
1565 #ifdef MONO_ARCH_NOMAP32BIT
1566                 near_call = FALSE;
1567 #endif
1568
1569                 if (near_call) {
1570                         amd64_call_code (code, 0);
1571                 }
1572                 else {
1573                         amd64_set_reg_template (code, GP_SCRATCH_REG);
1574                         amd64_call_reg (code, GP_SCRATCH_REG);
1575                 }
1576         }
1577
1578         return code;
1579 }
1580
1581 static inline guint8*
1582 emit_call (MonoCompile *cfg, guint8 *code, guint32 patch_type, gconstpointer data)
1583 {
1584         mono_add_patch_info (cfg, code - cfg->native_code, patch_type, data);
1585
1586         return emit_call_body (cfg, code, patch_type, data);
1587 }
1588
1589 static inline int
1590 store_membase_imm_to_store_membase_reg (int opcode)
1591 {
1592         switch (opcode) {
1593         case OP_STORE_MEMBASE_IMM:
1594                 return OP_STORE_MEMBASE_REG;
1595         case OP_STOREI4_MEMBASE_IMM:
1596                 return OP_STOREI4_MEMBASE_REG;
1597         case OP_STOREI8_MEMBASE_IMM:
1598                 return OP_STOREI8_MEMBASE_REG;
1599         }
1600
1601         return -1;
1602 }
1603
1604 #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)))
1605
1606 /*
1607  * peephole_pass_1:
1608  *
1609  *   Perform peephole opts which should/can be performed before local regalloc
1610  */
1611 static void
1612 peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
1613 {
1614         MonoInst *ins, *n;
1615
1616         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (ins, n, &bb->ins_list, node) {
1617                 MonoInst *last_ins = mono_inst_list_prev (&ins->node, &bb->ins_list);
1618
1619                 switch (ins->opcode) {
1620                 case OP_ADD_IMM:
1621                 case OP_IADD_IMM:
1622                 case OP_LADD_IMM:
1623                         if ((ins->sreg1 < MONO_MAX_IREGS) && (ins->dreg >= MONO_MAX_IREGS) && (ins->inst_imm > 0)) {
1624                                 /* 
1625                                  * X86_LEA is like ADD, but doesn't have the
1626                                  * sreg1==dreg restriction. inst_imm > 0 is needed since LEA sign-extends 
1627                                  * its operand to 64 bit.
1628                                  */
1629                                 ins->opcode = OP_X86_LEA_MEMBASE;
1630                                 ins->inst_basereg = ins->sreg1;
1631                                 /* Fall through */
1632                         }
1633                         else
1634                                 break;
1635                 case CEE_XOR:
1636                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
1637                                 MonoInst *ins2;
1638
1639                                 /* 
1640                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
1641                                  * the latter has length 2-3 instead of 6 (reverse constant
1642                                  * propagation). These instruction sequences are very common
1643                                  * in the initlocals bblock.
1644                                  */
1645                                 for (ins2 = mono_inst_list_next (&ins->node, &bb->ins_list); ins2;
1646                                                 ins2 = mono_inst_list_next (&ins2->node, &bb->ins_list)) {
1647                                         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)) {
1648                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
1649                                                 ins2->sreg1 = ins->dreg;
1650                                         } 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)) {
1651                                                 /* Continue */
1652                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
1653                                                 NULLIFY_INS (ins2);
1654                                                 /* Continue */
1655                                         } else {
1656                                                 break;
1657                                         }
1658                                 }
1659                         }
1660                         break;
1661                 case OP_COMPARE_IMM:
1662                         /* OP_COMPARE_IMM (reg, 0) 
1663                          * --> 
1664                          * OP_AMD64_TEST_NULL (reg) 
1665                          */
1666                         if (!ins->inst_imm)
1667                                 ins->opcode = OP_AMD64_TEST_NULL;
1668                         break;
1669                 case OP_ICOMPARE_IMM:
1670                         if (!ins->inst_imm)
1671                                 ins->opcode = OP_X86_TEST_NULL;
1672                         break;
1673                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
1674                         /* 
1675                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1676                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
1677                          * -->
1678                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1679                          * OP_COMPARE_IMM reg, imm
1680                          *
1681                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
1682                          */
1683                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
1684                             ins->inst_basereg == last_ins->inst_destbasereg &&
1685                             ins->inst_offset == last_ins->inst_offset) {
1686                                         ins->opcode = OP_ICOMPARE_IMM;
1687                                         ins->sreg1 = last_ins->sreg1;
1688
1689                                         /* check if we can remove cmp reg,0 with test null */
1690                                         if (!ins->inst_imm)
1691                                                 ins->opcode = OP_X86_TEST_NULL;
1692                                 }
1693
1694                         break;
1695                 case OP_LOAD_MEMBASE:
1696                 case OP_LOADI4_MEMBASE:
1697                         /* 
1698                          * Note: if reg1 = reg2 the load op is removed
1699                          *
1700                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1701                          * OP_LOAD_MEMBASE offset(basereg), reg2
1702                          * -->
1703                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1704                          * OP_MOVE reg1, reg2
1705                          */
1706                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG 
1707                                          || last_ins->opcode == OP_STORE_MEMBASE_REG) &&
1708                             ins->inst_basereg == last_ins->inst_destbasereg &&
1709                             ins->inst_offset == last_ins->inst_offset) {
1710                                 if (ins->dreg == last_ins->sreg1) {
1711                                         MONO_DEL_INS (ins);
1712                                         continue;
1713                                 } else {
1714                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1715                                         ins->opcode = OP_MOVE;
1716                                         ins->sreg1 = last_ins->sreg1;
1717                                 }
1718
1719                         /* 
1720                          * Note: reg1 must be different from the basereg in the second load
1721                          * Note: if reg1 = reg2 is equal then second load is removed
1722                          *
1723                          * OP_LOAD_MEMBASE offset(basereg), reg1
1724                          * OP_LOAD_MEMBASE offset(basereg), reg2
1725                          * -->
1726                          * OP_LOAD_MEMBASE offset(basereg), reg1
1727                          * OP_MOVE reg1, reg2
1728                          */
1729                         } if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE
1730                                            || last_ins->opcode == OP_LOAD_MEMBASE) &&
1731                               ins->inst_basereg != last_ins->dreg &&
1732                               ins->inst_basereg == last_ins->inst_basereg &&
1733                               ins->inst_offset == last_ins->inst_offset) {
1734
1735                                 if (ins->dreg == last_ins->dreg) {
1736                                         MONO_DEL_INS (ins);
1737                                         continue;
1738                                 } else {
1739                                         ins->opcode = OP_MOVE;
1740                                         ins->sreg1 = last_ins->dreg;
1741                                 }
1742
1743                                 //g_assert_not_reached ();
1744
1745 #if 0
1746                         /* 
1747                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
1748                          * OP_LOAD_MEMBASE offset(basereg), reg
1749                          * -->
1750                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
1751                          * OP_ICONST reg, imm
1752                          */
1753                         } else if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM
1754                                                 || last_ins->opcode == OP_STORE_MEMBASE_IMM) &&
1755                                    ins->inst_basereg == last_ins->inst_destbasereg &&
1756                                    ins->inst_offset == last_ins->inst_offset) {
1757                                 //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1758                                 ins->opcode = OP_ICONST;
1759                                 ins->inst_c0 = last_ins->inst_imm;
1760                                 g_assert_not_reached (); // check this rule
1761 #endif
1762                         }
1763                         break;
1764                 case OP_LOADI1_MEMBASE:
1765                         /* 
1766                          * Note: if reg1 = reg2 the load op is removed
1767                          *
1768                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1769                          * OP_LOAD_MEMBASE offset(basereg), reg2
1770                          * -->
1771                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1772                          * OP_MOVE reg1, reg2
1773                          */
1774                         if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) &&
1775                                         ins->inst_basereg == last_ins->inst_destbasereg &&
1776                                         ins->inst_offset == last_ins->inst_offset) {
1777                                 if (ins->dreg == last_ins->sreg1) {
1778                                         MONO_DEL_INS (ins);
1779                                         continue;
1780                                 } else {
1781                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1782                                         ins->opcode = OP_MOVE;
1783                                         ins->sreg1 = last_ins->sreg1;
1784                                 }
1785                         }
1786                         break;
1787                 case OP_LOADI2_MEMBASE:
1788                         /* 
1789                          * Note: if reg1 = reg2 the load op is removed
1790                          *
1791                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1792                          * OP_LOAD_MEMBASE offset(basereg), reg2
1793                          * -->
1794                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1795                          * OP_MOVE reg1, reg2
1796                          */
1797                         if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) &&
1798                                         ins->inst_basereg == last_ins->inst_destbasereg &&
1799                                         ins->inst_offset == last_ins->inst_offset) {
1800                                 if (ins->dreg == last_ins->sreg1) {
1801                                         MONO_DEL_INS (ins);
1802                                         continue;
1803                                 } else {
1804                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1805                                         ins->opcode = OP_MOVE;
1806                                         ins->sreg1 = last_ins->sreg1;
1807                                 }
1808                         }
1809                         break;
1810                 case CEE_CONV_I4:
1811                 case CEE_CONV_U4:
1812                 case OP_MOVE:
1813                 case OP_FMOVE:
1814                         /*
1815                          * Removes:
1816                          *
1817                          * OP_MOVE reg, reg 
1818                          */
1819                         if (ins->dreg == ins->sreg1) {
1820                                 MONO_DEL_INS (ins);
1821                                 continue;
1822                         }
1823                         /* 
1824                          * Removes:
1825                          *
1826                          * OP_MOVE sreg, dreg 
1827                          * OP_MOVE dreg, sreg
1828                          */
1829                         if (last_ins && last_ins->opcode == OP_MOVE &&
1830                             ins->sreg1 == last_ins->dreg &&
1831                             ins->dreg == last_ins->sreg1) {
1832                                 MONO_DEL_INS (ins);
1833                                 continue;
1834                         }
1835                         break;
1836                 }
1837         }
1838 }
1839
1840 static void
1841 peephole_pass (MonoCompile *cfg, MonoBasicBlock *bb)
1842 {
1843         MonoInst *ins, *n;
1844
1845         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (ins, n, &bb->ins_list, node) {
1846                 MonoInst *last_ins = mono_inst_list_prev (&ins->node, &bb->ins_list);
1847
1848                 switch (ins->opcode) {
1849                 case OP_ICONST:
1850                 case OP_I8CONST: {
1851                         MonoInst *next;
1852
1853                         /* reg = 0 -> XOR (reg, reg) */
1854                         /* XOR sets cflags on x86, so we cant do it always */
1855                         next = mono_inst_list_next (&ins->node, &bb->ins_list);
1856                         if (ins->inst_c0 == 0 && (!next ||
1857                                         (next && INST_IGNORES_CFLAGS (next->opcode)))) {
1858                                 ins->opcode = OP_LXOR;
1859                                 ins->sreg1 = ins->dreg;
1860                                 ins->sreg2 = ins->dreg;
1861                                 /* Fall through */
1862                         } else {
1863                                 break;
1864                         }
1865                 }
1866                 case CEE_XOR:
1867                 case OP_LXOR:
1868                         /*
1869                          * Use IXOR to avoid a rex prefix if possible. The cpu will sign extend the 
1870                          * 0 result into 64 bits.
1871                          */
1872                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
1873                                 ins->opcode = OP_IXOR;
1874                         }
1875                         /* Fall through */
1876                 case OP_IXOR:
1877                         if ((ins->sreg1 == ins->sreg2) && (ins->sreg1 == ins->dreg)) {
1878                                 MonoInst *ins2;
1879
1880                                 /* 
1881                                  * Replace STORE_MEMBASE_IMM 0 with STORE_MEMBASE_REG since 
1882                                  * the latter has length 2-3 instead of 6 (reverse constant
1883                                  * propagation). These instruction sequences are very common
1884                                  * in the initlocals bblock.
1885                                  */
1886                                 for (ins2 = mono_inst_list_next (&ins->node, &bb->ins_list); ins2;
1887                                                 ins2 = mono_inst_list_next (&ins2->node, &bb->ins_list)) {
1888                                         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)) {
1889                                                 ins2->opcode = store_membase_imm_to_store_membase_reg (ins2->opcode);
1890                                                 ins2->sreg1 = ins->dreg;
1891                                         } 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)) {
1892                                                 /* Continue */
1893                                         } else if (((ins2->opcode == OP_ICONST) || (ins2->opcode == OP_I8CONST)) && (ins2->dreg == ins->dreg) && (ins2->inst_c0 == 0)) {
1894                                                 NULLIFY_INS (ins2);
1895                                                 /* Continue */
1896                                         } else {
1897                                                 break;
1898                                         }
1899                                 }
1900                         }
1901                         break;
1902                 case OP_IADD_IMM:
1903                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
1904                                 ins->opcode = OP_X86_INC_REG;
1905                         break;
1906                 case OP_ISUB_IMM:
1907                         if ((ins->inst_imm == 1) && (ins->dreg == ins->sreg1))
1908                                 ins->opcode = OP_X86_DEC_REG;
1909                         break;
1910                 case OP_MUL_IMM: 
1911                         /* remove unnecessary multiplication with 1 */
1912                         if (ins->inst_imm == 1) {
1913                                 if (ins->dreg != ins->sreg1) {
1914                                         ins->opcode = OP_MOVE;
1915                                 } else {
1916                                         MONO_DEL_INS (ins);
1917                                         continue;
1918                                 }
1919                         }
1920                         break;
1921                 case OP_COMPARE_IMM:
1922                         /* OP_COMPARE_IMM (reg, 0) 
1923                          * --> 
1924                          * OP_AMD64_TEST_NULL (reg) 
1925                          */
1926                         if (!ins->inst_imm)
1927                                 ins->opcode = OP_AMD64_TEST_NULL;
1928                         break;
1929                 case OP_ICOMPARE_IMM:
1930                         if (!ins->inst_imm)
1931                                 ins->opcode = OP_X86_TEST_NULL;
1932                         break;
1933                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
1934                         /* 
1935                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1936                          * OP_X86_COMPARE_MEMBASE_IMM offset(basereg), imm
1937                          * -->
1938                          * OP_STORE_MEMBASE_REG reg, offset(basereg)
1939                          * OP_COMPARE_IMM reg, imm
1940                          *
1941                          * Note: if imm = 0 then OP_COMPARE_IMM replaced with OP_X86_TEST_NULL
1942                          */
1943                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG) &&
1944                             ins->inst_basereg == last_ins->inst_destbasereg &&
1945                             ins->inst_offset == last_ins->inst_offset) {
1946                                         ins->opcode = OP_ICOMPARE_IMM;
1947                                         ins->sreg1 = last_ins->sreg1;
1948
1949                                         /* check if we can remove cmp reg,0 with test null */
1950                                         if (!ins->inst_imm)
1951                                                 ins->opcode = OP_X86_TEST_NULL;
1952                                 }
1953
1954                         break;
1955                 case OP_LOAD_MEMBASE:
1956                 case OP_LOADI4_MEMBASE:
1957                         /* 
1958                          * Note: if reg1 = reg2 the load op is removed
1959                          *
1960                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
1961                          * OP_LOAD_MEMBASE offset(basereg), reg2
1962                          * -->
1963                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
1964                          * OP_MOVE reg1, reg2
1965                          */
1966                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG 
1967                                          || last_ins->opcode == OP_STORE_MEMBASE_REG) &&
1968                             ins->inst_basereg == last_ins->inst_destbasereg &&
1969                             ins->inst_offset == last_ins->inst_offset) {
1970                                 if (ins->dreg == last_ins->sreg1) {
1971                                         MONO_DEL_INS (ins);
1972                                         continue;
1973                                 } else {
1974                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
1975                                         ins->opcode = OP_MOVE;
1976                                         ins->sreg1 = last_ins->sreg1;
1977                                 }
1978
1979                         /* 
1980                          * Note: reg1 must be different from the basereg in the second load
1981                          * Note: if reg1 = reg2 is equal then second load is removed
1982                          *
1983                          * OP_LOAD_MEMBASE offset(basereg), reg1
1984                          * OP_LOAD_MEMBASE offset(basereg), reg2
1985                          * -->
1986                          * OP_LOAD_MEMBASE offset(basereg), reg1
1987                          * OP_MOVE reg1, reg2
1988                          */
1989                         } if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE
1990                                            || last_ins->opcode == OP_LOAD_MEMBASE) &&
1991                               ins->inst_basereg != last_ins->dreg &&
1992                               ins->inst_basereg == last_ins->inst_basereg &&
1993                               ins->inst_offset == last_ins->inst_offset) {
1994
1995                                 if (ins->dreg == last_ins->dreg) {
1996                                         MONO_DEL_INS (ins);
1997                                         continue;
1998                                 } else {
1999                                         ins->opcode = OP_MOVE;
2000                                         ins->sreg1 = last_ins->dreg;
2001                                 }
2002
2003                                 //g_assert_not_reached ();
2004
2005 #if 0
2006                         /* 
2007                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
2008                          * OP_LOAD_MEMBASE offset(basereg), reg
2009                          * -->
2010                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
2011                          * OP_ICONST reg, imm
2012                          */
2013                         } else if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM
2014                                                 || last_ins->opcode == OP_STORE_MEMBASE_IMM) &&
2015                                    ins->inst_basereg == last_ins->inst_destbasereg &&
2016                                    ins->inst_offset == last_ins->inst_offset) {
2017                                 //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
2018                                 ins->opcode = OP_ICONST;
2019                                 ins->inst_c0 = last_ins->inst_imm;
2020                                 g_assert_not_reached (); // check this rule
2021 #endif
2022                         }
2023                         break;
2024                 case OP_LOADI1_MEMBASE:
2025                 case OP_LOADU1_MEMBASE:
2026                         /* 
2027                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
2028                          * OP_LOAD_MEMBASE offset(basereg), reg2
2029                          * -->
2030                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
2031                          * CONV_I1/U1 reg1, reg2
2032                          */
2033                         if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) &&
2034                                         ins->inst_basereg == last_ins->inst_destbasereg &&
2035                                         ins->inst_offset == last_ins->inst_offset) {
2036                                 ins->opcode = (ins->opcode == OP_LOADI1_MEMBASE) ? CEE_CONV_I1 : CEE_CONV_U1;
2037                                 ins->sreg1 = last_ins->sreg1;
2038                         }
2039                         break;
2040                 case OP_LOADI2_MEMBASE:
2041                 case OP_LOADU2_MEMBASE:
2042                         /* 
2043                          * OP_STORE_MEMBASE_REG reg1, offset(basereg) 
2044                          * OP_LOAD_MEMBASE offset(basereg), reg2
2045                          * -->
2046                          * OP_STORE_MEMBASE_REG reg1, offset(basereg)
2047                          * CONV_I2/U2 reg1, reg2
2048                          */
2049                         if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) &&
2050                                         ins->inst_basereg == last_ins->inst_destbasereg &&
2051                                         ins->inst_offset == last_ins->inst_offset) {
2052                                 ins->opcode = (ins->opcode == OP_LOADI2_MEMBASE) ? CEE_CONV_I2 : CEE_CONV_U2;
2053                                 ins->sreg1 = last_ins->sreg1;
2054                         }
2055                         break;
2056                 case CEE_CONV_I4:
2057                 case CEE_CONV_U4:
2058                 case OP_MOVE:
2059                 case OP_FMOVE:
2060                         /*
2061                          * Removes:
2062                          *
2063                          * OP_MOVE reg, reg 
2064                          */
2065                         if (ins->dreg == ins->sreg1) {
2066                                 MONO_DEL_INS (ins);
2067                                 continue;
2068                         }
2069                         /* 
2070                          * Removes:
2071                          *
2072                          * OP_MOVE sreg, dreg 
2073                          * OP_MOVE dreg, sreg
2074                          */
2075                         if (last_ins && last_ins->opcode == OP_MOVE &&
2076                                         ins->sreg1 == last_ins->dreg &&
2077                                         ins->dreg == last_ins->sreg1) {
2078                                 MONO_DEL_INS (ins);
2079                                 continue;
2080                         }
2081                         break;
2082                 }
2083         }
2084 }
2085
2086 #define NEW_INS(cfg,ins,dest,op) do {                                   \
2087                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
2088                 (dest)->opcode = (op);  \
2089                 MONO_INST_LIST_ADD_TAIL (&(dest)->node, &(ins)->node); \
2090         } while (0)
2091
2092 /*
2093  * mono_arch_lowering_pass:
2094  *
2095  *  Converts complex opcodes into simpler ones so that each IR instruction
2096  * corresponds to one machine instruction.
2097  */
2098 static void
2099 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
2100 {
2101         MonoInst *ins, *n, *temp;
2102
2103         if (bb->max_vreg > cfg->rs->next_vreg)
2104                 cfg->rs->next_vreg = bb->max_vreg;
2105
2106         /*
2107          * FIXME: Need to add more instructions, but the current machine 
2108          * description can't model some parts of the composite instructions like
2109          * cdq.
2110          */
2111         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (ins, n, &bb->ins_list, node) {
2112                 switch (ins->opcode) {
2113                 case OP_DIV_IMM:
2114                 case OP_REM_IMM:
2115                 case OP_IDIV_IMM:
2116                 case OP_IREM_IMM:
2117                         NEW_INS (cfg, ins, temp, OP_ICONST);
2118                         temp->inst_c0 = ins->inst_imm;
2119                         temp->dreg = mono_regstate_next_int (cfg->rs);
2120                         switch (ins->opcode) {
2121                         case OP_DIV_IMM:
2122                                 ins->opcode = OP_LDIV;
2123                                 break;
2124                         case OP_REM_IMM:
2125                                 ins->opcode = OP_LREM;
2126                                 break;
2127                         case OP_IDIV_IMM:
2128                                 ins->opcode = OP_IDIV;
2129                                 break;
2130                         case OP_IREM_IMM:
2131                                 ins->opcode = OP_IREM;
2132                                 break;
2133                         }
2134                         ins->sreg2 = temp->dreg;
2135                         break;
2136                 case OP_COMPARE_IMM:
2137                         if (!amd64_is_imm32 (ins->inst_imm)) {
2138                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
2139                                 temp->inst_c0 = ins->inst_imm;
2140                                 temp->dreg = mono_regstate_next_int (cfg->rs);
2141                                 ins->opcode = OP_COMPARE;
2142                                 ins->sreg2 = temp->dreg;
2143                         }
2144                         break;
2145                 case OP_LOAD_MEMBASE:
2146                 case OP_LOADI8_MEMBASE:
2147                         if (!amd64_is_imm32 (ins->inst_offset)) {
2148                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
2149                                 temp->inst_c0 = ins->inst_offset;
2150                                 temp->dreg = mono_regstate_next_int (cfg->rs);
2151                                 ins->opcode = OP_AMD64_LOADI8_MEMINDEX;
2152                                 ins->inst_indexreg = temp->dreg;
2153                         }
2154                         break;
2155                 case OP_STORE_MEMBASE_IMM:
2156                 case OP_STOREI8_MEMBASE_IMM:
2157                         if (!amd64_is_imm32 (ins->inst_imm)) {
2158                                 NEW_INS (cfg, ins, temp, OP_I8CONST);
2159                                 temp->inst_c0 = ins->inst_imm;
2160                                 temp->dreg = mono_regstate_next_int (cfg->rs);
2161                                 ins->opcode = OP_STOREI8_MEMBASE_REG;
2162                                 ins->sreg1 = temp->dreg;
2163                         }
2164                         break;
2165                 default:
2166                         break;
2167                 }
2168         }
2169
2170         bb->max_vreg = cfg->rs->next_vreg;
2171 }
2172
2173 static const int 
2174 branch_cc_table [] = {
2175         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
2176         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
2177         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
2178 };
2179
2180 /* Maps CMP_... constants to X86_CC_... constants */
2181 static const int
2182 cc_table [] = {
2183         X86_CC_EQ, X86_CC_NE, X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT,
2184         X86_CC_LE, X86_CC_GE, X86_CC_LT, X86_CC_GT
2185 };
2186
2187 static const int
2188 cc_signed_table [] = {
2189         TRUE, TRUE, TRUE, TRUE, TRUE, TRUE,
2190         FALSE, FALSE, FALSE, FALSE
2191 };
2192
2193 /*#include "cprop.c"*/
2194
2195 /*
2196  * Local register allocation.
2197  * We first scan the list of instructions and we save the liveness info of
2198  * each register (when the register is first used, when it's value is set etc.).
2199  * We also reverse the list of instructions (in the InstList list) because assigning
2200  * registers backwards allows for more tricks to be used.
2201  */
2202 void
2203 mono_arch_local_regalloc (MonoCompile *cfg, MonoBasicBlock *bb)
2204 {
2205         if (MONO_INST_LIST_EMPTY (&bb->ins_list))
2206                 return;
2207
2208         mono_arch_lowering_pass (cfg, bb);
2209
2210         if (cfg->opt & MONO_OPT_PEEPHOLE)
2211                 peephole_pass_1 (cfg, bb);
2212
2213         mono_local_regalloc (cfg, bb);
2214 }
2215
2216 static unsigned char*
2217 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed)
2218 {
2219         if (use_sse2) {
2220                 amd64_sse_cvttsd2si_reg_reg (code, dreg, sreg);
2221         }
2222         else {
2223                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
2224                 x86_fnstcw_membase(code, AMD64_RSP, 0);
2225                 amd64_mov_reg_membase (code, dreg, AMD64_RSP, 0, 2);
2226                 amd64_alu_reg_imm (code, X86_OR, dreg, 0xc00);
2227                 amd64_mov_membase_reg (code, AMD64_RSP, 2, dreg, 2);
2228                 amd64_fldcw_membase (code, AMD64_RSP, 2);
2229                 amd64_push_reg (code, AMD64_RAX); // SP = SP - 8
2230                 amd64_fist_pop_membase (code, AMD64_RSP, 0, size == 8);
2231                 amd64_pop_reg (code, dreg);
2232                 amd64_fldcw_membase (code, AMD64_RSP, 0);
2233                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
2234         }
2235
2236         if (size == 1)
2237                 amd64_widen_reg (code, dreg, dreg, is_signed, FALSE);
2238         else if (size == 2)
2239                 amd64_widen_reg (code, dreg, dreg, is_signed, TRUE);
2240         return code;
2241 }
2242
2243 static unsigned char*
2244 mono_emit_stack_alloc (guchar *code, MonoInst* tree)
2245 {
2246         int sreg = tree->sreg1;
2247         int need_touch = FALSE;
2248
2249 #if defined(PLATFORM_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
2250         if (!tree->flags & MONO_INST_INIT)
2251                 need_touch = TRUE;
2252 #endif
2253
2254         if (need_touch) {
2255                 guint8* br[5];
2256
2257                 /*
2258                  * Under Windows:
2259                  * If requested stack size is larger than one page,
2260                  * perform stack-touch operation
2261                  */
2262                 /*
2263                  * Generate stack probe code.
2264                  * Under Windows, it is necessary to allocate one page at a time,
2265                  * "touching" stack after each successful sub-allocation. This is
2266                  * because of the way stack growth is implemented - there is a
2267                  * guard page before the lowest stack page that is currently commited.
2268                  * Stack normally grows sequentially so OS traps access to the
2269                  * guard page and commits more pages when needed.
2270                  */
2271                 amd64_test_reg_imm (code, sreg, ~0xFFF);
2272                 br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
2273
2274                 br[2] = code; /* loop */
2275                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
2276                 amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
2277                 amd64_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
2278                 amd64_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
2279                 br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
2280                 amd64_patch (br[3], br[2]);
2281                 amd64_test_reg_reg (code, sreg, sreg);
2282                 br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
2283                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
2284
2285                 br[1] = code; x86_jump8 (code, 0);
2286
2287                 amd64_patch (br[0], code);
2288                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, sreg);
2289                 amd64_patch (br[1], code);
2290                 amd64_patch (br[4], code);
2291         }
2292         else
2293                 amd64_alu_reg_reg (code, X86_SUB, AMD64_RSP, tree->sreg1);
2294
2295         if (tree->flags & MONO_INST_INIT) {
2296                 int offset = 0;
2297                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX) {
2298                         amd64_push_reg (code, AMD64_RAX);
2299                         offset += 8;
2300                 }
2301                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX) {
2302                         amd64_push_reg (code, AMD64_RCX);
2303                         offset += 8;
2304                 }
2305                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI) {
2306                         amd64_push_reg (code, AMD64_RDI);
2307                         offset += 8;
2308                 }
2309                 
2310                 amd64_shift_reg_imm (code, X86_SHR, sreg, 3);
2311                 if (sreg != AMD64_RCX)
2312                         amd64_mov_reg_reg (code, AMD64_RCX, sreg, 8);
2313                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
2314                                 
2315                 amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, offset);
2316                 amd64_cld (code);
2317                 amd64_prefix (code, X86_REP_PREFIX);
2318                 amd64_stosl (code);
2319                 
2320                 if (tree->dreg != AMD64_RDI && sreg != AMD64_RDI)
2321                         amd64_pop_reg (code, AMD64_RDI);
2322                 if (tree->dreg != AMD64_RCX && sreg != AMD64_RCX)
2323                         amd64_pop_reg (code, AMD64_RCX);
2324                 if (tree->dreg != AMD64_RAX && sreg != AMD64_RAX)
2325                         amd64_pop_reg (code, AMD64_RAX);
2326         }
2327         return code;
2328 }
2329
2330 static guint8*
2331 emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
2332 {
2333         CallInfo *cinfo;
2334         guint32 quad;
2335
2336         /* Move return value to the target register */
2337         /* FIXME: do this in the local reg allocator */
2338         switch (ins->opcode) {
2339         case CEE_CALL:
2340         case OP_CALL_REG:
2341         case OP_CALL_MEMBASE:
2342         case OP_LCALL:
2343         case OP_LCALL_REG:
2344         case OP_LCALL_MEMBASE:
2345                 g_assert (ins->dreg == AMD64_RAX);
2346                 break;
2347         case OP_FCALL:
2348         case OP_FCALL_REG:
2349         case OP_FCALL_MEMBASE:
2350                 if (((MonoCallInst*)ins)->signature->ret->type == MONO_TYPE_R4) {
2351                         if (use_sse2)
2352                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, AMD64_XMM0);
2353                         else {
2354                                 /* FIXME: optimize this */
2355                                 amd64_movss_membase_reg (code, AMD64_RSP, -8, AMD64_XMM0);
2356                                 amd64_fld_membase (code, AMD64_RSP, -8, FALSE);
2357                         }
2358                 }
2359                 else {
2360                         if (use_sse2) {
2361                                 if (ins->dreg != AMD64_XMM0)
2362                                         amd64_sse_movsd_reg_reg (code, ins->dreg, AMD64_XMM0);
2363                         }
2364                         else {
2365                                 /* FIXME: optimize this */
2366                                 amd64_movsd_membase_reg (code, AMD64_RSP, -8, AMD64_XMM0);
2367                                 amd64_fld_membase (code, AMD64_RSP, -8, TRUE);
2368                         }
2369                 }
2370                 break;
2371         case OP_VCALL:
2372         case OP_VCALL_REG:
2373         case OP_VCALL_MEMBASE:
2374                 cinfo = get_call_info (cfg, cfg->mempool, ((MonoCallInst*)ins)->signature, FALSE);
2375                 if (cinfo->ret.storage == ArgValuetypeInReg) {
2376                         /* Pop the destination address from the stack */
2377                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
2378                         amd64_pop_reg (code, AMD64_RCX);
2379                         
2380                         for (quad = 0; quad < 2; quad ++) {
2381                                 switch (cinfo->ret.pair_storage [quad]) {
2382                                 case ArgInIReg:
2383                                         amd64_mov_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad], 8);
2384                                         break;
2385                                 case ArgInFloatSSEReg:
2386                                         amd64_movss_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
2387                                         break;
2388                                 case ArgInDoubleSSEReg:
2389                                         amd64_movsd_membase_reg (code, AMD64_RCX, (quad * 8), cinfo->ret.pair_regs [quad]);
2390                                         break;
2391                                 case ArgNone:
2392                                         break;
2393                                 default:
2394                                         NOT_IMPLEMENTED;
2395                                 }
2396                         }
2397                 }
2398                 break;
2399         }
2400
2401         return code;
2402 }
2403
2404 /*
2405  * emit_tls_get:
2406  * @code: buffer to store code to
2407  * @dreg: hard register where to place the result
2408  * @tls_offset: offset info
2409  *
2410  * emit_tls_get emits in @code the native code that puts in the dreg register
2411  * the item in the thread local storage identified by tls_offset.
2412  *
2413  * Returns: a pointer to the end of the stored code
2414  */
2415 static guint8*
2416 emit_tls_get (guint8* code, int dreg, int tls_offset)
2417 {
2418         if (optimize_for_xen) {
2419                 x86_prefix (code, X86_FS_PREFIX);
2420                 amd64_mov_reg_mem (code, dreg, 0, 8);
2421                 amd64_mov_reg_membase (code, dreg, dreg, tls_offset, 8);
2422         } else {
2423                 x86_prefix (code, X86_FS_PREFIX);
2424                 amd64_mov_reg_mem (code, dreg, tls_offset, 8);
2425         }
2426         return code;
2427 }
2428
2429 /*
2430  * emit_load_volatile_arguments:
2431  *
2432  *  Load volatile arguments from the stack to the original input registers.
2433  * Required before a tail call.
2434  */
2435 static guint8*
2436 emit_load_volatile_arguments (MonoCompile *cfg, guint8 *code)
2437 {
2438         MonoMethod *method = cfg->method;
2439         MonoMethodSignature *sig;
2440         MonoInst *inst;
2441         CallInfo *cinfo;
2442         guint32 i;
2443
2444         /* FIXME: Generate intermediate code instead */
2445
2446         sig = mono_method_signature (method);
2447
2448         cinfo = cfg->arch.cinfo;
2449         
2450         /* This is the opposite of the code in emit_prolog */
2451
2452         if (sig->ret->type != MONO_TYPE_VOID) {
2453                 if ((cinfo->ret.storage == ArgInIReg) && (cfg->ret->opcode != OP_REGVAR)) {
2454                         amd64_mov_reg_membase (code, cinfo->ret.reg, cfg->ret->inst_basereg, cfg->ret->inst_offset, 8);
2455                 }
2456         }
2457
2458         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2459                 ArgInfo *ainfo = cinfo->args + i;
2460                 MonoType *arg_type;
2461                 inst = cfg->args [i];
2462
2463                 if (sig->hasthis && (i == 0))
2464                         arg_type = &mono_defaults.object_class->byval_arg;
2465                 else
2466                         arg_type = sig->params [i - sig->hasthis];
2467
2468                 if (inst->opcode != OP_REGVAR) {
2469                         switch (ainfo->storage) {
2470                         case ArgInIReg: {
2471                                 guint32 size = 8;
2472
2473                                 /* FIXME: I1 etc */
2474                                 amd64_mov_reg_membase (code, ainfo->reg, inst->inst_basereg, inst->inst_offset, size);
2475                                 break;
2476                         }
2477                         case ArgInFloatSSEReg:
2478                                 amd64_movss_reg_membase (code, ainfo->reg, inst->inst_basereg, inst->inst_offset);
2479                                 break;
2480                         case ArgInDoubleSSEReg:
2481                                 amd64_movsd_reg_membase (code, ainfo->reg, inst->inst_basereg, inst->inst_offset);
2482                                 break;
2483                         default:
2484                                 break;
2485                         }
2486                 }
2487                 else {
2488                         g_assert (ainfo->storage == ArgInIReg);
2489
2490                         amd64_mov_reg_reg (code, ainfo->reg, inst->dreg, 8);
2491                 }
2492         }
2493
2494         return code;
2495 }
2496
2497 #define REAL_PRINT_REG(text,reg) \
2498 mono_assert (reg >= 0); \
2499 amd64_push_reg (code, AMD64_RAX); \
2500 amd64_push_reg (code, AMD64_RDX); \
2501 amd64_push_reg (code, AMD64_RCX); \
2502 amd64_push_reg (code, reg); \
2503 amd64_push_imm (code, reg); \
2504 amd64_push_imm (code, text " %d %p\n"); \
2505 amd64_mov_reg_imm (code, AMD64_RAX, printf); \
2506 amd64_call_reg (code, AMD64_RAX); \
2507 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 3*4); \
2508 amd64_pop_reg (code, AMD64_RCX); \
2509 amd64_pop_reg (code, AMD64_RDX); \
2510 amd64_pop_reg (code, AMD64_RAX);
2511
2512 /* benchmark and set based on cpu */
2513 #define LOOP_ALIGNMENT 8
2514 #define bb_is_loop_start(bb) ((bb)->loop_body_start && (bb)->nesting)
2515
2516 void
2517 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
2518 {
2519         MonoInst *ins;
2520         MonoCallInst *call;
2521         guint offset;
2522         guint8 *code = cfg->native_code + cfg->code_len;
2523         guint last_offset = 0;
2524         int max_len, cpos;
2525
2526         if (cfg->opt & MONO_OPT_PEEPHOLE)
2527                 peephole_pass (cfg, bb);
2528
2529         if (cfg->opt & MONO_OPT_LOOP) {
2530                 int pad, align = LOOP_ALIGNMENT;
2531                 /* set alignment depending on cpu */
2532                 if (bb_is_loop_start (bb) && (pad = (cfg->code_len & (align - 1)))) {
2533                         pad = align - pad;
2534                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
2535                         amd64_padding (code, pad);
2536                         cfg->code_len += pad;
2537                         bb->native_offset = cfg->code_len;
2538                 }
2539         }
2540
2541         if (cfg->verbose_level > 2)
2542                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
2543
2544         cpos = bb->max_offset;
2545
2546         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
2547                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
2548                 g_assert (!cfg->compile_aot);
2549                 cpos += 6;
2550
2551                 cov->data [bb->dfn].cil_code = bb->cil_code;
2552                 amd64_mov_reg_imm (code, AMD64_R11, (guint64)&cov->data [bb->dfn].count);
2553                 /* this is not thread save, but good enough */
2554                 amd64_inc_membase (code, AMD64_R11, 0);
2555         }
2556
2557         offset = code - cfg->native_code;
2558
2559         mono_debug_open_block (cfg, bb, offset);
2560
2561         MONO_BB_FOR_EACH_INS (bb, ins) {
2562                 offset = code - cfg->native_code;
2563
2564                 max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
2565
2566                 if (G_UNLIKELY (offset > (cfg->code_size - max_len - 16))) {
2567                         cfg->code_size *= 2;
2568                         cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
2569                         code = cfg->native_code + offset;
2570                         mono_jit_stats.code_reallocs++;
2571                 }
2572
2573                 if (cfg->debug_info)
2574                         mono_debug_record_line_number (cfg, ins, offset);
2575
2576                 switch (ins->opcode) {
2577                 case OP_BIGMUL:
2578                         amd64_mul_reg (code, ins->sreg2, TRUE);
2579                         break;
2580                 case OP_BIGMUL_UN:
2581                         amd64_mul_reg (code, ins->sreg2, FALSE);
2582                         break;
2583                 case OP_X86_SETEQ_MEMBASE:
2584                         amd64_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
2585                         break;
2586                 case OP_STOREI1_MEMBASE_IMM:
2587                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
2588                         break;
2589                 case OP_STOREI2_MEMBASE_IMM:
2590                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
2591                         break;
2592                 case OP_STOREI4_MEMBASE_IMM:
2593                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
2594                         break;
2595                 case OP_STOREI1_MEMBASE_REG:
2596                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
2597                         break;
2598                 case OP_STOREI2_MEMBASE_REG:
2599                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
2600                         break;
2601                 case OP_STORE_MEMBASE_REG:
2602                 case OP_STOREI8_MEMBASE_REG:
2603                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 8);
2604                         break;
2605                 case OP_STOREI4_MEMBASE_REG:
2606                         amd64_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
2607                         break;
2608                 case OP_STORE_MEMBASE_IMM:
2609                 case OP_STOREI8_MEMBASE_IMM:
2610                         g_assert (amd64_is_imm32 (ins->inst_imm));
2611                         amd64_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 8);
2612                         break;
2613                 case OP_LOADU4_MEM:
2614                         amd64_mov_reg_imm (code, ins->dreg, ins->inst_p0);
2615                         amd64_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
2616                         break;
2617                 case OP_LOAD_MEMBASE:
2618                 case OP_LOADI8_MEMBASE:
2619                         g_assert (amd64_is_imm32 (ins->inst_offset));
2620                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, sizeof (gpointer));
2621                         break;
2622                 case OP_LOADI4_MEMBASE:
2623                         amd64_movsxd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
2624                         break;
2625                 case OP_LOADU4_MEMBASE:
2626                         amd64_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
2627                         break;
2628                 case OP_LOADU1_MEMBASE:
2629                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE);
2630                         break;
2631                 case OP_LOADI1_MEMBASE:
2632                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
2633                         break;
2634                 case OP_LOADU2_MEMBASE:
2635                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE);
2636                         break;
2637                 case OP_LOADI2_MEMBASE:
2638                         amd64_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
2639                         break;
2640                 case OP_AMD64_LOADI8_MEMINDEX:
2641                         amd64_mov_reg_memindex_size (code, ins->dreg, ins->inst_basereg, 0, ins->inst_indexreg, 0, 8);
2642                         break;
2643                 case CEE_CONV_I1:
2644                 case OP_SEXT_I1:
2645                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
2646                         break;
2647                 case CEE_CONV_I2:
2648                 case OP_SEXT_I2:
2649                         amd64_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
2650                         break;
2651                 case CEE_CONV_U1:
2652                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
2653                         break;
2654                 case CEE_CONV_U2:
2655                         amd64_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
2656                         break;
2657                 case CEE_CONV_U8:
2658                 case CEE_CONV_U:
2659                         /* Clean out the upper word */
2660                         amd64_mov_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
2661                         break;
2662                 case CEE_CONV_I8:
2663                 case CEE_CONV_I:
2664                 case OP_SEXT_I4:
2665                         amd64_movsxd_reg_reg (code, ins->dreg, ins->sreg1);
2666                         break;                  
2667                 case OP_COMPARE:
2668                 case OP_LCOMPARE:
2669                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
2670                         break;
2671                 case OP_COMPARE_IMM:
2672                         g_assert (amd64_is_imm32 (ins->inst_imm));
2673                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
2674                         break;
2675                 case OP_X86_COMPARE_REG_MEMBASE:
2676                         amd64_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
2677                         break;
2678                 case OP_X86_TEST_NULL:
2679                         amd64_test_reg_reg_size (code, ins->sreg1, ins->sreg1, 4);
2680                         break;
2681                 case OP_AMD64_TEST_NULL:
2682                         amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
2683                         break;
2684                 case OP_X86_ADD_MEMBASE_IMM:
2685                         /* FIXME: Make a 64 version too */
2686                         amd64_alu_membase_imm_size (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2687                         break;
2688                 case OP_X86_ADD_MEMBASE:
2689                         amd64_alu_reg_membase_size (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2690                         break;
2691                 case OP_X86_SUB_MEMBASE_IMM:
2692                         g_assert (amd64_is_imm32 (ins->inst_imm));
2693                         amd64_alu_membase_imm_size (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2694                         break;
2695                 case OP_X86_SUB_MEMBASE:
2696                         amd64_alu_reg_membase_size (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2697                         break;
2698                 case OP_X86_INC_MEMBASE:
2699                         amd64_inc_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
2700                         break;
2701                 case OP_X86_INC_REG:
2702                         amd64_inc_reg_size (code, ins->dreg, 4);
2703                         break;
2704                 case OP_X86_DEC_MEMBASE:
2705                         amd64_dec_membase_size (code, ins->inst_basereg, ins->inst_offset, 4);
2706                         break;
2707                 case OP_X86_DEC_REG:
2708                         amd64_dec_reg_size (code, ins->dreg, 4);
2709                         break;
2710                 case OP_X86_MUL_MEMBASE:
2711                         amd64_imul_reg_membase_size (code, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2712                         break;
2713                 case OP_AMD64_ICOMPARE_MEMBASE_REG:
2714                         amd64_alu_membase_reg_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2, 4);
2715                         break;
2716                 case OP_AMD64_ICOMPARE_MEMBASE_IMM:
2717                         amd64_alu_membase_imm_size (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm, 4);
2718                         break;
2719                 case OP_AMD64_ICOMPARE_REG_MEMBASE:
2720                         amd64_alu_reg_membase_size (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset, 4);
2721                         break;
2722                 case OP_BREAK:
2723                         amd64_breakpoint (code);
2724                         break;
2725                 case OP_ADDCC:
2726                 case CEE_ADD:
2727                 case OP_LADD:
2728                         amd64_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
2729                         break;
2730                 case OP_ADC:
2731                         amd64_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
2732                         break;
2733                 case OP_ADD_IMM:
2734                         g_assert (amd64_is_imm32 (ins->inst_imm));
2735                         amd64_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
2736                         break;
2737                 case OP_ADC_IMM:
2738                         g_assert (amd64_is_imm32 (ins->inst_imm));
2739                         amd64_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
2740                         break;
2741                 case OP_SUBCC:
2742                 case CEE_SUB:
2743                         amd64_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
2744                         break;
2745                 case OP_SBB:
2746                         amd64_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
2747                         break;
2748                 case OP_SUB_IMM:
2749                         g_assert (amd64_is_imm32 (ins->inst_imm));
2750                         amd64_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
2751                         break;
2752                 case OP_SBB_IMM:
2753                         g_assert (amd64_is_imm32 (ins->inst_imm));
2754                         amd64_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
2755                         break;
2756                 case CEE_AND:
2757                         amd64_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
2758                         break;
2759                 case OP_AND_IMM:
2760                         g_assert (amd64_is_imm32 (ins->inst_imm));
2761                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
2762                         break;
2763                 case CEE_MUL:
2764                 case OP_LMUL:
2765                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2766                         break;
2767                 case OP_MUL_IMM:
2768                 case OP_LMUL_IMM:
2769                 case OP_IMUL_IMM: {
2770                         guint32 size = (ins->opcode == OP_IMUL_IMM) ? 4 : 8;
2771                         
2772                         switch (ins->inst_imm) {
2773                         case 2:
2774                                 /* MOV r1, r2 */
2775                                 /* ADD r1, r1 */
2776                                 if (ins->dreg != ins->sreg1)
2777                                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, size);
2778                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
2779                                 break;
2780                         case 3:
2781                                 /* LEA r1, [r2 + r2*2] */
2782                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
2783                                 break;
2784                         case 5:
2785                                 /* LEA r1, [r2 + r2*4] */
2786                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2787                                 break;
2788                         case 6:
2789                                 /* LEA r1, [r2 + r2*2] */
2790                                 /* ADD r1, r1          */
2791                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
2792                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
2793                                 break;
2794                         case 9:
2795                                 /* LEA r1, [r2 + r2*8] */
2796                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 3);
2797                                 break;
2798                         case 10:
2799                                 /* LEA r1, [r2 + r2*4] */
2800                                 /* ADD r1, r1          */
2801                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2802                                 amd64_alu_reg_reg (code, X86_ADD, ins->dreg, ins->dreg);
2803                                 break;
2804                         case 12:
2805                                 /* LEA r1, [r2 + r2*2] */
2806                                 /* SHL r1, 2           */
2807                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 1);
2808                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
2809                                 break;
2810                         case 25:
2811                                 /* LEA r1, [r2 + r2*4] */
2812                                 /* LEA r1, [r1 + r1*4] */
2813                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2814                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
2815                                 break;
2816                         case 100:
2817                                 /* LEA r1, [r2 + r2*4] */
2818                                 /* SHL r1, 2           */
2819                                 /* LEA r1, [r1 + r1*4] */
2820                                 amd64_lea_memindex (code, ins->dreg, ins->sreg1, 0, ins->sreg1, 2);
2821                                 amd64_shift_reg_imm (code, X86_SHL, ins->dreg, 2);
2822                                 amd64_lea_memindex (code, ins->dreg, ins->dreg, 0, ins->dreg, 2);
2823                                 break;
2824                         default:
2825                                 amd64_imul_reg_reg_imm_size (code, ins->dreg, ins->sreg1, ins->inst_imm, size);
2826                                 break;
2827                         }
2828                         break;
2829                 }
2830                 case CEE_DIV:
2831                 case OP_LDIV:
2832                 case CEE_REM:
2833                 case OP_LREM:
2834                         /* Regalloc magic makes the div/rem cases the same */
2835                         if (ins->sreg2 == AMD64_RDX) {
2836                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2837                                 amd64_cdq (code);
2838                                 amd64_div_membase (code, AMD64_RSP, -8, TRUE);
2839                         } else {
2840                                 amd64_cdq (code);
2841                                 amd64_div_reg (code, ins->sreg2, TRUE);
2842                         }
2843                         break;
2844                 case CEE_DIV_UN:
2845                 case OP_LDIV_UN:
2846                 case CEE_REM_UN:
2847                 case OP_LREM_UN:
2848                         if (ins->sreg2 == AMD64_RDX) {
2849                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2850                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
2851                                 amd64_div_membase (code, AMD64_RSP, -8, FALSE);
2852                         } else {
2853                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
2854                                 amd64_div_reg (code, ins->sreg2, FALSE);
2855                         }
2856                         break;
2857                 case OP_IDIV:
2858                 case OP_IREM:
2859                         if (ins->sreg2 == AMD64_RDX) {
2860                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2861                                 amd64_cdq_size (code, 4);
2862                                 amd64_div_membase_size (code, AMD64_RSP, -8, TRUE, 4);
2863                         } else {
2864                                 amd64_cdq_size (code, 4);
2865                                 amd64_div_reg_size (code, ins->sreg2, TRUE, 4);
2866                         }
2867                         break;
2868                 case OP_IDIV_UN:
2869                 case OP_IREM_UN:
2870                         if (ins->sreg2 == AMD64_RDX) {
2871                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RDX, 8);
2872                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
2873                                 amd64_div_membase_size (code, AMD64_RSP, -8, FALSE, 4);
2874                         } else {
2875                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RDX, AMD64_RDX);
2876                                 amd64_div_reg_size (code, ins->sreg2, FALSE, 4);
2877                         }
2878                         break;
2879                 case OP_LMUL_OVF:
2880                         amd64_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2881                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
2882                         break;
2883                 case CEE_OR:
2884                         amd64_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
2885                         break;
2886                 case OP_OR_IMM:
2887                         g_assert (amd64_is_imm32 (ins->inst_imm));
2888                         amd64_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
2889                         break;
2890                 case CEE_XOR:
2891                 case OP_LXOR:
2892                         amd64_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
2893                         break;
2894                 case OP_XOR_IMM:
2895                         g_assert (amd64_is_imm32 (ins->inst_imm));
2896                         amd64_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
2897                         break;
2898                 case CEE_SHL:
2899                 case OP_LSHL:
2900                         g_assert (ins->sreg2 == AMD64_RCX);
2901                         amd64_shift_reg (code, X86_SHL, ins->dreg);
2902                         break;
2903                 case CEE_SHR:
2904                 case OP_LSHR:
2905                         g_assert (ins->sreg2 == AMD64_RCX);
2906                         amd64_shift_reg (code, X86_SAR, ins->dreg);
2907                         break;
2908                 case OP_SHR_IMM:
2909                         g_assert (amd64_is_imm32 (ins->inst_imm));
2910                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
2911                         break;
2912                 case OP_LSHR_IMM:
2913                         g_assert (amd64_is_imm32 (ins->inst_imm));
2914                         amd64_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
2915                         break;
2916                 case OP_SHR_UN_IMM:
2917                         g_assert (amd64_is_imm32 (ins->inst_imm));
2918                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
2919                         break;
2920                 case OP_LSHR_UN_IMM:
2921                         g_assert (amd64_is_imm32 (ins->inst_imm));
2922                         amd64_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
2923                         break;
2924                 case CEE_SHR_UN:
2925                         g_assert (ins->sreg2 == AMD64_RCX);
2926                         amd64_shift_reg_size (code, X86_SHR, ins->dreg, 4);
2927                         break;
2928                 case OP_LSHR_UN:
2929                         g_assert (ins->sreg2 == AMD64_RCX);
2930                         amd64_shift_reg (code, X86_SHR, ins->dreg);
2931                         break;
2932                 case OP_SHL_IMM:
2933                         g_assert (amd64_is_imm32 (ins->inst_imm));
2934                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
2935                         break;
2936                 case OP_LSHL_IMM:
2937                         g_assert (amd64_is_imm32 (ins->inst_imm));
2938                         amd64_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
2939                         break;
2940
2941                 case OP_IADDCC:
2942                 case OP_IADD:
2943                         amd64_alu_reg_reg_size (code, X86_ADD, ins->sreg1, ins->sreg2, 4);
2944                         break;
2945                 case OP_IADC:
2946                         amd64_alu_reg_reg_size (code, X86_ADC, ins->sreg1, ins->sreg2, 4);
2947                         break;
2948                 case OP_IADD_IMM:
2949                         amd64_alu_reg_imm_size (code, X86_ADD, ins->dreg, ins->inst_imm, 4);
2950                         break;
2951                 case OP_IADC_IMM:
2952                         amd64_alu_reg_imm_size (code, X86_ADC, ins->dreg, ins->inst_imm, 4);
2953                         break;
2954                 case OP_ISUBCC:
2955                 case OP_ISUB:
2956                         amd64_alu_reg_reg_size (code, X86_SUB, ins->sreg1, ins->sreg2, 4);
2957                         break;
2958                 case OP_ISBB:
2959                         amd64_alu_reg_reg_size (code, X86_SBB, ins->sreg1, ins->sreg2, 4);
2960                         break;
2961                 case OP_ISUB_IMM:
2962                         amd64_alu_reg_imm_size (code, X86_SUB, ins->dreg, ins->inst_imm, 4);
2963                         break;
2964                 case OP_ISBB_IMM:
2965                         amd64_alu_reg_imm_size (code, X86_SBB, ins->dreg, ins->inst_imm, 4);
2966                         break;
2967                 case OP_IAND:
2968                         amd64_alu_reg_reg_size (code, X86_AND, ins->sreg1, ins->sreg2, 4);
2969                         break;
2970                 case OP_IAND_IMM:
2971                         amd64_alu_reg_imm_size (code, X86_AND, ins->sreg1, ins->inst_imm, 4);
2972                         break;
2973                 case OP_IOR:
2974                         amd64_alu_reg_reg_size (code, X86_OR, ins->sreg1, ins->sreg2, 4);
2975                         break;
2976                 case OP_IOR_IMM:
2977                         amd64_alu_reg_imm_size (code, X86_OR, ins->sreg1, ins->inst_imm, 4);
2978                         break;
2979                 case OP_IXOR:
2980                         amd64_alu_reg_reg_size (code, X86_XOR, ins->sreg1, ins->sreg2, 4);
2981                         break;
2982                 case OP_IXOR_IMM:
2983                         amd64_alu_reg_imm_size (code, X86_XOR, ins->sreg1, ins->inst_imm, 4);
2984                         break;
2985                 case OP_INEG:
2986                         amd64_neg_reg_size (code, ins->sreg1, 4);
2987                         break;
2988                 case OP_INOT:
2989                         amd64_not_reg_size (code, ins->sreg1, 4);
2990                         break;
2991                 case OP_ISHL:
2992                         g_assert (ins->sreg2 == AMD64_RCX);
2993                         amd64_shift_reg_size (code, X86_SHL, ins->dreg, 4);
2994                         break;
2995                 case OP_ISHR:
2996                         g_assert (ins->sreg2 == AMD64_RCX);
2997                         amd64_shift_reg_size (code, X86_SAR, ins->dreg, 4);
2998                         break;
2999                 case OP_ISHR_IMM:
3000                         amd64_shift_reg_imm_size (code, X86_SAR, ins->dreg, ins->inst_imm, 4);
3001                         break;
3002                 case OP_ISHR_UN_IMM:
3003                         amd64_shift_reg_imm_size (code, X86_SHR, ins->dreg, ins->inst_imm, 4);
3004                         break;
3005                 case OP_ISHR_UN:
3006                         g_assert (ins->sreg2 == AMD64_RCX);
3007                         amd64_shift_reg_size (code, X86_SHR, ins->dreg, 4);
3008                         break;
3009                 case OP_ISHL_IMM:
3010                         amd64_shift_reg_imm_size (code, X86_SHL, ins->dreg, ins->inst_imm, 4);
3011                         break;
3012                 case OP_IMUL:
3013                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
3014                         break;
3015                 case OP_IMUL_OVF:
3016                         amd64_imul_reg_reg_size (code, ins->sreg1, ins->sreg2, 4);
3017                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
3018                         break;
3019                 case OP_IMUL_OVF_UN:
3020                 case OP_LMUL_OVF_UN: {
3021                         /* the mul operation and the exception check should most likely be split */
3022                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
3023                         int size = (ins->opcode == OP_IMUL_OVF_UN) ? 4 : 8;
3024                         /*g_assert (ins->sreg2 == X86_EAX);
3025                         g_assert (ins->dreg == X86_EAX);*/
3026                         if (ins->sreg2 == X86_EAX) {
3027                                 non_eax_reg = ins->sreg1;
3028                         } else if (ins->sreg1 == X86_EAX) {
3029                                 non_eax_reg = ins->sreg2;
3030                         } else {
3031                                 /* no need to save since we're going to store to it anyway */
3032                                 if (ins->dreg != X86_EAX) {
3033                                         saved_eax = TRUE;
3034                                         amd64_push_reg (code, X86_EAX);
3035                                 }
3036                                 amd64_mov_reg_reg (code, X86_EAX, ins->sreg1, size);
3037                                 non_eax_reg = ins->sreg2;
3038                         }
3039                         if (ins->dreg == X86_EDX) {
3040                                 if (!saved_eax) {
3041                                         saved_eax = TRUE;
3042                                         amd64_push_reg (code, X86_EAX);
3043                                 }
3044                         } else {
3045                                 saved_edx = TRUE;
3046                                 amd64_push_reg (code, X86_EDX);
3047                         }
3048                         amd64_mul_reg_size (code, non_eax_reg, FALSE, size);
3049                         /* save before the check since pop and mov don't change the flags */
3050                         if (ins->dreg != X86_EAX)
3051                                 amd64_mov_reg_reg (code, ins->dreg, X86_EAX, size);
3052                         if (saved_edx)
3053                                 amd64_pop_reg (code, X86_EDX);
3054                         if (saved_eax)
3055                                 amd64_pop_reg (code, X86_EAX);
3056                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
3057                         break;
3058                 }
3059                 case OP_ICOMPARE:
3060                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
3061                         break;
3062                 case OP_ICOMPARE_IMM:
3063                         amd64_alu_reg_imm_size (code, X86_CMP, ins->sreg1, ins->inst_imm, 4);
3064                         break;
3065                 case OP_IBEQ:
3066                 case OP_IBLT:
3067                 case OP_IBGT:
3068                 case OP_IBGE:
3069                 case OP_IBLE:
3070                 case OP_IBNE_UN:
3071                 case OP_IBLT_UN:
3072                 case OP_IBGT_UN:
3073                 case OP_IBGE_UN:
3074                 case OP_IBLE_UN:
3075                         EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
3076                         break;
3077                 case CEE_NOT:
3078                         amd64_not_reg (code, ins->sreg1);
3079                         break;
3080                 case CEE_NEG:
3081                         amd64_neg_reg (code, ins->sreg1);
3082                         break;
3083
3084                 case OP_ICONST:
3085                 case OP_I8CONST:
3086                         if ((((guint64)ins->inst_c0) >> 32) == 0)
3087                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 4);
3088                         else
3089                                 amd64_mov_reg_imm_size (code, ins->dreg, ins->inst_c0, 8);
3090                         break;
3091                 case OP_AOTCONST:
3092                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
3093                         amd64_mov_reg_membase (code, ins->dreg, AMD64_RIP, 0, 8);
3094                         break;
3095                 case CEE_CONV_I4:
3096                 case CEE_CONV_U4:
3097                 case OP_MOVE:
3098                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, sizeof (gpointer));
3099                         break;
3100                 case OP_AMD64_SET_XMMREG_R4: {
3101                         if (use_sse2) {
3102                                 amd64_sse_cvtsd2ss_reg_reg (code, ins->dreg, ins->sreg1);
3103                         }
3104                         else {
3105                                 amd64_fst_membase (code, AMD64_RSP, -8, FALSE, TRUE);
3106                                 /* ins->dreg is set to -1 by the reg allocator */
3107                                 amd64_movss_reg_membase (code, ins->backend.reg3, AMD64_RSP, -8);
3108                         }
3109                         break;
3110                 }
3111                 case OP_AMD64_SET_XMMREG_R8: {
3112                         if (use_sse2) {
3113                                 if (ins->dreg != ins->sreg1)
3114                                         amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
3115                         }
3116                         else {
3117                                 amd64_fst_membase (code, AMD64_RSP, -8, TRUE, TRUE);
3118                                 /* ins->dreg is set to -1 by the reg allocator */
3119                                 amd64_movsd_reg_membase (code, ins->backend.reg3, AMD64_RSP, -8);
3120                         }
3121                         break;
3122                 }
3123                 case OP_JMP: {
3124                         /*
3125                          * Note: this 'frame destruction' logic is useful for tail calls, too.
3126                          * Keep in sync with the code in emit_epilog.
3127                          */
3128                         int pos = 0, i;
3129
3130                         /* FIXME: no tracing support... */
3131                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3132                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
3133
3134                         g_assert (!cfg->method->save_lmf);
3135
3136                         code = emit_load_volatile_arguments (cfg, code);
3137
3138                         if (cfg->arch.omit_fp) {
3139                                 guint32 save_offset = 0;
3140                                 /* Pop callee-saved registers */
3141                                 for (i = 0; i < AMD64_NREG; ++i)
3142                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
3143                                                 amd64_mov_reg_membase (code, i, AMD64_RSP, save_offset, 8);
3144                                                 save_offset += 8;
3145                                         }
3146                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
3147                         }
3148                         else {
3149                                 for (i = 0; i < AMD64_NREG; ++i)
3150                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
3151                                                 pos -= sizeof (gpointer);
3152                         
3153                                 if (pos)
3154                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
3155
3156                                 /* Pop registers in reverse order */
3157                                 for (i = AMD64_NREG - 1; i > 0; --i)
3158                                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
3159                                                 amd64_pop_reg (code, i);
3160                                         }
3161
3162                                 amd64_leave (code);
3163                         }
3164
3165                         offset = code - cfg->native_code;
3166                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0);
3167                         if (cfg->compile_aot)
3168                                 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 0, 8);
3169                         else
3170                                 amd64_set_reg_template (code, AMD64_R11);
3171                         amd64_jump_reg (code, AMD64_R11);
3172                         break;
3173                 }
3174                 case OP_CHECK_THIS:
3175                         /* ensure ins->sreg1 is not NULL */
3176                         amd64_alu_membase_imm_size (code, X86_CMP, ins->sreg1, 0, 0, 4);
3177                         break;
3178                 case OP_ARGLIST: {
3179                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, cfg->sig_cookie);
3180                         amd64_mov_membase_reg (code, ins->sreg1, 0, AMD64_R11, 8);
3181                         break;
3182                 }
3183                 case OP_FCALL:
3184                 case OP_LCALL:
3185                 case OP_VCALL:
3186                 case OP_VOIDCALL:
3187                 case CEE_CALL:
3188                         call = (MonoCallInst*)ins;
3189                         /*
3190                          * The AMD64 ABI forces callers to know about varargs.
3191                          */
3192                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke))
3193                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3194                         else if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (cfg->method->klass->image != mono_defaults.corlib)) {
3195                                 /* 
3196                                  * Since the unmanaged calling convention doesn't contain a 
3197                                  * 'vararg' entry, we have to treat every pinvoke call as a
3198                                  * potential vararg call.
3199                                  */
3200                                 guint32 nregs, i;
3201                                 nregs = 0;
3202                                 for (i = 0; i < AMD64_XMM_NREG; ++i)
3203                                         if (call->used_fregs & (1 << i))
3204                                                 nregs ++;
3205                                 if (!nregs)
3206                                         amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3207                                 else
3208                                         amd64_mov_reg_imm (code, AMD64_RAX, nregs);
3209                         }
3210
3211                         if (ins->flags & MONO_INST_HAS_METHOD)
3212                                 code = emit_call (cfg, code, MONO_PATCH_INFO_METHOD, call->method);
3213                         else
3214                                 code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, call->fptr);
3215                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
3216                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
3217                         code = emit_move_return_value (cfg, ins, code);
3218                         break;
3219                 case OP_FCALL_REG:
3220                 case OP_LCALL_REG:
3221                 case OP_VCALL_REG:
3222                 case OP_VOIDCALL_REG:
3223                 case OP_CALL_REG:
3224                         call = (MonoCallInst*)ins;
3225
3226                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
3227                                 amd64_mov_reg_reg (code, AMD64_R11, ins->sreg1, 8);
3228                                 ins->sreg1 = AMD64_R11;
3229                         }
3230
3231                         /*
3232                          * The AMD64 ABI forces callers to know about varargs.
3233                          */
3234                         if ((call->signature->call_convention == MONO_CALL_VARARG) && (call->signature->pinvoke)) {
3235                                 if (ins->sreg1 == AMD64_RAX) {
3236                                         amd64_mov_reg_reg (code, AMD64_R11, AMD64_RAX, 8);
3237                                         ins->sreg1 = AMD64_R11;
3238                                 }
3239                                 amd64_alu_reg_reg (code, X86_XOR, AMD64_RAX, AMD64_RAX);
3240                         }
3241                         amd64_call_reg (code, ins->sreg1);
3242                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
3243                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
3244                         code = emit_move_return_value (cfg, ins, code);
3245                         break;
3246                 case OP_FCALL_MEMBASE:
3247                 case OP_LCALL_MEMBASE:
3248                 case OP_VCALL_MEMBASE:
3249                 case OP_VOIDCALL_MEMBASE:
3250                 case OP_CALL_MEMBASE:
3251                         call = (MonoCallInst*)ins;
3252
3253                         if (AMD64_IS_ARGUMENT_REG (ins->sreg1)) {
3254                                 /* 
3255                                  * Can't use R11 because it is clobbered by the trampoline 
3256                                  * code, and the reg value is needed by get_vcall_slot_addr.
3257                                  */
3258                                 amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
3259                                 ins->sreg1 = AMD64_RAX;
3260                         }
3261
3262                         amd64_call_membase (code, ins->sreg1, ins->inst_offset);
3263                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
3264                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, call->stack_usage);
3265                         code = emit_move_return_value (cfg, ins, code);
3266                         break;
3267                 case OP_AMD64_SAVE_SP_TO_LMF:
3268                         amd64_mov_membase_reg (code, cfg->frame_reg, cfg->arch.lmf_offset + G_STRUCT_OFFSET (MonoLMF, rsp), AMD64_RSP, 8);
3269                         break;
3270                 case OP_OUTARG:
3271                 case OP_X86_PUSH:
3272                         amd64_push_reg (code, ins->sreg1);
3273                         break;
3274                 case OP_X86_PUSH_IMM:
3275                         g_assert (amd64_is_imm32 (ins->inst_imm));
3276                         amd64_push_imm (code, ins->inst_imm);
3277                         break;
3278                 case OP_X86_PUSH_MEMBASE:
3279                         amd64_push_membase (code, ins->inst_basereg, ins->inst_offset);
3280                         break;
3281                 case OP_X86_PUSH_OBJ: 
3282                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, ins->inst_imm);
3283                         amd64_push_reg (code, AMD64_RDI);
3284                         amd64_push_reg (code, AMD64_RSI);
3285                         amd64_push_reg (code, AMD64_RCX);
3286                         if (ins->inst_offset)
3287                                 amd64_lea_membase (code, AMD64_RSI, ins->inst_basereg, ins->inst_offset);
3288                         else
3289                                 amd64_mov_reg_reg (code, AMD64_RSI, ins->inst_basereg, 8);
3290                         amd64_lea_membase (code, AMD64_RDI, AMD64_RSP, 3 * 8);
3291                         amd64_mov_reg_imm (code, AMD64_RCX, (ins->inst_imm >> 3));
3292                         amd64_cld (code);
3293                         amd64_prefix (code, X86_REP_PREFIX);
3294                         amd64_movsd (code);
3295                         amd64_pop_reg (code, AMD64_RCX);
3296                         amd64_pop_reg (code, AMD64_RSI);
3297                         amd64_pop_reg (code, AMD64_RDI);
3298                         break;
3299                 case OP_X86_LEA:
3300                         amd64_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->backend.shift_amount);
3301                         break;
3302                 case OP_X86_LEA_MEMBASE:
3303                         amd64_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
3304                         break;
3305                 case OP_X86_XCHG:
3306                         amd64_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
3307                         break;
3308                 case OP_LOCALLOC:
3309                         /* keep alignment */
3310                         amd64_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
3311                         amd64_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
3312                         code = mono_emit_stack_alloc (code, ins);
3313                         amd64_mov_reg_reg (code, ins->dreg, AMD64_RSP, 8);
3314                         break;
3315                 case OP_THROW: {
3316                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
3317                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3318                                              (gpointer)"mono_arch_throw_exception");
3319                         break;
3320                 }
3321                 case OP_RETHROW: {
3322                         amd64_mov_reg_reg (code, AMD64_ARG_REG1, ins->sreg1, 8);
3323                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3324                                              (gpointer)"mono_arch_rethrow_exception");
3325                         break;
3326                 }
3327                 case OP_CALL_HANDLER: 
3328                         /* Align stack */
3329                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
3330                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
3331                         amd64_call_imm (code, 0);
3332                         /* Restore stack alignment */
3333                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
3334                         break;
3335                 case OP_START_HANDLER: {
3336                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
3337                         amd64_mov_membase_reg (code, spvar->inst_basereg, spvar->inst_offset, AMD64_RSP, 8);
3338                         break;
3339                 }
3340                 case OP_ENDFINALLY: {
3341                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
3342                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, 8);
3343                         amd64_ret (code);
3344                         break;
3345                 }
3346                 case OP_ENDFILTER: {
3347                         MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region);
3348                         amd64_mov_reg_membase (code, AMD64_RSP, spvar->inst_basereg, spvar->inst_offset, 8);
3349                         /* The local allocator will put the result into RAX */
3350                         amd64_ret (code);
3351                         break;
3352                 }
3353
3354                 case OP_LABEL:
3355                         ins->inst_c0 = code - cfg->native_code;
3356                         break;
3357                 case OP_NOP:
3358                         break;
3359                 case OP_BR:
3360                         if (ins->flags & MONO_INST_BRLABEL) {
3361                                 if (ins->inst_i0->inst_c0) {
3362                                         amd64_jump_code (code, cfg->native_code + ins->inst_i0->inst_c0);
3363                                 } else {
3364                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_LABEL, ins->inst_i0);
3365                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
3366                                             x86_is_imm8 (ins->inst_i0->inst_c1 - cpos))
3367                                                 x86_jump8 (code, 0);
3368                                         else 
3369                                                 x86_jump32 (code, 0);
3370                                 }
3371                         } else {
3372                                 if (ins->inst_target_bb->native_offset) {
3373                                         amd64_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
3374                                 } else {
3375                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
3376                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
3377                                             x86_is_imm8 (ins->inst_target_bb->max_offset - cpos))
3378                                                 x86_jump8 (code, 0);
3379                                         else 
3380                                                 x86_jump32 (code, 0);
3381                                 } 
3382                         }
3383                         break;
3384                 case OP_BR_REG:
3385                         amd64_jump_reg (code, ins->sreg1);
3386                         break;
3387                 case OP_CEQ:
3388                 case OP_ICEQ:
3389                 case OP_CLT:
3390                 case OP_ICLT:
3391                 case OP_CGT:
3392                 case OP_ICGT:
3393                 case OP_CLT_UN:
3394                 case OP_ICLT_UN:
3395                 case OP_CGT_UN:
3396                 case OP_ICGT_UN:
3397                         amd64_set_reg (code, cc_table [mono_opcode_to_cond (ins->opcode)], ins->dreg, cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
3398                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3399                         break;
3400                 case OP_COND_EXC_EQ:
3401                 case OP_COND_EXC_NE_UN:
3402                 case OP_COND_EXC_LT:
3403                 case OP_COND_EXC_LT_UN:
3404                 case OP_COND_EXC_GT:
3405                 case OP_COND_EXC_GT_UN:
3406                 case OP_COND_EXC_GE:
3407                 case OP_COND_EXC_GE_UN:
3408                 case OP_COND_EXC_LE:
3409                 case OP_COND_EXC_LE_UN:
3410                         EMIT_COND_SYSTEM_EXCEPTION (cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)], ins->inst_p1);
3411                         break;
3412                 case OP_COND_EXC_OV:
3413                 case OP_COND_EXC_NO:
3414                 case OP_COND_EXC_C:
3415                 case OP_COND_EXC_NC:
3416                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
3417                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
3418                         break;
3419                 case OP_COND_EXC_IOV:
3420                 case OP_COND_EXC_IC:
3421                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_IEQ], 
3422                                                     (ins->opcode < OP_COND_EXC_INE_UN), ins->inst_p1);
3423                         break;
3424                 case CEE_BEQ:
3425                 case CEE_BNE_UN:
3426                 case CEE_BLT:
3427                 case CEE_BLT_UN:
3428                 case CEE_BGT:
3429                 case CEE_BGT_UN:
3430                 case CEE_BGE:
3431                 case CEE_BGE_UN:
3432                 case CEE_BLE:
3433                 case CEE_BLE_UN:
3434                         EMIT_COND_BRANCH (ins, cc_table [mono_opcode_to_cond (ins->opcode)], cc_signed_table [mono_opcode_to_cond (ins->opcode)]);
3435                         break;
3436
3437                 /* floating point opcodes */
3438                 case OP_R8CONST: {
3439                         double d = *(double *)ins->inst_p0;
3440
3441                         if (use_sse2) {
3442                                 if ((d == 0.0) && (mono_signbit (d) == 0)) {
3443                                         amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
3444                                 }
3445                                 else {
3446                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
3447                                         amd64_sse_movsd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
3448                                 }
3449                         }
3450                         else if ((d == 0.0) && (mono_signbit (d) == 0)) {
3451                                 amd64_fldz (code);
3452                         } else if (d == 1.0) {
3453                                 x86_fld1 (code);
3454                         } else {
3455                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
3456                                 amd64_fld_membase (code, AMD64_RIP, 0, TRUE);
3457                         }
3458                         break;
3459                 }
3460                 case OP_R4CONST: {
3461                         float f = *(float *)ins->inst_p0;
3462
3463                         if (use_sse2) {
3464                                 if ((f == 0.0) && (mono_signbit (f) == 0)) {
3465                                         amd64_sse_xorpd_reg_reg (code, ins->dreg, ins->dreg);
3466                                 }
3467                                 else {
3468                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
3469                                         amd64_sse_movss_reg_membase (code, ins->dreg, AMD64_RIP, 0);
3470                                         amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
3471                                 }
3472                         }
3473                         else if ((f == 0.0) && (mono_signbit (f) == 0)) {
3474                                 amd64_fldz (code);
3475                         } else if (f == 1.0) {
3476                                 x86_fld1 (code);
3477                         } else {
3478                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
3479                                 amd64_fld_membase (code, AMD64_RIP, 0, FALSE);
3480                         }
3481                         break;
3482                 }
3483                 case OP_STORER8_MEMBASE_REG:
3484                         if (use_sse2)
3485                                 amd64_sse_movsd_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1);
3486                         else
3487                                 amd64_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, TRUE, TRUE);
3488                         break;
3489                 case OP_LOADR8_SPILL_MEMBASE:
3490                         if (use_sse2)
3491                                 g_assert_not_reached ();
3492                         amd64_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
3493                         amd64_fxch (code, 1);
3494                         break;
3495                 case OP_LOADR8_MEMBASE:
3496                         if (use_sse2)
3497                                 amd64_sse_movsd_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
3498                         else
3499                                 amd64_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
3500                         break;
3501                 case OP_STORER4_MEMBASE_REG:
3502                         if (use_sse2) {
3503                                 /* This requires a double->single conversion */
3504                                 amd64_sse_cvtsd2ss_reg_reg (code, AMD64_XMM15, ins->sreg1);
3505                                 amd64_sse_movss_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, AMD64_XMM15);
3506                         }
3507                         else
3508                                 amd64_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, FALSE, TRUE);
3509                         break;
3510                 case OP_LOADR4_MEMBASE:
3511                         if (use_sse2) {
3512                                 amd64_sse_movss_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset);
3513                                 amd64_sse_cvtss2sd_reg_reg (code, ins->dreg, ins->dreg);
3514                         }
3515                         else
3516                                 amd64_fld_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
3517                         break;
3518                 case CEE_CONV_R4: /* FIXME: change precision */
3519                 case CEE_CONV_R8:
3520                         if (use_sse2)
3521                                 amd64_sse_cvtsi2sd_reg_reg_size (code, ins->dreg, ins->sreg1, 4);
3522                         else {
3523                                 amd64_push_reg (code, ins->sreg1);
3524                                 amd64_fild_membase (code, AMD64_RSP, 0, FALSE);
3525                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
3526                         }
3527                         break;
3528                 case CEE_CONV_R_UN:
3529                         /* Emulated */
3530                         g_assert_not_reached ();
3531                         break;
3532                 case OP_LCONV_TO_R4: /* FIXME: change precision */
3533                 case OP_LCONV_TO_R8:
3534                         if (use_sse2)
3535                                 amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
3536                         else {
3537                                 amd64_push_reg (code, ins->sreg1);
3538                                 amd64_fild_membase (code, AMD64_RSP, 0, TRUE);
3539                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
3540                         }
3541                         break;
3542                 case OP_X86_FP_LOAD_I8:
3543                         if (use_sse2)
3544                                 g_assert_not_reached ();
3545                         amd64_fild_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
3546                         break;
3547                 case OP_X86_FP_LOAD_I4:
3548                         if (use_sse2)
3549                                 g_assert_not_reached ();
3550                         amd64_fild_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
3551                         break;
3552                 case OP_FCONV_TO_I1:
3553                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE);
3554                         break;
3555                 case OP_FCONV_TO_U1:
3556                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE);
3557                         break;
3558                 case OP_FCONV_TO_I2:
3559                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE);
3560                         break;
3561                 case OP_FCONV_TO_U2:
3562                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE);
3563                         break;
3564                 case OP_FCONV_TO_I4:
3565                 case OP_FCONV_TO_I:
3566                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE);
3567                         break;
3568                 case OP_FCONV_TO_I8:
3569                         code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 8, TRUE);
3570                         break;
3571                 case OP_LCONV_TO_R_UN: { 
3572                         static guint8 mn[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x40 };
3573                         guint8 *br [2];
3574
3575                         if (use_sse2) {
3576                                 /* Based on gcc code */
3577                                 amd64_test_reg_reg (code, ins->sreg1, ins->sreg1);
3578                                 br [0] = code; x86_branch8 (code, X86_CC_S, 0, TRUE);
3579
3580                                 /* Positive case */
3581                                 amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, ins->sreg1);
3582                                 br [1] = code; x86_jump8 (code, 0);
3583                                 amd64_patch (br [0], code);
3584
3585                                 /* Negative case */
3586                                 /* Save to the red zone */
3587                                 amd64_mov_membase_reg (code, AMD64_RSP, -8, AMD64_RAX, 8);
3588                                 amd64_mov_membase_reg (code, AMD64_RSP, -16, AMD64_RCX, 8);
3589                                 amd64_mov_reg_reg (code, AMD64_RCX, ins->sreg1, 8);
3590                                 amd64_mov_reg_reg (code, AMD64_RAX, ins->sreg1, 8);
3591                                 amd64_alu_reg_imm (code, X86_AND, AMD64_RCX, 1);
3592                                 amd64_shift_reg_imm (code, X86_SHR, AMD64_RAX, 1);
3593                                 amd64_alu_reg_imm (code, X86_OR, AMD64_RAX, AMD64_RCX);
3594                                 amd64_sse_cvtsi2sd_reg_reg (code, ins->dreg, AMD64_RAX);
3595                                 amd64_sse_addsd_reg_reg (code, ins->dreg, ins->dreg);
3596                                 /* Restore */
3597                                 amd64_mov_reg_membase (code, AMD64_RCX, AMD64_RSP, -16, 8);
3598                                 amd64_mov_reg_membase (code, AMD64_RAX, AMD64_RSP, -8, 8);
3599                                 amd64_patch (br [1], code);
3600
3601                                 break;
3602                         }
3603
3604                         /* load 64bit integer to FP stack */
3605                         amd64_push_imm (code, 0);
3606                         amd64_push_reg (code, ins->sreg2);
3607                         amd64_push_reg (code, ins->sreg1);
3608                         amd64_fild_membase (code, AMD64_RSP, 0, TRUE);
3609                         /* store as 80bit FP value */
3610                         x86_fst80_membase (code, AMD64_RSP, 0);
3611                         
3612                         /* test if lreg is negative */
3613                         amd64_test_reg_reg (code, ins->sreg2, ins->sreg2);
3614                         br [0] = code; x86_branch8 (code, X86_CC_GEZ, 0, TRUE);
3615         
3616                         /* add correction constant mn */
3617                         x86_fld80_mem (code, (gssize)mn);
3618                         x86_fld80_membase (code, AMD64_RSP, 0);
3619                         amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3620                         x86_fst80_membase (code, AMD64_RSP, 0);
3621
3622                         amd64_patch (br [0], code);
3623
3624                         x86_fld80_membase (code, AMD64_RSP, 0);
3625                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 12);
3626
3627                         break;
3628                 }
3629                 case CEE_CONV_OVF_U4:
3630                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0);
3631                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_LT, TRUE, "OverflowException");
3632                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
3633                         break;
3634                 case CEE_CONV_OVF_I4_UN:
3635                         amd64_alu_reg_imm (code, X86_CMP, ins->sreg1, 0x7fffffff);
3636                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_GT, FALSE, "OverflowException");
3637                         amd64_mov_reg_reg (code, ins->dreg, ins->sreg1, 8);
3638                         break;
3639                 case OP_FMOVE:
3640                         if (use_sse2 && (ins->dreg != ins->sreg1))
3641                                 amd64_sse_movsd_reg_reg (code, ins->dreg, ins->sreg1);
3642                         break;
3643                 case OP_FADD:
3644                         if (use_sse2)
3645                                 amd64_sse_addsd_reg_reg (code, ins->dreg, ins->sreg2);
3646                         else
3647                                 amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3648                         break;
3649                 case OP_FSUB:
3650                         if (use_sse2)
3651                                 amd64_sse_subsd_reg_reg (code, ins->dreg, ins->sreg2);
3652                         else
3653                                 amd64_fp_op_reg (code, X86_FSUB, 1, TRUE);
3654                         break;          
3655                 case OP_FMUL:
3656                         if (use_sse2)
3657                                 amd64_sse_mulsd_reg_reg (code, ins->dreg, ins->sreg2);
3658                         else
3659                                 amd64_fp_op_reg (code, X86_FMUL, 1, TRUE);
3660                         break;          
3661                 case OP_FDIV:
3662                         if (use_sse2)
3663                                 amd64_sse_divsd_reg_reg (code, ins->dreg, ins->sreg2);
3664                         else
3665                                 amd64_fp_op_reg (code, X86_FDIV, 1, TRUE);
3666                         break;          
3667                 case OP_FNEG:
3668                         if (use_sse2) {
3669                                 static double r8_0 = -0.0;
3670
3671                                 g_assert (ins->sreg1 == ins->dreg);
3672                                         
3673                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, &r8_0);
3674                                 amd64_sse_xorpd_reg_membase (code, ins->dreg, AMD64_RIP, 0);
3675                         }
3676                         else
3677                                 amd64_fchs (code);
3678                         break;          
3679                 case OP_SIN:
3680                         if (use_sse2) {
3681                                 EMIT_SSE2_FPFUNC (code, fsin, ins->dreg, ins->sreg1);
3682                         }
3683                         else {
3684                                 amd64_fsin (code);
3685                                 amd64_fldz (code);
3686                                 amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3687                         }
3688                         break;          
3689                 case OP_COS:
3690                         if (use_sse2) {
3691                                 EMIT_SSE2_FPFUNC (code, fcos, ins->dreg, ins->sreg1);
3692                         }
3693                         else {
3694                                 amd64_fcos (code);
3695                                 amd64_fldz (code);
3696                                 amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3697                         }
3698                         break;          
3699                 case OP_ABS:
3700                         if (use_sse2) {
3701                                 EMIT_SSE2_FPFUNC (code, fabs, ins->dreg, ins->sreg1);
3702                         }
3703                         else
3704                                 amd64_fabs (code);
3705                         break;          
3706                 case OP_TAN: {
3707                         /* 
3708                          * it really doesn't make sense to inline all this code,
3709                          * it's here just to show that things may not be as simple 
3710                          * as they appear.
3711                          */
3712                         guchar *check_pos, *end_tan, *pop_jump;
3713                         if (use_sse2)
3714                                 g_assert_not_reached ();
3715                         amd64_push_reg (code, AMD64_RAX);
3716                         amd64_fptan (code);
3717                         amd64_fnstsw (code);
3718                         amd64_test_reg_imm (code, AMD64_RAX, X86_FP_C2);
3719                         check_pos = code;
3720                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
3721                         amd64_fstp (code, 0); /* pop the 1.0 */
3722                         end_tan = code;
3723                         x86_jump8 (code, 0);
3724                         amd64_fldpi (code);
3725                         amd64_fp_op (code, X86_FADD, 0);
3726                         amd64_fxch (code, 1);
3727                         x86_fprem1 (code);
3728                         amd64_fstsw (code);
3729                         amd64_test_reg_imm (code, AMD64_RAX, X86_FP_C2);
3730                         pop_jump = code;
3731                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
3732                         amd64_fstp (code, 1);
3733                         amd64_fptan (code);
3734                         amd64_patch (pop_jump, code);
3735                         amd64_fstp (code, 0); /* pop the 1.0 */
3736                         amd64_patch (check_pos, code);
3737                         amd64_patch (end_tan, code);
3738                         amd64_fldz (code);
3739                         amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3740                         amd64_pop_reg (code, AMD64_RAX);
3741                         break;
3742                 }
3743                 case OP_ATAN:
3744                         if (use_sse2)
3745                                 g_assert_not_reached ();
3746                         x86_fld1 (code);
3747                         amd64_fpatan (code);
3748                         amd64_fldz (code);
3749                         amd64_fp_op_reg (code, X86_FADD, 1, TRUE);
3750                         break;          
3751                 case OP_SQRT:
3752                         if (use_sse2) {
3753                                 EMIT_SSE2_FPFUNC (code, fsqrt, ins->dreg, ins->sreg1);
3754                         }
3755                         else
3756                                 amd64_fsqrt (code);
3757                         break;
3758                 case OP_IMIN:
3759                         g_assert (cfg->opt & MONO_OPT_CMOV);
3760                         g_assert (ins->dreg == ins->sreg1);
3761                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
3762                         amd64_cmov_reg_size (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2, 4);
3763                         break;
3764                 case OP_IMAX:
3765                         g_assert (cfg->opt & MONO_OPT_CMOV);
3766                         g_assert (ins->dreg == ins->sreg1);
3767                         amd64_alu_reg_reg_size (code, X86_CMP, ins->sreg1, ins->sreg2, 4);
3768                         amd64_cmov_reg_size (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2, 4);
3769                         break;
3770                 case OP_LMIN:
3771                         g_assert (cfg->opt & MONO_OPT_CMOV);
3772                         g_assert (ins->dreg == ins->sreg1);
3773                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
3774                         amd64_cmov_reg (code, X86_CC_GT, TRUE, ins->dreg, ins->sreg2);
3775                         break;
3776                 case OP_LMAX:
3777                         g_assert (cfg->opt & MONO_OPT_CMOV);
3778                         g_assert (ins->dreg == ins->sreg1);
3779                         amd64_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
3780                         amd64_cmov_reg (code, X86_CC_LT, TRUE, ins->dreg, ins->sreg2);
3781                         break;  
3782                 case OP_X86_FPOP:
3783                         if (!use_sse2)
3784                                 amd64_fstp (code, 0);
3785                         break;          
3786                 case OP_FREM: {
3787                         guint8 *l1, *l2;
3788
3789                         if (use_sse2)
3790                                 g_assert_not_reached ();
3791                         amd64_push_reg (code, AMD64_RAX);
3792                         /* we need to exchange ST(0) with ST(1) */
3793                         amd64_fxch (code, 1);
3794
3795                         /* this requires a loop, because fprem somtimes 
3796                          * returns a partial remainder */
3797                         l1 = code;
3798                         /* looks like MS is using fprem instead of the IEEE compatible fprem1 */
3799                         /* x86_fprem1 (code); */
3800                         amd64_fprem (code);
3801                         amd64_fnstsw (code);
3802                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_C2);
3803                         l2 = code + 2;
3804                         x86_branch8 (code, X86_CC_NE, l1 - l2, FALSE);
3805
3806                         /* pop result */
3807                         amd64_fstp (code, 1);
3808
3809                         amd64_pop_reg (code, AMD64_RAX);
3810                         break;
3811                 }
3812                 case OP_FCOMPARE:
3813                         if (use_sse2) {
3814                                 /* 
3815                                  * The two arguments are swapped because the fbranch instructions
3816                                  * depend on this for the non-sse case to work.
3817                                  */
3818                                 amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
3819                                 break;
3820                         }
3821                         if (cfg->opt & MONO_OPT_FCMOV) {
3822                                 amd64_fcomip (code, 1);
3823                                 amd64_fstp (code, 0);
3824                                 break;
3825                         }
3826                         /* this overwrites EAX */
3827                         EMIT_FPCOMPARE(code);
3828                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
3829                         break;
3830                 case OP_FCEQ:
3831                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
3832                                 /* zeroing the register at the start results in 
3833                                  * shorter and faster code (we can also remove the widening op)
3834                                  */
3835                                 guchar *unordered_check;
3836                                 amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3837                                 
3838                                 if (use_sse2)
3839                                         amd64_sse_comisd_reg_reg (code, ins->sreg1, ins->sreg2);
3840                                 else {
3841                                         amd64_fcomip (code, 1);
3842                                         amd64_fstp (code, 0);
3843                                 }
3844                                 unordered_check = code;
3845                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3846                                 amd64_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
3847                                 amd64_patch (unordered_check, code);
3848                                 break;
3849                         }
3850                         if (ins->dreg != AMD64_RAX) 
3851                                 amd64_push_reg (code, AMD64_RAX);
3852
3853                         EMIT_FPCOMPARE(code);
3854                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
3855                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0x4000);
3856                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3857                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3858
3859                         if (ins->dreg != AMD64_RAX) 
3860                                 amd64_pop_reg (code, AMD64_RAX);
3861                         break;
3862                 case OP_FCLT:
3863                 case OP_FCLT_UN:
3864                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
3865                                 /* zeroing the register at the start results in 
3866                                  * shorter and faster code (we can also remove the widening op)
3867                                  */
3868                                 amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3869                                 if (use_sse2)
3870                                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
3871                                 else {
3872                                         amd64_fcomip (code, 1);
3873                                         amd64_fstp (code, 0);
3874                                 }
3875                                 if (ins->opcode == OP_FCLT_UN) {
3876                                         guchar *unordered_check = code;
3877                                         guchar *jump_to_end;
3878                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
3879                                         amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
3880                                         jump_to_end = code;
3881                                         x86_jump8 (code, 0);
3882                                         amd64_patch (unordered_check, code);
3883                                         amd64_inc_reg (code, ins->dreg);
3884                                         amd64_patch (jump_to_end, code);
3885                                 } else {
3886                                         amd64_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
3887                                 }
3888                                 break;
3889                         }
3890                         if (ins->dreg != AMD64_RAX) 
3891                                 amd64_push_reg (code, AMD64_RAX);
3892
3893                         EMIT_FPCOMPARE(code);
3894                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
3895                         if (ins->opcode == OP_FCLT_UN) {
3896                                 guchar *is_not_zero_check, *end_jump;
3897                                 is_not_zero_check = code;
3898                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3899                                 end_jump = code;
3900                                 x86_jump8 (code, 0);
3901                                 amd64_patch (is_not_zero_check, code);
3902                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
3903
3904                                 amd64_patch (end_jump, code);
3905                         }
3906                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3907                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3908
3909                         if (ins->dreg != AMD64_RAX) 
3910                                 amd64_pop_reg (code, AMD64_RAX);
3911                         break;
3912                 case OP_FCGT:
3913                 case OP_FCGT_UN:
3914                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
3915                                 /* zeroing the register at the start results in 
3916                                  * shorter and faster code (we can also remove the widening op)
3917                                  */
3918                                 guchar *unordered_check;
3919                                 amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3920                                 if (use_sse2)
3921                                         amd64_sse_comisd_reg_reg (code, ins->sreg2, ins->sreg1);
3922                                 else {
3923                                         amd64_fcomip (code, 1);
3924                                         amd64_fstp (code, 0);
3925                                 }
3926                                 if (ins->opcode == OP_FCGT) {
3927                                         unordered_check = code;
3928                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
3929                                         amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
3930                                         amd64_patch (unordered_check, code);
3931                                 } else {
3932                                         amd64_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
3933                                 }
3934                                 break;
3935                         }
3936                         if (ins->dreg != AMD64_RAX) 
3937                                 amd64_push_reg (code, AMD64_RAX);
3938
3939                         EMIT_FPCOMPARE(code);
3940                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, X86_FP_CC_MASK);
3941                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
3942                         if (ins->opcode == OP_FCGT_UN) {
3943                                 guchar *is_not_zero_check, *end_jump;
3944                                 is_not_zero_check = code;
3945                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3946                                 end_jump = code;
3947                                 x86_jump8 (code, 0);
3948                                 amd64_patch (is_not_zero_check, code);
3949                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
3950
3951                                 amd64_patch (end_jump, code);
3952                         }
3953                         amd64_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3954                         amd64_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3955
3956                         if (ins->dreg != AMD64_RAX) 
3957                                 amd64_pop_reg (code, AMD64_RAX);
3958                         break;
3959                 case OP_FCLT_MEMBASE:
3960                 case OP_FCGT_MEMBASE:
3961                 case OP_FCLT_UN_MEMBASE:
3962                 case OP_FCGT_UN_MEMBASE:
3963                 case OP_FCEQ_MEMBASE: {
3964                         guchar *unordered_check, *jump_to_end;
3965                         int x86_cond;
3966                         g_assert (use_sse2);
3967
3968                         amd64_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3969                         amd64_sse_comisd_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
3970
3971                         switch (ins->opcode) {
3972                         case OP_FCEQ_MEMBASE:
3973                                 x86_cond = X86_CC_EQ;
3974                                 break;
3975                         case OP_FCLT_MEMBASE:
3976                         case OP_FCLT_UN_MEMBASE:
3977                                 x86_cond = X86_CC_LT;
3978                                 break;
3979                         case OP_FCGT_MEMBASE:
3980                         case OP_FCGT_UN_MEMBASE:
3981                                 x86_cond = X86_CC_GT;
3982                                 break;
3983                         default:
3984                                 g_assert_not_reached ();
3985                         }
3986
3987                         unordered_check = code;
3988                         x86_branch8 (code, X86_CC_P, 0, FALSE);
3989                         amd64_set_reg (code, x86_cond, ins->dreg, FALSE);
3990
3991                         switch (ins->opcode) {
3992                         case OP_FCEQ_MEMBASE:
3993                         case OP_FCLT_MEMBASE:
3994                         case OP_FCGT_MEMBASE:
3995                                 amd64_patch (unordered_check, code);
3996                                 break;
3997                         case OP_FCLT_UN_MEMBASE:
3998                         case OP_FCGT_UN_MEMBASE:
3999                                 jump_to_end = code;
4000                                 x86_jump8 (code, 0);
4001                                 amd64_patch (unordered_check, code);
4002                                 amd64_inc_reg (code, ins->dreg);
4003                                 amd64_patch (jump_to_end, code);
4004                                 break;
4005                         default:
4006                                 break;
4007                         }
4008                         break;
4009                 }
4010                 case OP_FBEQ:
4011                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4012                                 guchar *jump = code;
4013                                 x86_branch8 (code, X86_CC_P, 0, TRUE);
4014                                 EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4015                                 amd64_patch (jump, code);
4016                                 break;
4017                         }
4018                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0x4000);
4019                         EMIT_COND_BRANCH (ins, X86_CC_EQ, TRUE);
4020                         break;
4021                 case OP_FBNE_UN:
4022                         /* Branch if C013 != 100 */
4023                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4024                                 /* branch if !ZF or (PF|CF) */
4025                                 EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4026                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
4027                                 EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
4028                                 break;
4029                         }
4030                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C3);
4031                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4032                         break;
4033                 case OP_FBLT:
4034                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4035                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
4036                                 break;
4037                         }
4038                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4039                         break;
4040                 case OP_FBLT_UN:
4041                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4042                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
4043                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
4044                                 break;
4045                         }
4046                         if (ins->opcode == OP_FBLT_UN) {
4047                                 guchar *is_not_zero_check, *end_jump;
4048                                 is_not_zero_check = code;
4049                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
4050                                 end_jump = code;
4051                                 x86_jump8 (code, 0);
4052                                 amd64_patch (is_not_zero_check, code);
4053                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
4054
4055                                 amd64_patch (end_jump, code);
4056                         }
4057                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4058                         break;
4059                 case OP_FBGT:
4060                 case OP_FBGT_UN:
4061                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4062                                 if (ins->opcode == OP_FBGT) {
4063                                         guchar *br1;
4064
4065                                         /* skip branch if C1=1 */
4066                                         br1 = code;
4067                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
4068                                         /* branch if (C0 | C3) = 1 */
4069                                         EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
4070                                         amd64_patch (br1, code);
4071                                         break;
4072                                 } else {
4073                                         EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
4074                                 }
4075                                 break;
4076                         }
4077                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4078                         if (ins->opcode == OP_FBGT_UN) {
4079                                 guchar *is_not_zero_check, *end_jump;
4080                                 is_not_zero_check = code;
4081                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
4082                                 end_jump = code;
4083                                 x86_jump8 (code, 0);
4084                                 amd64_patch (is_not_zero_check, code);
4085                                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_CC_MASK);
4086
4087                                 amd64_patch (end_jump, code);
4088                         }
4089                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4090                         break;
4091                 case OP_FBGE:
4092                         /* Branch if C013 == 100 or 001 */
4093                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4094                                 guchar *br1;
4095
4096                                 /* skip branch if C1=1 */
4097                                 br1 = code;
4098                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
4099                                 /* branch if (C0 | C3) = 1 */
4100                                 EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
4101                                 amd64_patch (br1, code);
4102                                 break;
4103                         }
4104                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4105                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4106                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C3);
4107                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4108                         break;
4109                 case OP_FBGE_UN:
4110                         /* Branch if C013 == 000 */
4111                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4112                                 EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
4113                                 break;
4114                         }
4115                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4116                         break;
4117                 case OP_FBLE:
4118                         /* Branch if C013=000 or 100 */
4119                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4120                                 guchar *br1;
4121
4122                                 /* skip branch if C1=1 */
4123                                 br1 = code;
4124                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
4125                                 /* branch if C0=0 */
4126                                 EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
4127                                 amd64_patch (br1, code);
4128                                 break;
4129                         }
4130                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, (X86_FP_C0|X86_FP_C1));
4131                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
4132                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
4133                         break;
4134                 case OP_FBLE_UN:
4135                         /* Branch if C013 != 001 */
4136                         if (use_sse2 || (cfg->opt & MONO_OPT_FCMOV)) {
4137                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
4138                                 EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
4139                                 break;
4140                         }
4141                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4142                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
4143                         break;
4144                 case OP_CKFINITE: {
4145                         if (use_sse2) {
4146                                 /* Transfer value to the fp stack */
4147                                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 16);
4148                                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, ins->sreg1);
4149                                 amd64_fld_membase (code, AMD64_RSP, 0, TRUE);
4150                         }
4151                         amd64_push_reg (code, AMD64_RAX);
4152                         amd64_fxam (code);
4153                         amd64_fnstsw (code);
4154                         amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0x4100);
4155                         amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, X86_FP_C0);
4156                         amd64_pop_reg (code, AMD64_RAX);
4157                         if (use_sse2) {
4158                                 amd64_fstp (code, 0);
4159                         }                               
4160                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
4161                         if (use_sse2)
4162                                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 16);
4163                         break;
4164                 }
4165                 case OP_TLS_GET: {
4166                         code = emit_tls_get (code, ins->dreg, ins->inst_offset);
4167                         break;
4168                 }
4169                 case OP_MEMORY_BARRIER: {
4170                         /* Not needed on amd64 */
4171                         break;
4172                 }
4173                 case OP_ATOMIC_ADD_I4:
4174                 case OP_ATOMIC_ADD_I8: {
4175                         int dreg = ins->dreg;
4176                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_I4) ? 4 : 8;
4177
4178                         if (dreg == ins->inst_basereg)
4179                                 dreg = AMD64_R11;
4180                         
4181                         if (dreg != ins->sreg2)
4182                                 amd64_mov_reg_reg (code, ins->dreg, ins->sreg2, size);
4183
4184                         x86_prefix (code, X86_LOCK_PREFIX);
4185                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
4186
4187                         if (dreg != ins->dreg)
4188                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
4189
4190                         break;
4191                 }
4192                 case OP_ATOMIC_ADD_NEW_I4:
4193                 case OP_ATOMIC_ADD_NEW_I8: {
4194                         int dreg = ins->dreg;
4195                         guint32 size = (ins->opcode == OP_ATOMIC_ADD_NEW_I4) ? 4 : 8;
4196
4197                         if ((dreg == ins->sreg2) || (dreg == ins->inst_basereg))
4198                                 dreg = AMD64_R11;
4199
4200                         amd64_mov_reg_reg (code, dreg, ins->sreg2, size);
4201                         amd64_prefix (code, X86_LOCK_PREFIX);
4202                         amd64_xadd_membase_reg (code, ins->inst_basereg, ins->inst_offset, dreg, size);
4203                         /* dreg contains the old value, add with sreg2 value */
4204                         amd64_alu_reg_reg_size (code, X86_ADD, dreg, ins->sreg2, size);
4205                         
4206                         if (ins->dreg != dreg)
4207                                 amd64_mov_reg_reg (code, ins->dreg, dreg, size);
4208
4209                         break;
4210                 }
4211                 case OP_ATOMIC_EXCHANGE_I4:
4212                 case OP_ATOMIC_EXCHANGE_I8: {
4213                         guchar *br[2];
4214                         int sreg2 = ins->sreg2;
4215                         int breg = ins->inst_basereg;
4216                         guint32 size = (ins->opcode == OP_ATOMIC_EXCHANGE_I4) ? 4 : 8;
4217
4218                         /* 
4219                          * See http://msdn.microsoft.com/msdnmag/issues/0700/Win32/ for
4220                          * an explanation of how this works.
4221                          */
4222
4223                         /* cmpxchg uses eax as comperand, need to make sure we can use it
4224                          * hack to overcome limits in x86 reg allocator 
4225                          * (req: dreg == eax and sreg2 != eax and breg != eax) 
4226                          */
4227                         /* The pushes invalidate rsp */
4228                         if ((breg == AMD64_RAX) || (breg == AMD64_RSP)) {
4229                                 amd64_mov_reg_reg (code, AMD64_R11, breg, 8);
4230                                 breg = AMD64_R11;
4231                         }
4232
4233                         if (ins->dreg != AMD64_RAX)
4234                                 amd64_push_reg (code, AMD64_RAX);
4235                         
4236                         /* We need the EAX reg for the cmpxchg */
4237                         if (ins->sreg2 == AMD64_RAX) {
4238                                 amd64_push_reg (code, AMD64_RDX);
4239                                 amd64_mov_reg_reg (code, AMD64_RDX, AMD64_RAX, size);
4240                                 sreg2 = AMD64_RDX;
4241                         }
4242
4243                         amd64_mov_reg_membase (code, AMD64_RAX, breg, ins->inst_offset, size);
4244
4245                         br [0] = code; amd64_prefix (code, X86_LOCK_PREFIX);
4246                         amd64_cmpxchg_membase_reg_size (code, breg, ins->inst_offset, sreg2, size);
4247                         br [1] = code; amd64_branch8 (code, X86_CC_NE, -1, FALSE);
4248                         amd64_patch (br [1], br [0]);
4249
4250                         if (ins->dreg != AMD64_RAX) {
4251                                 amd64_mov_reg_reg (code, ins->dreg, AMD64_RAX, size);
4252                                 amd64_pop_reg (code, AMD64_RAX);
4253                         }
4254
4255                         if (ins->sreg2 != sreg2)
4256                                 amd64_pop_reg (code, AMD64_RDX);
4257
4258                         break;
4259                 }
4260                 default:
4261                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
4262                         g_assert_not_reached ();
4263                 }
4264
4265                 if ((code - cfg->native_code - offset) > max_len) {
4266                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %ld)",
4267                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
4268                         g_assert_not_reached ();
4269                 }
4270                
4271                 cpos += max_len;
4272
4273                 last_offset = offset;
4274         }
4275
4276         cfg->code_len = code - cfg->native_code;
4277 }
4278
4279 void
4280 mono_arch_register_lowlevel_calls (void)
4281 {
4282 }
4283
4284 void
4285 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gboolean run_cctors)
4286 {
4287         MonoJumpInfo *patch_info;
4288         gboolean compile_aot = !run_cctors;
4289
4290         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
4291                 unsigned char *ip = patch_info->ip.i + code;
4292                 const unsigned char *target;
4293
4294                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
4295
4296                 if (compile_aot) {
4297                         switch (patch_info->type) {
4298                         case MONO_PATCH_INFO_BB:
4299                         case MONO_PATCH_INFO_LABEL:
4300                                 break;
4301                         default:
4302                                 /* No need to patch these */
4303                                 continue;
4304                         }
4305                 }
4306
4307                 switch (patch_info->type) {
4308                 case MONO_PATCH_INFO_NONE:
4309                         continue;
4310                 case MONO_PATCH_INFO_METHOD_REL:
4311                 case MONO_PATCH_INFO_R8:
4312                 case MONO_PATCH_INFO_R4:
4313                         g_assert_not_reached ();
4314                         continue;
4315                 case MONO_PATCH_INFO_BB:
4316                         break;
4317                 default:
4318                         break;
4319                 }
4320
4321                 /* 
4322                  * Debug code to help track down problems where the target of a near call is
4323                  * is not valid.
4324                  */
4325                 if (amd64_is_near_call (ip)) {
4326                         gint64 disp = (guint8*)target - (guint8*)ip;
4327
4328                         if (!amd64_is_imm32 (disp)) {
4329                                 printf ("TYPE: %d\n", patch_info->type);
4330                                 switch (patch_info->type) {
4331                                 case MONO_PATCH_INFO_INTERNAL_METHOD:
4332                                         printf ("V: %s\n", patch_info->data.name);
4333                                         break;
4334                                 case MONO_PATCH_INFO_METHOD_JUMP:
4335                                 case MONO_PATCH_INFO_METHOD:
4336                                         printf ("V: %s\n", patch_info->data.method->name);
4337                                         break;
4338                                 default:
4339                                         break;
4340                                 }
4341                         }
4342                 }
4343
4344                 amd64_patch (ip, (gpointer)target);
4345         }
4346 }
4347
4348 /*
4349  * This macro is used for testing whenever the unwinder works correctly at every point
4350  * where an async exception can happen.
4351  */
4352 /* This will generate a SIGSEGV at the given point in the code */
4353 #define async_exc_point(code) do { \
4354     if (mono_inject_async_exc_method && mono_method_desc_full_match (mono_inject_async_exc_method, cfg->method)) { \
4355          if (cfg->arch.async_point_count == mono_inject_async_exc_pos) \
4356              amd64_mov_reg_mem (code, AMD64_RAX, 0, 4); \
4357          cfg->arch.async_point_count ++; \
4358     } \
4359 } while (0)
4360
4361 guint8 *
4362 mono_arch_emit_prolog (MonoCompile *cfg)
4363 {
4364         MonoMethod *method = cfg->method;
4365         MonoBasicBlock *bb;
4366         MonoMethodSignature *sig;
4367         MonoInst *ins;
4368         int alloc_size, pos, max_offset, i, quad;
4369         guint8 *code;
4370         CallInfo *cinfo;
4371         gint32 lmf_offset = cfg->arch.lmf_offset;
4372         gboolean args_clobbered = FALSE;
4373
4374         cfg->code_size =  MAX (((MonoMethodNormal *)method)->header->code_size * 4, 10240);
4375
4376         code = cfg->native_code = g_malloc (cfg->code_size);
4377
4378         /* Amount of stack space allocated by register saving code */
4379         pos = 0;
4380
4381         /* 
4382          * The prolog consists of the following parts:
4383          * FP present:
4384          * - push rbp, mov rbp, rsp
4385          * - save callee saved regs using pushes
4386          * - allocate frame
4387          * - save lmf if needed
4388          * FP not present:
4389          * - allocate frame
4390          * - save lmf if needed
4391          * - save callee saved regs using moves
4392          */
4393
4394         async_exc_point (code);
4395
4396         if (!cfg->arch.omit_fp) {
4397                 amd64_push_reg (code, AMD64_RBP);
4398                 async_exc_point (code);
4399                 amd64_mov_reg_reg (code, AMD64_RBP, AMD64_RSP, sizeof (gpointer));
4400                 async_exc_point (code);
4401         }
4402
4403         /* Save callee saved registers */
4404         if (!cfg->arch.omit_fp && !method->save_lmf) {
4405                 for (i = 0; i < AMD64_NREG; ++i)
4406                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4407                                 amd64_push_reg (code, i);
4408                                 pos += sizeof (gpointer);
4409                                 async_exc_point (code);
4410                         }
4411         }
4412
4413         if (cfg->arch.omit_fp) {
4414                 /* 
4415                  * On enter, the stack is misaligned by the the pushing of the return
4416                  * address. It is either made aligned by the pushing of %rbp, or by
4417                  * this.
4418                  */
4419                 alloc_size = ALIGN_TO (cfg->stack_offset, 8);
4420                 if ((alloc_size % 16) == 0)
4421                         alloc_size += 8;
4422         } else {
4423                 alloc_size = ALIGN_TO (cfg->stack_offset, MONO_ARCH_FRAME_ALIGNMENT);
4424
4425                 alloc_size -= pos;
4426         }
4427
4428         cfg->arch.stack_alloc_size = alloc_size;
4429
4430         /* Allocate stack frame */
4431         if (alloc_size) {
4432                 /* See mono_emit_stack_alloc */
4433 #if defined(PLATFORM_WIN32) || defined(MONO_ARCH_SIGSEGV_ON_ALTSTACK)
4434                 guint32 remaining_size = alloc_size;
4435                 while (remaining_size >= 0x1000) {
4436                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 0x1000);
4437                         async_exc_point (code);
4438                         amd64_test_membase_reg (code, AMD64_RSP, 0, AMD64_RSP);
4439                         remaining_size -= 0x1000;
4440                 }
4441                 if (remaining_size) {
4442                         amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, remaining_size);
4443                         async_exc_point (code);
4444                 }
4445 #else
4446                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, alloc_size);
4447                 async_exc_point (code);
4448 #endif
4449         }
4450
4451         /* Stack alignment check */
4452 #if 0
4453         {
4454                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_RSP, 8);
4455                 amd64_alu_reg_imm (code, X86_AND, AMD64_RAX, 0xf);
4456                 amd64_alu_reg_imm (code, X86_CMP, AMD64_RAX, 0);
4457                 x86_branch8 (code, X86_CC_EQ, 2, FALSE);
4458                 amd64_breakpoint (code);
4459         }
4460 #endif
4461
4462         /* Save LMF */
4463         if (method->save_lmf) {
4464                 /* 
4465                  * The ip field is not set, the exception handling code will obtain it from the stack location pointed to by the sp field.
4466                  */
4467                 /* sp is saved right before calls */
4468                 /* Skip method (only needed for trampoline LMF frames) */
4469                 /* Save callee saved regs */
4470                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), AMD64_RBX, 8);
4471                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), AMD64_RBP, 8);
4472                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), AMD64_R12, 8);
4473                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), AMD64_R13, 8);
4474                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), AMD64_R14, 8);
4475                 amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), AMD64_R15, 8);
4476         }
4477
4478         /* Save callee saved registers */
4479         if (cfg->arch.omit_fp && !method->save_lmf) {
4480                 gint32 save_area_offset = 0;
4481
4482                 /* Save caller saved registers after sp is adjusted */
4483                 /* The registers are saved at the bottom of the frame */
4484                 /* FIXME: Optimize this so the regs are saved at the end of the frame in increasing order */
4485                 for (i = 0; i < AMD64_NREG; ++i)
4486                         if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4487                                 amd64_mov_membase_reg (code, AMD64_RSP, save_area_offset, i, 8);
4488                                 save_area_offset += 8;
4489                                 async_exc_point (code);
4490                         }
4491         }
4492
4493         /* compute max_offset in order to use short forward jumps */
4494         max_offset = 0;
4495         if (cfg->opt & MONO_OPT_BRANCH) {
4496                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4497                         bb->max_offset = max_offset;
4498
4499                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
4500                                 max_offset += 6;
4501                         /* max alignment for loops */
4502                         if ((cfg->opt & MONO_OPT_LOOP) && bb_is_loop_start (bb))
4503                                 max_offset += LOOP_ALIGNMENT;
4504
4505                         MONO_BB_FOR_EACH_INS (bb, ins) {
4506                                 if (ins->opcode == OP_LABEL)
4507                                         ins->inst_c1 = max_offset;
4508                                 
4509                                 max_offset += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN];
4510                         }
4511                 }
4512         }
4513
4514         sig = mono_method_signature (method);
4515         pos = 0;
4516
4517         cinfo = cfg->arch.cinfo;
4518
4519         if (sig->ret->type != MONO_TYPE_VOID) {
4520                 if ((cinfo->ret.storage == ArgInIReg) && (cfg->ret->opcode != OP_REGVAR)) {
4521                         /* Save volatile arguments to the stack */
4522                         amd64_mov_membase_reg (code, cfg->ret->inst_basereg, cfg->ret->inst_offset, cinfo->ret.reg, 8);
4523                 }
4524         }
4525
4526         /* Keep this in sync with emit_load_volatile_arguments */
4527         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4528                 ArgInfo *ainfo = cinfo->args + i;
4529                 gint32 stack_offset;
4530                 MonoType *arg_type;
4531
4532                 ins = cfg->args [i];
4533
4534                 if (sig->hasthis && (i == 0))
4535                         arg_type = &mono_defaults.object_class->byval_arg;
4536                 else
4537                         arg_type = sig->params [i - sig->hasthis];
4538
4539                 stack_offset = ainfo->offset + ARGS_OFFSET;
4540
4541                 /* Save volatile arguments to the stack */
4542                 if (ins->opcode != OP_REGVAR) {
4543                         switch (ainfo->storage) {
4544                         case ArgInIReg: {
4545                                 guint32 size = 8;
4546
4547                                 /* FIXME: I1 etc */
4548                                 /*
4549                                 if (stack_offset & 0x1)
4550                                         size = 1;
4551                                 else if (stack_offset & 0x2)
4552                                         size = 2;
4553                                 else if (stack_offset & 0x4)
4554                                         size = 4;
4555                                 else
4556                                         size = 8;
4557                                 */
4558                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg, size);
4559                                 break;
4560                         }
4561                         case ArgInFloatSSEReg:
4562                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
4563                                 break;
4564                         case ArgInDoubleSSEReg:
4565                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset, ainfo->reg);
4566                                 break;
4567                         case ArgValuetypeInReg:
4568                                 for (quad = 0; quad < 2; quad ++) {
4569                                         switch (ainfo->pair_storage [quad]) {
4570                                         case ArgInIReg:
4571                                                 amd64_mov_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), ainfo->pair_regs [quad], sizeof (gpointer));
4572                                                 break;
4573                                         case ArgInFloatSSEReg:
4574                                                 amd64_movss_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), ainfo->pair_regs [quad]);
4575                                                 break;
4576                                         case ArgInDoubleSSEReg:
4577                                                 amd64_movsd_membase_reg (code, ins->inst_basereg, ins->inst_offset + (quad * sizeof (gpointer)), ainfo->pair_regs [quad]);
4578                                                 break;
4579                                         case ArgNone:
4580                                                 break;
4581                                         default:
4582                                                 g_assert_not_reached ();
4583                                         }
4584                                 }
4585                                 break;
4586                         default:
4587                                 break;
4588                         }
4589                 } else {
4590                         /* Argument allocated to (non-volatile) register */
4591                         switch (ainfo->storage) {
4592                         case ArgInIReg:
4593                                 amd64_mov_reg_reg (code, ins->dreg, ainfo->reg, 8);
4594                                 break;
4595                         case ArgOnStack:
4596                                 amd64_mov_reg_membase (code, ins->dreg, AMD64_RBP, ARGS_OFFSET + ainfo->offset, 8);
4597                                 break;
4598                         default:
4599                                 g_assert_not_reached ();
4600                         }
4601                 }
4602         }
4603
4604         /* Might need to attach the thread to the JIT  or change the domain for the callback */
4605         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
4606                 guint64 domain = (guint64)cfg->domain;
4607
4608                 args_clobbered = TRUE;
4609
4610                 /* 
4611                  * The call might clobber argument registers, but they are already
4612                  * saved to the stack/global regs.
4613                  */
4614                 if (appdomain_tls_offset != -1 && lmf_tls_offset != -1) {
4615                         guint8 *buf, *no_domain_branch;
4616
4617                         code = emit_tls_get (code, AMD64_RAX, appdomain_tls_offset);
4618                         if ((domain >> 32) == 0)
4619                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 4);
4620                         else
4621                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 8);
4622                         amd64_alu_reg_reg (code, X86_CMP, AMD64_RAX, AMD64_ARG_REG1);
4623                         no_domain_branch = code;
4624                         x86_branch8 (code, X86_CC_NE, 0, 0);
4625                         code = emit_tls_get ( code, AMD64_RAX, lmf_addr_tls_offset);
4626                         amd64_test_reg_reg (code, AMD64_RAX, AMD64_RAX);
4627                         buf = code;
4628                         x86_branch8 (code, X86_CC_NE, 0, 0);
4629                         amd64_patch (no_domain_branch, code);
4630                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_jit_thread_attach");
4631                         amd64_patch (buf, code);
4632                 } else {
4633                         g_assert (!cfg->compile_aot);
4634                         if ((domain >> 32) == 0)
4635                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 4);
4636                         else
4637                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG1, domain, 8);
4638                         code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_jit_thread_attach");
4639                 }
4640         }
4641
4642         if (method->save_lmf) {
4643                 if ((lmf_tls_offset != -1) && !optimize_for_xen) {
4644                         /*
4645                          * Optimized version which uses the mono_lmf TLS variable instead of indirection
4646                          * through the mono_lmf_addr TLS variable.
4647                          */
4648                         /* %rax = previous_lmf */
4649                         x86_prefix (code, X86_FS_PREFIX);
4650                         amd64_mov_reg_mem (code, AMD64_RAX, lmf_tls_offset, 8);
4651
4652                         /* Save previous_lmf */
4653                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_RAX, 8);
4654                         /* Set new lmf */
4655                         if (lmf_offset == 0) {
4656                                 x86_prefix (code, X86_FS_PREFIX);
4657                                 amd64_mov_mem_reg (code, lmf_tls_offset, cfg->frame_reg, 8);
4658                         } else {
4659                                 amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
4660                                 x86_prefix (code, X86_FS_PREFIX);
4661                                 amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
4662                         }
4663                 } else {
4664                         if (lmf_addr_tls_offset != -1) {
4665                                 /* Load lmf quicky using the FS register */
4666                                 code = emit_tls_get (code, AMD64_RAX, lmf_addr_tls_offset);
4667                         }
4668                         else {
4669                                 /* 
4670                                  * The call might clobber argument registers, but they are already
4671                                  * saved to the stack/global regs.
4672                                  */
4673                                 args_clobbered = TRUE;
4674                                 code = emit_call (cfg, code, MONO_PATCH_INFO_INTERNAL_METHOD, 
4675                                                                   (gpointer)"mono_get_lmf_addr");               
4676                         }
4677
4678                         /* Save lmf_addr */
4679                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), AMD64_RAX, 8);
4680                         /* Save previous_lmf */
4681                         amd64_mov_reg_membase (code, AMD64_R11, AMD64_RAX, 0, 8);
4682                         amd64_mov_membase_reg (code, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), AMD64_R11, 8);
4683                         /* Set new lmf */
4684                         amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset);
4685                         amd64_mov_membase_reg (code, AMD64_RAX, 0, AMD64_R11, 8);
4686                 }
4687         }
4688
4689         if (mono_jit_trace_calls != NULL && mono_trace_eval (method)) {
4690                 args_clobbered = TRUE;
4691                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
4692         }
4693
4694         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4695                 args_clobbered = TRUE;
4696
4697         /*
4698          * Optimize the common case of the first bblock making a call with the same
4699          * arguments as the method. This works because the arguments are still in their
4700          * original argument registers.
4701          * FIXME: Generalize this
4702          */
4703         if (!args_clobbered) {
4704                 MonoBasicBlock *first_bb = cfg->bb_entry;
4705                 MonoInst *next;
4706
4707                 next = mono_inst_list_first (&first_bb->ins_list);
4708                 if (!next && first_bb->next_bb) {
4709                         first_bb = first_bb->next_bb;
4710                         next = mono_inst_list_first (&first_bb->ins_list);
4711                 }
4712
4713                 if (first_bb->in_count > 1)
4714                         next = NULL;
4715
4716                 for (i = 0; next && i < sig->param_count + sig->hasthis; ++i) {
4717                         ArgInfo *ainfo = cinfo->args + i;
4718                         gboolean match = FALSE;
4719                         
4720                         ins = cfg->args [i];
4721                         if (ins->opcode != OP_REGVAR) {
4722                                 switch (ainfo->storage) {
4723                                 case ArgInIReg: {
4724                                         if (((next->opcode == OP_LOAD_MEMBASE) || (next->opcode == OP_LOADI4_MEMBASE)) && next->inst_basereg == ins->inst_basereg && next->inst_offset == ins->inst_offset) {
4725                                                 if (next->dreg == ainfo->reg)
4726                                                         NULLIFY_INS (next);
4727                                                 else {
4728                                                         next->opcode = OP_MOVE;
4729                                                         next->sreg1 = ainfo->reg;
4730                                                 }
4731                                                 /* Only continue if the instruction doesn't change argument regs */
4732                                                 if (next->dreg == ainfo->reg || next->dreg == AMD64_RAX)
4733                                                         match = TRUE;
4734                                         }
4735                                         break;
4736                                 }
4737                                 default:
4738                                         break;
4739                                 }
4740                         } else {
4741                                 /* Argument allocated to (non-volatile) register */
4742                                 switch (ainfo->storage) {
4743                                 case ArgInIReg:
4744                                         if (next->opcode == OP_MOVE && next->sreg1 == ins->dreg && next->dreg == ainfo->reg) {
4745                                                 NULLIFY_INS (next);
4746                                                 match = TRUE;
4747                                         }
4748                                         break;
4749                                 default:
4750                                         break;
4751                                 }
4752                         }
4753
4754                         if (!match)
4755                                 break;
4756                         next = mono_inst_list_next (&next->node, &first_bb->ins_list);
4757                 }
4758         }
4759
4760         cfg->code_len = code - cfg->native_code;
4761
4762         g_assert (cfg->code_len < cfg->code_size);
4763
4764         return code;
4765 }
4766
4767 void
4768 mono_arch_emit_epilog (MonoCompile *cfg)
4769 {
4770         MonoMethod *method = cfg->method;
4771         int quad, pos, i;
4772         guint8 *code;
4773         int max_epilog_size = 16;
4774         CallInfo *cinfo;
4775         gint32 lmf_offset = cfg->arch.lmf_offset;
4776         
4777         if (cfg->method->save_lmf)
4778                 max_epilog_size += 256;
4779         
4780         if (mono_jit_trace_calls != NULL)
4781                 max_epilog_size += 50;
4782
4783         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
4784                 max_epilog_size += 50;
4785
4786         max_epilog_size += (AMD64_NREG * 2);
4787
4788         while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) {
4789                 cfg->code_size *= 2;
4790                 cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
4791                 mono_jit_stats.code_reallocs++;
4792         }
4793
4794         code = cfg->native_code + cfg->code_len;
4795
4796         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
4797                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
4798
4799         /* the code restoring the registers must be kept in sync with OP_JMP */
4800         pos = 0;
4801         
4802         if (method->save_lmf) {
4803                 if ((lmf_tls_offset != -1) && !optimize_for_xen) {
4804                         /*
4805                          * Optimized version which uses the mono_lmf TLS variable instead of indirection
4806                          * through the mono_lmf_addr TLS variable.
4807                          */
4808                         /* reg = previous_lmf */
4809                         amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), 8);
4810                         x86_prefix (code, X86_FS_PREFIX);
4811                         amd64_mov_mem_reg (code, lmf_tls_offset, AMD64_R11, 8);
4812                 } else {
4813                         /* Restore previous lmf */
4814                         amd64_mov_reg_membase (code, AMD64_RCX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, previous_lmf), 8);
4815                         amd64_mov_reg_membase (code, AMD64_R11, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, lmf_addr), 8);
4816                         amd64_mov_membase_reg (code, AMD64_R11, 0, AMD64_RCX, 8);
4817                 }
4818
4819                 /* Restore caller saved regs */
4820                 if (cfg->used_int_regs & (1 << AMD64_RBP)) {
4821                         amd64_mov_reg_membase (code, AMD64_RBP, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbp), 8);
4822                 }
4823                 if (cfg->used_int_regs & (1 << AMD64_RBX)) {
4824                         amd64_mov_reg_membase (code, AMD64_RBX, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, rbx), 8);
4825                 }
4826                 if (cfg->used_int_regs & (1 << AMD64_R12)) {
4827                         amd64_mov_reg_membase (code, AMD64_R12, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r12), 8);
4828                 }
4829                 if (cfg->used_int_regs & (1 << AMD64_R13)) {
4830                         amd64_mov_reg_membase (code, AMD64_R13, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r13), 8);
4831                 }
4832                 if (cfg->used_int_regs & (1 << AMD64_R14)) {
4833                         amd64_mov_reg_membase (code, AMD64_R14, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r14), 8);
4834                 }
4835                 if (cfg->used_int_regs & (1 << AMD64_R15)) {
4836                         amd64_mov_reg_membase (code, AMD64_R15, cfg->frame_reg, lmf_offset + G_STRUCT_OFFSET (MonoLMF, r15), 8);
4837                 }
4838         } else {
4839
4840                 if (cfg->arch.omit_fp) {
4841                         gint32 save_area_offset = 0;
4842
4843                         for (i = 0; i < AMD64_NREG; ++i)
4844                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4845                                         amd64_mov_reg_membase (code, i, AMD64_RSP, save_area_offset, 8);
4846                                         save_area_offset += 8;
4847                                 }
4848                 }
4849                 else {
4850                         for (i = 0; i < AMD64_NREG; ++i)
4851                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i)))
4852                                         pos -= sizeof (gpointer);
4853
4854                         if (pos) {
4855                                 if (pos == - sizeof (gpointer)) {
4856                                         /* Only one register, so avoid lea */
4857                                         for (i = AMD64_NREG - 1; i > 0; --i)
4858                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4859                                                         amd64_mov_reg_membase (code, i, AMD64_RBP, pos, 8);
4860                                                 }
4861                                 }
4862                                 else {
4863                                         amd64_lea_membase (code, AMD64_RSP, AMD64_RBP, pos);
4864
4865                                         /* Pop registers in reverse order */
4866                                         for (i = AMD64_NREG - 1; i > 0; --i)
4867                                                 if (AMD64_IS_CALLEE_SAVED_REG (i) && (cfg->used_int_regs & (1 << i))) {
4868                                                         amd64_pop_reg (code, i);
4869                                                 }
4870                                 }
4871                         }
4872                 }
4873         }
4874
4875         /* Load returned vtypes into registers if needed */
4876         cinfo = cfg->arch.cinfo;
4877         if (cinfo->ret.storage == ArgValuetypeInReg) {
4878                 ArgInfo *ainfo = &cinfo->ret;
4879                 MonoInst *inst = cfg->ret;
4880
4881                 for (quad = 0; quad < 2; quad ++) {
4882                         switch (ainfo->pair_storage [quad]) {
4883                         case ArgInIReg:
4884                                 amd64_mov_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof (gpointer)), sizeof (gpointer));
4885                                 break;
4886                         case ArgInFloatSSEReg:
4887                                 amd64_movss_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof (gpointer)));
4888                                 break;
4889                         case ArgInDoubleSSEReg:
4890                                 amd64_movsd_reg_membase (code, ainfo->pair_regs [quad], inst->inst_basereg, inst->inst_offset + (quad * sizeof (gpointer)));
4891                                 break;
4892                         case ArgNone:
4893                                 break;
4894                         default:
4895                                 g_assert_not_reached ();
4896                         }
4897                 }
4898         }
4899
4900         if (cfg->arch.omit_fp) {
4901                 if (cfg->arch.stack_alloc_size)
4902                         amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, cfg->arch.stack_alloc_size);
4903         } else {
4904                 amd64_leave (code);
4905         }
4906         async_exc_point (code);
4907         amd64_ret (code);
4908
4909         cfg->code_len = code - cfg->native_code;
4910
4911         g_assert (cfg->code_len < cfg->code_size);
4912
4913         if (cfg->arch.omit_fp) {
4914                 /* 
4915                  * Encode the stack size into used_int_regs so the exception handler
4916                  * can access it.
4917                  */
4918                 g_assert (cfg->arch.stack_alloc_size < (1 << 16));
4919                 cfg->used_int_regs |= (1 << 31) | (cfg->arch.stack_alloc_size << 16);
4920         }
4921 }
4922
4923 void
4924 mono_arch_emit_exceptions (MonoCompile *cfg)
4925 {
4926         MonoJumpInfo *patch_info;
4927         int nthrows, i;
4928         guint8 *code;
4929         MonoClass *exc_classes [16];
4930         guint8 *exc_throw_start [16], *exc_throw_end [16];
4931         guint32 code_size = 0;
4932
4933         /* Compute needed space */
4934         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4935                 if (patch_info->type == MONO_PATCH_INFO_EXC)
4936                         code_size += 40;
4937                 if (patch_info->type == MONO_PATCH_INFO_R8)
4938                         code_size += 8 + 15; /* sizeof (double) + alignment */
4939                 if (patch_info->type == MONO_PATCH_INFO_R4)
4940                         code_size += 4 + 15; /* sizeof (float) + alignment */
4941         }
4942
4943         while (cfg->code_len + code_size > (cfg->code_size - 16)) {
4944                 cfg->code_size *= 2;
4945                 cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
4946                 mono_jit_stats.code_reallocs++;
4947         }
4948
4949         code = cfg->native_code + cfg->code_len;
4950
4951         /* add code to raise exceptions */
4952         nthrows = 0;
4953         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4954                 switch (patch_info->type) {
4955                 case MONO_PATCH_INFO_EXC: {
4956                         MonoClass *exc_class;
4957                         guint8 *buf, *buf2;
4958                         guint32 throw_ip;
4959
4960                         amd64_patch (patch_info->ip.i + cfg->native_code, code);
4961
4962                         exc_class = mono_class_from_name (mono_defaults.corlib, "System", patch_info->data.name);
4963                         g_assert (exc_class);
4964                         throw_ip = patch_info->ip.i;
4965
4966                         //x86_breakpoint (code);
4967                         /* Find a throw sequence for the same exception class */
4968                         for (i = 0; i < nthrows; ++i)
4969                                 if (exc_classes [i] == exc_class)
4970                                         break;
4971                         if (i < nthrows) {
4972                                 amd64_mov_reg_imm (code, AMD64_ARG_REG2, (exc_throw_end [i] - cfg->native_code) - throw_ip);
4973                                 x86_jump_code (code, exc_throw_start [i]);
4974                                 patch_info->type = MONO_PATCH_INFO_NONE;
4975                         }
4976                         else {
4977                                 buf = code;
4978                                 amd64_mov_reg_imm_size (code, AMD64_ARG_REG2, 0xf0f0f0f0, 4);
4979                                 buf2 = code;
4980
4981                                 if (nthrows < 16) {
4982                                         exc_classes [nthrows] = exc_class;
4983                                         exc_throw_start [nthrows] = code;
4984                                 }
4985                                 amd64_mov_reg_imm (code, AMD64_ARG_REG1, exc_class->type_token);
4986                                 patch_info->data.name = "mono_arch_throw_corlib_exception";
4987                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
4988                                 patch_info->ip.i = code - cfg->native_code;
4989
4990                                 code = emit_call_body (cfg, code, patch_info->type, patch_info->data.name);
4991
4992                                 amd64_mov_reg_imm (buf, AMD64_ARG_REG2, (code - cfg->native_code) - throw_ip);
4993                                 while (buf < buf2)
4994                                         x86_nop (buf);
4995
4996                                 if (nthrows < 16) {
4997                                         exc_throw_end [nthrows] = code;
4998                                         nthrows ++;
4999                                 }
5000                         }
5001                         break;
5002                 }
5003                 default:
5004                         /* do nothing */
5005                         break;
5006                 }
5007         }
5008
5009         /* Handle relocations with RIP relative addressing */
5010         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5011                 gboolean remove = FALSE;
5012
5013                 switch (patch_info->type) {
5014                 case MONO_PATCH_INFO_R8:
5015                 case MONO_PATCH_INFO_R4: {
5016                         guint8 *pos;
5017
5018                         if (use_sse2) {
5019                                 /* The SSE opcodes require a 16 byte alignment */
5020                                 code = (guint8*)ALIGN_TO (code, 16);
5021                         } else {
5022                                 code = (guint8*)ALIGN_TO (code, 8);
5023                         }
5024
5025                         pos = cfg->native_code + patch_info->ip.i;
5026
5027
5028                         if (use_sse2) {
5029                                 if (IS_REX (pos [1]))
5030                                         *(guint32*)(pos + 5) = (guint8*)code - pos - 9;
5031                                 else
5032                                         *(guint32*)(pos + 4) = (guint8*)code - pos - 8;
5033                         } else {
5034                                 *(guint32*)(pos + 3) = (guint8*)code - pos - 7;
5035                         }
5036
5037                         if (patch_info->type == MONO_PATCH_INFO_R8) {
5038                                 *(double*)code = *(double*)patch_info->data.target;
5039                                 code += sizeof (double);
5040                         } else {
5041                                 *(float*)code = *(float*)patch_info->data.target;
5042                                 code += sizeof (float);
5043                         }
5044
5045                         remove = TRUE;
5046                         break;
5047                 }
5048                 default:
5049                         break;
5050                 }
5051
5052                 if (remove) {
5053                         if (patch_info == cfg->patch_info)
5054                                 cfg->patch_info = patch_info->next;
5055                         else {
5056                                 MonoJumpInfo *tmp;
5057
5058                                 for (tmp = cfg->patch_info; tmp->next != patch_info; tmp = tmp->next)
5059                                         ;
5060                                 tmp->next = patch_info->next;
5061                         }
5062                 }
5063         }
5064
5065         cfg->code_len = code - cfg->native_code;
5066
5067         g_assert (cfg->code_len < cfg->code_size);
5068
5069 }
5070
5071 void*
5072 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
5073 {
5074         guchar *code = p;
5075         CallInfo *cinfo = NULL;
5076         MonoMethodSignature *sig;
5077         MonoInst *inst;
5078         int i, n, stack_area = 0;
5079
5080         /* Keep this in sync with mono_arch_get_argument_info */
5081
5082         if (enable_arguments) {
5083                 /* Allocate a new area on the stack and save arguments there */
5084                 sig = mono_method_signature (cfg->method);
5085
5086                 cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
5087
5088                 n = sig->param_count + sig->hasthis;
5089
5090                 stack_area = ALIGN_TO (n * 8, 16);
5091
5092                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, stack_area);
5093
5094                 for (i = 0; i < n; ++i) {
5095                         inst = cfg->args [i];
5096
5097                         if (inst->opcode == OP_REGVAR)
5098                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), inst->dreg, 8);
5099                         else {
5100                                 amd64_mov_reg_membase (code, AMD64_R11, inst->inst_basereg, inst->inst_offset, 8);
5101                                 amd64_mov_membase_reg (code, AMD64_RSP, (i * 8), AMD64_R11, 8);
5102                         }
5103                 }
5104         }
5105
5106         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
5107         amd64_set_reg_template (code, AMD64_ARG_REG1);
5108         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RSP, 8);
5109         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func);
5110
5111         if (enable_arguments)
5112                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, stack_area);
5113
5114         return code;
5115 }
5116
5117 enum {
5118         SAVE_NONE,
5119         SAVE_STRUCT,
5120         SAVE_EAX,
5121         SAVE_EAX_EDX,
5122         SAVE_XMM
5123 };
5124
5125 void*
5126 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
5127 {
5128         guchar *code = p;
5129         int save_mode = SAVE_NONE;
5130         MonoMethod *method = cfg->method;
5131         int rtype = mono_type_get_underlying_type (mono_method_signature (method)->ret)->type;
5132         
5133         switch (rtype) {
5134         case MONO_TYPE_VOID:
5135                 /* special case string .ctor icall */
5136                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
5137                         save_mode = SAVE_EAX;
5138                 else
5139                         save_mode = SAVE_NONE;
5140                 break;
5141         case MONO_TYPE_I8:
5142         case MONO_TYPE_U8:
5143                 save_mode = SAVE_EAX;
5144                 break;
5145         case MONO_TYPE_R4:
5146         case MONO_TYPE_R8:
5147                 save_mode = SAVE_XMM;
5148                 break;
5149         case MONO_TYPE_GENERICINST:
5150                 if (!mono_type_generic_inst_is_valuetype (mono_method_signature (method)->ret)) {
5151                         save_mode = SAVE_EAX;
5152                         break;
5153                 }
5154                 /* Fall through */
5155         case MONO_TYPE_VALUETYPE:
5156                 save_mode = SAVE_STRUCT;
5157                 break;
5158         default:
5159                 save_mode = SAVE_EAX;
5160                 break;
5161         }
5162
5163         /* Save the result and copy it into the proper argument register */
5164         switch (save_mode) {
5165         case SAVE_EAX:
5166                 amd64_push_reg (code, AMD64_RAX);
5167                 /* Align stack */
5168                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5169                 if (enable_arguments)
5170                         amd64_mov_reg_reg (code, AMD64_ARG_REG2, AMD64_RAX, 8);
5171                 break;
5172         case SAVE_STRUCT:
5173                 /* FIXME: */
5174                 if (enable_arguments)
5175                         amd64_mov_reg_imm (code, AMD64_ARG_REG2, 0);
5176                 break;
5177         case SAVE_XMM:
5178                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5179                 amd64_movsd_membase_reg (code, AMD64_RSP, 0, AMD64_XMM0);
5180                 /* Align stack */
5181                 amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
5182                 /* 
5183                  * The result is already in the proper argument register so no copying
5184                  * needed.
5185                  */
5186                 break;
5187         case SAVE_NONE:
5188                 break;
5189         default:
5190                 g_assert_not_reached ();
5191         }
5192
5193         /* Set %al since this is a varargs call */
5194         if (save_mode == SAVE_XMM)
5195                 amd64_mov_reg_imm (code, AMD64_RAX, 1);
5196         else
5197                 amd64_mov_reg_imm (code, AMD64_RAX, 0);
5198
5199         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
5200         amd64_set_reg_template (code, AMD64_ARG_REG1);
5201         code = emit_call (cfg, code, MONO_PATCH_INFO_ABS, (gpointer)func);
5202
5203         /* Restore result */
5204         switch (save_mode) {
5205         case SAVE_EAX:
5206                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5207                 amd64_pop_reg (code, AMD64_RAX);
5208                 break;
5209         case SAVE_STRUCT:
5210                 /* FIXME: */
5211                 break;
5212         case SAVE_XMM:
5213                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5214                 amd64_movsd_reg_membase (code, AMD64_XMM0, AMD64_RSP, 0);
5215                 amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
5216                 break;
5217         case SAVE_NONE:
5218                 break;
5219         default:
5220                 g_assert_not_reached ();
5221         }
5222
5223         return code;
5224 }
5225
5226 void
5227 mono_arch_flush_icache (guint8 *code, gint size)
5228 {
5229         /* Not needed */
5230 }
5231
5232 void
5233 mono_arch_flush_register_windows (void)
5234 {
5235 }
5236
5237 gboolean 
5238 mono_arch_is_inst_imm (gint64 imm)
5239 {
5240         return amd64_is_imm32 (imm);
5241 }
5242
5243 /*
5244  * Determine whenever the trap whose info is in SIGINFO is caused by
5245  * integer overflow.
5246  */
5247 gboolean
5248 mono_arch_is_int_overflow (void *sigctx, void *info)
5249 {
5250         MonoContext ctx;
5251         guint8* rip;
5252         int reg;
5253         gint64 value;
5254
5255         mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5256
5257         rip = (guint8*)ctx.rip;
5258
5259         if (IS_REX (rip [0])) {
5260                 reg = amd64_rex_b (rip [0]);
5261                 rip ++;
5262         }
5263         else
5264                 reg = 0;
5265
5266         if ((rip [0] == 0xf7) && (x86_modrm_mod (rip [1]) == 0x3) && (x86_modrm_reg (rip [1]) == 0x7)) {
5267                 /* idiv REG */
5268                 reg += x86_modrm_rm (rip [1]);
5269
5270                 switch (reg) {
5271                 case AMD64_RAX:
5272                         value = ctx.rax;
5273                         break;
5274                 case AMD64_RBX:
5275                         value = ctx.rbx;
5276                         break;
5277                 case AMD64_RCX:
5278                         value = ctx.rcx;
5279                         break;
5280                 case AMD64_RDX:
5281                         value = ctx.rdx;
5282                         break;
5283                 case AMD64_RBP:
5284                         value = ctx.rbp;
5285                         break;
5286                 case AMD64_RSP:
5287                         value = ctx.rsp;
5288                         break;
5289                 case AMD64_RSI:
5290                         value = ctx.rsi;
5291                         break;
5292                 case AMD64_RDI:
5293                         value = ctx.rdi;
5294                         break;
5295                 case AMD64_R12:
5296                         value = ctx.r12;
5297                         break;
5298                 case AMD64_R13:
5299                         value = ctx.r13;
5300                         break;
5301                 case AMD64_R14:
5302                         value = ctx.r14;
5303                         break;
5304                 case AMD64_R15:
5305                         value = ctx.r15;
5306                         break;
5307                 default:
5308                         g_assert_not_reached ();
5309                         reg = -1;
5310                 }                       
5311
5312                 if (value == -1)
5313                         return TRUE;
5314         }
5315
5316         return FALSE;
5317 }
5318
5319 guint32
5320 mono_arch_get_patch_offset (guint8 *code)
5321 {
5322         return 3;
5323 }
5324
5325 gboolean
5326 mono_breakpoint_clean_code (guint8 *code, guint8 *buf, int size)
5327 {
5328         int i;
5329         gboolean can_write = TRUE;
5330         memcpy (buf, code, size);
5331         for (i = 0; i < MONO_BREAKPOINT_ARRAY_SIZE; ++i) {
5332                 int idx = mono_breakpoint_info_index [i];
5333                 guint8 *ptr;
5334                 if (idx < 1)
5335                         continue;
5336                 ptr = mono_breakpoint_info [idx].address;
5337                 if (ptr >= code && ptr < code + size) {
5338                         guint8 saved_byte = mono_breakpoint_info [idx].saved_byte;
5339                         can_write = FALSE;
5340                         /*g_print ("patching %p with 0x%02x (was: 0x%02x)\n", ptr, saved_byte, buf [ptr - code]);*/
5341                         buf [ptr - code] = saved_byte;
5342                 }
5343         }
5344         return can_write;
5345 }
5346
5347 gpointer
5348 mono_arch_get_vcall_slot (guint8 *code, gpointer *regs, int *displacement)
5349 {
5350         guint8 buf [10];
5351         guint32 reg;
5352         gint32 disp;
5353         guint8 rex = 0;
5354
5355         mono_breakpoint_clean_code (code - 10, buf, sizeof (buf));
5356         code = buf + 10;
5357
5358         *displacement = 0;
5359
5360         /* go to the start of the call instruction
5361          *
5362          * address_byte = (m << 6) | (o << 3) | reg
5363          * call opcode: 0xff address_byte displacement
5364          * 0xff m=1,o=2 imm8
5365          * 0xff m=2,o=2 imm32
5366          */
5367         code -= 7;
5368
5369         /* 
5370          * A given byte sequence can match more than case here, so we have to be
5371          * really careful about the ordering of the cases. Longer sequences
5372          * come first.
5373          */
5374 #ifdef MONO_ARCH_HAVE_IMT
5375         if ((code [-2] == 0x41) && (code [-1] == 0xbb) && (code [4] == 0xff) && (x86_modrm_mod (code [5]) == 1) && (x86_modrm_reg (code [5]) == 2) && ((signed char)code [6] < 0)) {
5376                 /* IMT-based interface calls: with MONO_ARCH_IMT_REG == r11
5377                  * 41 bb 14 f8 28 08       mov    $0x828f814,%r11d
5378                  * ff 50 fc                call   *0xfffffffc(%rax)
5379                  */
5380                 reg = amd64_modrm_rm (code [5]);
5381                 disp = (signed char)code [6];
5382                 /* R10 is clobbered by the IMT thunk code */
5383                 g_assert (reg != AMD64_R10);
5384         }
5385 #else
5386         if (0) {
5387         }
5388 #endif
5389         else if ((code [-1] == 0x8b) && (amd64_modrm_mod (code [0]) == 0x2) && (code [5] == 0xff) && (amd64_modrm_reg (code [6]) == 0x2) && (amd64_modrm_mod (code [6]) == 0x0)) {
5390                         /*
5391                          * This is a interface call
5392                          * 48 8b 80 f0 e8 ff ff   mov    0xffffffffffffe8f0(%rax),%rax
5393                          * ff 10                  callq  *(%rax)
5394                          */
5395                 if (IS_REX (code [4]))
5396                         rex = code [4];
5397                 reg = amd64_modrm_rm (code [6]);
5398                 disp = 0;
5399                 /* R10 is clobbered by the IMT thunk code */
5400                 g_assert (reg != AMD64_R10);
5401         } else if ((code [0] == 0x41) && (code [1] == 0xff) && (code [2] == 0x15)) {
5402                 /* call OFFSET(%rip) */
5403                 disp = *(guint32*)(code + 3);
5404                 return (gpointer*)(code + disp + 7);
5405         }
5406         else if ((code [1] == 0xff) && (amd64_modrm_reg (code [2]) == 0x2) && (amd64_modrm_mod (code [2]) == 0x2)) {
5407                 /* call *[reg+disp32] */
5408                 if (IS_REX (code [0]))
5409                         rex = code [0];
5410                 reg = amd64_modrm_rm (code [2]);
5411                 disp = *(gint32*)(code + 3);
5412                 /* R10 is clobbered by the IMT thunk code */
5413                 g_assert (reg != AMD64_R10);
5414         }
5415         else if (code [2] == 0xe8) {
5416                 /* call <ADDR> */
5417                 return NULL;
5418         }
5419         else if (IS_REX (code [4]) && (code [5] == 0xff) && (amd64_modrm_reg (code [6]) == 0x2) && (amd64_modrm_mod (code [6]) == 0x3)) {
5420                 /* call *%reg */
5421                 return NULL;
5422         }
5423         else if ((code [4] == 0xff) && (amd64_modrm_reg (code [5]) == 0x2) && (amd64_modrm_mod (code [5]) == 0x1)) {
5424                 /* call *[reg+disp8] */
5425                 if (IS_REX (code [3]))
5426                         rex = code [3];
5427                 reg = amd64_modrm_rm (code [5]);
5428                 disp = *(gint8*)(code + 6);
5429                 //printf ("B: [%%r%d+0x%x]\n", reg, disp);
5430         }
5431         else if ((code [5] == 0xff) && (amd64_modrm_reg (code [6]) == 0x2) && (amd64_modrm_mod (code [6]) == 0x0)) {
5432                         /*
5433                          * This is a interface call: should check the above code can't catch it earlier 
5434                          * 8b 40 30   mov    0x30(%eax),%eax
5435                          * ff 10      call   *(%eax)
5436                          */
5437                 if (IS_REX (code [4]))
5438                         rex = code [4];
5439                 reg = amd64_modrm_rm (code [6]);
5440                 disp = 0;
5441         }
5442         else
5443                 g_assert_not_reached ();
5444
5445         reg += amd64_rex_b (rex);
5446
5447         /* R11 is clobbered by the trampoline code */
5448         g_assert (reg != AMD64_R11);
5449
5450         *displacement = disp;
5451         return regs [reg];
5452 }
5453
5454 gpointer*
5455 mono_arch_get_vcall_slot_addr (guint8* code, gpointer *regs)
5456 {
5457         gpointer vt;
5458         int displacement;
5459         vt = mono_arch_get_vcall_slot (code, regs, &displacement);
5460         if (!vt)
5461                 return NULL;
5462         return (gpointer*)((char*)vt + displacement);
5463 }
5464
5465 gpointer
5466 mono_arch_get_this_arg_from_call (MonoMethodSignature *sig, gssize *regs, guint8 *code)
5467 {
5468         if (MONO_TYPE_ISSTRUCT (sig->ret))
5469                 return (gpointer)regs [AMD64_ARG_REG2];
5470         else
5471                 return (gpointer)regs [AMD64_ARG_REG1];
5472 }
5473
5474 #define MAX_ARCH_DELEGATE_PARAMS 10
5475
5476 gpointer
5477 mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
5478 {
5479         guint8 *code, *start;
5480         int i;
5481
5482         if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
5483                 return NULL;
5484
5485         /* FIXME: Support more cases */
5486         if (MONO_TYPE_ISSTRUCT (sig->ret))
5487                 return NULL;
5488
5489         if (has_target) {
5490                 static guint8* cached = NULL;
5491                 mono_mini_arch_lock ();
5492                 if (cached) {
5493                         mono_mini_arch_unlock ();
5494                         return cached;
5495                 }
5496
5497                 start = code = mono_global_codeman_reserve (64);
5498
5499                 /* Replace the this argument with the target */
5500                 amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
5501                 amd64_mov_reg_membase (code, AMD64_ARG_REG1, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, target), 8);
5502                 amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
5503
5504                 g_assert ((code - start) < 64);
5505
5506                 cached = start;
5507                 mono_debug_add_delegate_trampoline (start, code - start);
5508                 mono_mini_arch_unlock ();
5509         } else {
5510                 static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
5511                 for (i = 0; i < sig->param_count; ++i)
5512                         if (!mono_is_regsize_var (sig->params [i]))
5513                                 return NULL;
5514                 if (sig->param_count > 4)
5515                         return NULL;
5516
5517                 mono_mini_arch_lock ();
5518                 code = cache [sig->param_count];
5519                 if (code) {
5520                         mono_mini_arch_unlock ();
5521                         return code;
5522                 }
5523
5524                 start = code = mono_global_codeman_reserve (64);
5525
5526                 if (sig->param_count == 0) {
5527                         amd64_jump_membase (code, AMD64_ARG_REG1, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
5528                 } else {
5529                         /* We have to shift the arguments left */
5530                         amd64_mov_reg_reg (code, AMD64_RAX, AMD64_ARG_REG1, 8);
5531                         for (i = 0; i < sig->param_count; ++i)
5532                                 amd64_mov_reg_reg (code, param_regs [i], param_regs [i + 1], 8);
5533
5534                         amd64_jump_membase (code, AMD64_RAX, G_STRUCT_OFFSET (MonoDelegate, method_ptr));
5535                 }
5536                 g_assert ((code - start) < 64);
5537
5538                 cache [sig->param_count] = start;
5539                 
5540                 mono_debug_add_delegate_trampoline (start, code - start);
5541                 mono_mini_arch_unlock ();
5542         }
5543
5544         return start;
5545 }
5546
5547 /*
5548  * Support for fast access to the thread-local lmf structure using the GS
5549  * segment register on NPTL + kernel 2.6.x.
5550  */
5551
5552 static gboolean tls_offset_inited = FALSE;
5553
5554 void
5555 mono_arch_setup_jit_tls_data (MonoJitTlsData *tls)
5556 {
5557         if (!tls_offset_inited) {
5558                 tls_offset_inited = TRUE;
5559 #ifdef MONO_XEN_OPT
5560                 optimize_for_xen = access ("/proc/xen", F_OK) == 0;
5561 #endif
5562                 appdomain_tls_offset = mono_domain_get_tls_offset ();
5563                 lmf_tls_offset = mono_get_lmf_tls_offset ();
5564                 lmf_addr_tls_offset = mono_get_lmf_addr_tls_offset ();
5565                 thread_tls_offset = mono_thread_get_tls_offset ();
5566         }               
5567 }
5568
5569 void
5570 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
5571 {
5572 }
5573
5574 void
5575 mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg)
5576 {
5577         MonoCallInst *call = (MonoCallInst*)inst;
5578         CallInfo * cinfo = get_call_info (cfg, cfg->mempool, inst->signature, FALSE);
5579
5580         if (vt_reg != -1) {
5581                 MonoInst *vtarg;
5582
5583                 if (cinfo->ret.storage == ArgValuetypeInReg) {
5584                         /*
5585                          * The valuetype is in RAX:RDX after the call, need to be copied to
5586                          * the stack. Push the address here, so the call instruction can
5587                          * access it.
5588                          */
5589                         MONO_INST_NEW (cfg, vtarg, OP_X86_PUSH);
5590                         vtarg->sreg1 = vt_reg;
5591                         mono_bblock_add_inst (cfg->cbb, vtarg);
5592
5593                         /* Align stack */
5594                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SUB_IMM, X86_ESP, X86_ESP, 8);
5595                 }
5596                 else {
5597                         MONO_INST_NEW (cfg, vtarg, OP_MOVE);
5598                         vtarg->sreg1 = vt_reg;
5599                         vtarg->dreg = mono_regstate_next_int (cfg->rs);
5600                         mono_bblock_add_inst (cfg->cbb, vtarg);
5601
5602                         mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->ret.reg, FALSE);
5603                 }
5604         }
5605
5606         /* add the this argument */
5607         if (this_reg != -1) {
5608                 MonoInst *this;
5609                 MONO_INST_NEW (cfg, this, OP_MOVE);
5610                 this->type = this_type;
5611                 this->sreg1 = this_reg;
5612                 this->dreg = mono_regstate_next_int (cfg->rs);
5613                 mono_bblock_add_inst (cfg->cbb, this);
5614
5615                 mono_call_inst_add_outarg_reg (cfg, call, this->dreg, cinfo->args [0].reg, FALSE);
5616         }
5617 }
5618
5619 #ifdef MONO_ARCH_HAVE_IMT
5620
5621 #define CMP_SIZE (6 + 1)
5622 #define CMP_REG_REG_SIZE (4 + 1)
5623 #define BR_SMALL_SIZE 2
5624 #define BR_LARGE_SIZE 6
5625 #define MOV_REG_IMM_SIZE 10
5626 #define MOV_REG_IMM_32BIT_SIZE 6
5627 #define JUMP_REG_SIZE (2 + 1)
5628
5629 static int
5630 imt_branch_distance (MonoIMTCheckItem **imt_entries, int start, int target)
5631 {
5632         int i, distance = 0;
5633         for (i = start; i < target; ++i)
5634                 distance += imt_entries [i]->chunk_size;
5635         return distance;
5636 }
5637
5638 /*
5639  * LOCKING: called with the domain lock held
5640  */
5641 gpointer
5642 mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count)
5643 {
5644         int i;
5645         int size = 0;
5646         guint8 *code, *start;
5647         gboolean vtable_is_32bit = ((gsize)(vtable) == (gsize)(int)(gsize)(vtable));
5648
5649         for (i = 0; i < count; ++i) {
5650                 MonoIMTCheckItem *item = imt_entries [i];
5651                 if (item->is_equals) {
5652                         if (item->check_target_idx) {
5653                                 if (!item->compare_done) {
5654                                         if (amd64_is_imm32 (item->method))
5655                                                 item->chunk_size += CMP_SIZE;
5656                                         else
5657                                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
5658                                 }
5659                                 if (vtable_is_32bit)
5660                                         item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
5661                                 else
5662                                         item->chunk_size += MOV_REG_IMM_SIZE;
5663                                 item->chunk_size += BR_SMALL_SIZE + JUMP_REG_SIZE;
5664                         } else {
5665                                 if (vtable_is_32bit)
5666                                         item->chunk_size += MOV_REG_IMM_32BIT_SIZE;
5667                                 else
5668                                         item->chunk_size += MOV_REG_IMM_SIZE;
5669                                 item->chunk_size += JUMP_REG_SIZE;
5670                                 /* with assert below:
5671                                  * item->chunk_size += CMP_SIZE + BR_SMALL_SIZE + 1;
5672                                  */
5673                         }
5674                 } else {
5675                         if (amd64_is_imm32 (item->method))
5676                                 item->chunk_size += CMP_SIZE;
5677                         else
5678                                 item->chunk_size += MOV_REG_IMM_SIZE + CMP_REG_REG_SIZE;
5679                         item->chunk_size += BR_LARGE_SIZE;
5680                         imt_entries [item->check_target_idx]->compare_done = TRUE;
5681                 }
5682                 size += item->chunk_size;
5683         }
5684         code = mono_code_manager_reserve (domain->code_mp, size);
5685         start = code;
5686         for (i = 0; i < count; ++i) {
5687                 MonoIMTCheckItem *item = imt_entries [i];
5688                 item->code_target = code;
5689                 if (item->is_equals) {
5690                         if (item->check_target_idx) {
5691                                 if (!item->compare_done) {
5692                                         if (amd64_is_imm32 (item->method))
5693                                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->method);
5694                                         else {
5695                                                 amd64_mov_reg_imm (code, AMD64_R10, item->method);
5696                                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, AMD64_R10);
5697                                         }
5698                                 }
5699                                 item->jmp_code = code;
5700                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
5701                                 amd64_mov_reg_imm (code, AMD64_R11, & (vtable->vtable [item->vtable_slot]));
5702                                 amd64_jump_membase (code, AMD64_R11, 0);
5703                         } else {
5704                                 /* enable the commented code to assert on wrong method */
5705 #if 0
5706                                 if (amd64_is_imm32 (item->method))
5707                                         amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->method);
5708                                 else {
5709                                         amd64_mov_reg_imm (code, AMD64_R10, item->method);
5710                                         amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, AMD64_R10);
5711                                 }
5712                                 item->jmp_code = code;
5713                                 amd64_branch8 (code, X86_CC_NE, 0, FALSE);
5714                                 amd64_mov_reg_imm (code, AMD64_R11, & (vtable->vtable [item->vtable_slot]));
5715                                 amd64_jump_membase (code, AMD64_R11, 0);
5716                                 amd64_patch (item->jmp_code, code);
5717                                 amd64_breakpoint (code);
5718                                 item->jmp_code = NULL;
5719 #else
5720                                 amd64_mov_reg_imm (code, AMD64_R11, & (vtable->vtable [item->vtable_slot]));
5721                                 amd64_jump_membase (code, AMD64_R11, 0);
5722 #endif
5723                         }
5724                 } else {
5725                         if (amd64_is_imm32 (item->method))
5726                                 amd64_alu_reg_imm (code, X86_CMP, MONO_ARCH_IMT_REG, (guint32)(gssize)item->method);
5727                         else {
5728                                 amd64_mov_reg_imm (code, AMD64_R10, item->method);
5729                                 amd64_alu_reg_reg (code, X86_CMP, MONO_ARCH_IMT_REG, AMD64_R10);
5730                         }
5731                         item->jmp_code = code;
5732                         if (x86_is_imm8 (imt_branch_distance (imt_entries, i, item->check_target_idx)))
5733                                 x86_branch8 (code, X86_CC_GE, 0, FALSE);
5734                         else
5735                                 x86_branch32 (code, X86_CC_GE, 0, FALSE);
5736                 }
5737                 g_assert (code - item->code_target <= item->chunk_size);
5738         }
5739         /* patch the branches to get to the target items */
5740         for (i = 0; i < count; ++i) {
5741                 MonoIMTCheckItem *item = imt_entries [i];
5742                 if (item->jmp_code) {
5743                         if (item->check_target_idx) {
5744                                 amd64_patch (item->jmp_code, imt_entries [item->check_target_idx]->code_target);
5745                         }
5746                 }
5747         }
5748                 
5749         mono_stats.imt_thunks_size += code - start;
5750         g_assert (code - start <= size);
5751
5752         return start;
5753 }
5754
5755 MonoMethod*
5756 mono_arch_find_imt_method (gpointer *regs, guint8 *code)
5757 {
5758         /* 
5759          * R11 is clobbered by the trampoline code, so we have to retrieve the method 
5760          * from the code.
5761          * 41 bb c0 f7 89 00     mov    $0x89f7c0,%r11d
5762          * ff 90 68 ff ff ff     callq  *0xffffffffffffff68(%rax)
5763          */
5764         /* Similar to get_vcall_slot_addr () */
5765
5766         /* Find the start of the call instruction */
5767         code -= 7;
5768         if ((code [-2] == 0x41) && (code [-1] == 0xbb) && (code [4] == 0xff) && (x86_modrm_mod (code [5]) == 1) && (x86_modrm_reg (code [5]) == 2) && ((signed char)code [6] < 0)) {
5769                 /* IMT-based interface calls
5770                  * 41 bb 14 f8 28 08       mov    $0x828f814,%r11
5771                  * ff 50 fc                call   *0xfffffffc(%rax)
5772                  */
5773                 code += 4;
5774         } else if ((code [1] == 0xff) && (amd64_modrm_reg (code [2]) == 0x2) && (amd64_modrm_mod (code [2]) == 0x2)) {
5775                 /* call *[reg+disp32] */
5776                 code += 1;
5777         } else if ((code [4] == 0xff) && (amd64_modrm_reg (code [5]) == 0x2) && (amd64_modrm_mod (code [5]) == 0x1)) {
5778                 /* call *[reg+disp8] */
5779                 code += 4;
5780         } else
5781                 g_assert_not_reached ();
5782
5783         /* Find the start of the mov instruction */
5784         code -= 10;
5785         if (code [0] == 0x49 && code [1] == 0xbb) {
5786                 return (MonoMethod*)*(gssize*)(code + 2);
5787         } else if (code [3] == 0x4d && code [4] == 0x8b && code [5] == 0x1d) {
5788                 /* mov    <OFFSET>(%rip),%r11 */
5789                 return (MonoMethod*)*(gssize*)(code + 10 + *(guint32*)(code + 6));
5790         } else if (code [4] == 0x41 && code [5] == 0xbb) {
5791                 return (MonoMethod*)(gssize)*(guint32*)(code + 6);
5792         } else {
5793                 int i;
5794
5795                 printf ("Unknown call sequence: ");
5796                 for (i = -10; i < 20; ++i)
5797                         printf ("%x ", code [i]);
5798                 g_assert_not_reached ();
5799                 return NULL;
5800         }
5801 }
5802
5803 MonoObject*
5804 mono_arch_find_this_argument (gpointer *regs, MonoMethod *method)
5805 {
5806         return mono_arch_get_this_arg_from_call (mono_method_signature (method), (gssize*)regs, NULL);
5807 }
5808 #endif
5809
5810 MonoInst*
5811 mono_arch_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5812 {
5813         MonoInst *ins = NULL;
5814
5815         if (cmethod->klass == mono_defaults.math_class) {
5816                 if (strcmp (cmethod->name, "Sin") == 0) {
5817                         MONO_INST_NEW (cfg, ins, OP_SIN);
5818                         ins->inst_i0 = args [0];
5819                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5820                         MONO_INST_NEW (cfg, ins, OP_COS);
5821                         ins->inst_i0 = args [0];
5822                 } else if (strcmp (cmethod->name, "Tan") == 0) {
5823                         if (use_sse2)
5824                                 return ins;
5825                         MONO_INST_NEW (cfg, ins, OP_TAN);
5826                         ins->inst_i0 = args [0];
5827                 } else if (strcmp (cmethod->name, "Atan") == 0) {
5828                         if (use_sse2)
5829                                 return ins;
5830                         MONO_INST_NEW (cfg, ins, OP_ATAN);
5831                         ins->inst_i0 = args [0];
5832                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5833                         MONO_INST_NEW (cfg, ins, OP_SQRT);
5834                         ins->inst_i0 = args [0];
5835                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5836                         MONO_INST_NEW (cfg, ins, OP_ABS);
5837                         ins->inst_i0 = args [0];
5838                 }
5839
5840                 if (cfg->opt & MONO_OPT_CMOV) {
5841                         int opcode = 0;
5842
5843                         if (strcmp (cmethod->name, "Min") == 0) {
5844                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5845                                         opcode = OP_IMIN;
5846                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5847                                         opcode = OP_LMIN;
5848                         } else if (strcmp (cmethod->name, "Max") == 0) {
5849                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5850                                         opcode = OP_IMAX;
5851                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5852                                         opcode = OP_LMAX;
5853                         }               
5854
5855                         if (opcode) {
5856                                 MONO_INST_NEW (cfg, ins, opcode);
5857                                 ins->inst_i0 = args [0];
5858                                 ins->inst_i1 = args [1];
5859                         }
5860                 }
5861
5862 #if 0
5863                 /* OP_FREM is not IEEE compatible */
5864                 else if (strcmp (cmethod->name, "IEEERemainder") == 0) {
5865                         MONO_INST_NEW (cfg, ins, OP_FREM);
5866                         ins->inst_i0 = args [0];
5867                         ins->inst_i1 = args [1];
5868                 }
5869 #endif
5870         } else if(cmethod->klass->image == mono_defaults.corlib &&
5871                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5872                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5873                 /* 
5874                  * Can't implement CompareExchange methods this way since they have
5875                  * three arguments.
5876                  */
5877         }
5878
5879         return ins;
5880 }
5881
5882 gboolean
5883 mono_arch_print_tree (MonoInst *tree, int arity)
5884 {
5885         return 0;
5886 }
5887
5888 MonoInst* mono_arch_get_domain_intrinsic (MonoCompile* cfg)
5889 {
5890         MonoInst* ins;
5891         
5892         if (appdomain_tls_offset == -1)
5893                 return NULL;
5894         
5895         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
5896         ins->inst_offset = appdomain_tls_offset;
5897         return ins;
5898 }
5899
5900 MonoInst* mono_arch_get_thread_intrinsic (MonoCompile* cfg)
5901 {
5902         MonoInst* ins;
5903         
5904         if (thread_tls_offset == -1)
5905                 return NULL;
5906         
5907         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
5908         ins->inst_offset = thread_tls_offset;
5909         return ins;
5910 }