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