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