Mon May 10 17:21:00 CEST 2004 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / mini-x86.c
1 /*
2  * mini-x86.c: x86 backend for the Mono code generator
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *   Patrik Torstensson
8  *
9  * (C) 2003 Ximian, Inc.
10  */
11 #include "mini.h"
12 #include <string.h>
13 #include <math.h>
14
15 #include <mono/metadata/appdomain.h>
16 #include <mono/metadata/debug-helpers.h>
17 #include <mono/metadata/profiler-private.h>
18 #include <mono/utils/mono-math.h>
19
20 #include "trace.h"
21 #include "mini-x86.h"
22 #include "inssel.h"
23 #include "cpu-pentium.h"
24
25 static gint lmf_tls_offset = -1;
26
27 #ifdef PLATFORM_WIN32
28 /* Under windows, the default pinvoke calling convention is stdcall */
29 #define CALLCONV_IS_STDCALL(call_conv) (((call_conv) == MONO_CALL_STDCALL) || ((call_conv) == MONO_CALL_DEFAULT))
30 #else
31 #define CALLCONV_IS_STDCALL(call_conv) ((call_conv) == MONO_CALL_STDCALL)
32 #endif
33
34 #define SIGNAL_STACK_SIZE (64 * 1024)
35
36 static gpointer mono_arch_get_lmf_addr (void);
37
38 const char*
39 mono_arch_regname (int reg) {
40         switch (reg) {
41         case X86_EAX: return "%eax";
42         case X86_EBX: return "%ebx";
43         case X86_ECX: return "%ecx";
44         case X86_EDX: return "%edx";
45         case X86_ESP: return "%esp";    case X86_EBP: return "%ebp";
46         case X86_EDI: return "%edi";
47         case X86_ESI: return "%esi";
48         }
49         return "unknown";
50 }
51
52 /*
53  * mono_arch_get_argument_info:
54  * @csig:  a method signature
55  * @param_count: the number of parameters to consider
56  * @arg_info: an array to store the result infos
57  *
58  * Gathers information on parameters such as size, alignment and
59  * padding. arg_info should be large enought to hold param_count + 1 entries. 
60  *
61  * Returns the size of the activation frame.
62  */
63 int
64 mono_arch_get_argument_info (MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info)
65 {
66         int k, frame_size = 0;
67         int size, align, pad;
68         int offset = 8;
69
70         if (MONO_TYPE_ISSTRUCT (csig->ret)) { 
71                 frame_size += sizeof (gpointer);
72                 offset += 4;
73         }
74
75         arg_info [0].offset = offset;
76
77         if (csig->hasthis) {
78                 frame_size += sizeof (gpointer);
79                 offset += 4;
80         }
81
82         arg_info [0].size = frame_size;
83
84         for (k = 0; k < param_count; k++) {
85                 
86                 if (csig->pinvoke)
87                         size = mono_type_native_stack_size (csig->params [k], &align);
88                 else
89                         size = mono_type_stack_size (csig->params [k], &align);
90
91                 /* ignore alignment for now */
92                 align = 1;
93
94                 frame_size += pad = (align - (frame_size & (align - 1))) & (align - 1); 
95                 arg_info [k].pad = pad;
96                 frame_size += size;
97                 arg_info [k + 1].pad = 0;
98                 arg_info [k + 1].size = size;
99                 offset += pad;
100                 arg_info [k + 1].offset = offset;
101                 offset += size;
102         }
103
104         align = MONO_ARCH_FRAME_ALIGNMENT;
105         frame_size += pad = (align - (frame_size & (align - 1))) & (align - 1);
106         arg_info [k].pad = pad;
107
108         return frame_size;
109 }
110
111 static const guchar cpuid_impl [] = {
112         0x55,                           /* push   %ebp */
113         0x89, 0xe5,                     /* mov    %esp,%ebp */
114         0x53,                           /* push   %ebx */
115         0x8b, 0x45, 0x08,               /* mov    0x8(%ebp),%eax */
116         0x0f, 0xa2,                     /* cpuid   */
117         0x50,                           /* push   %eax */
118         0x8b, 0x45, 0x10,               /* mov    0x10(%ebp),%eax */
119         0x89, 0x18,                     /* mov    %ebx,(%eax) */
120         0x8b, 0x45, 0x14,               /* mov    0x14(%ebp),%eax */
121         0x89, 0x08,                     /* mov    %ecx,(%eax) */
122         0x8b, 0x45, 0x18,               /* mov    0x18(%ebp),%eax */
123         0x89, 0x10,                     /* mov    %edx,(%eax) */
124         0x58,                           /* pop    %eax */
125         0x8b, 0x55, 0x0c,               /* mov    0xc(%ebp),%edx */
126         0x89, 0x02,                     /* mov    %eax,(%edx) */
127         0x5b,                           /* pop    %ebx */
128         0xc9,                           /* leave   */
129         0xc3,                           /* ret     */
130 };
131
132 typedef void (*CpuidFunc) (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx);
133
134 static int 
135 cpuid (int id, int* p_eax, int* p_ebx, int* p_ecx, int* p_edx)
136 {
137         int have_cpuid = 0;
138         __asm__  __volatile__ (
139                 "pushfl\n"
140                 "popl %%eax\n"
141                 "movl %%eax, %%edx\n"
142                 "xorl $0x200000, %%eax\n"
143                 "pushl %%eax\n"
144                 "popfl\n"
145                 "pushfl\n"
146                 "popl %%eax\n"
147                 "xorl %%edx, %%eax\n"
148                 "andl $0x200000, %%eax\n"
149                 "movl %%eax, %0"
150                 : "=r" (have_cpuid)
151                 :
152                 : "%eax", "%edx"
153         );
154
155         if (have_cpuid) {
156                 CpuidFunc func = (CpuidFunc)cpuid_impl;
157                 func (id, p_eax, p_ebx, p_ecx, p_edx);
158                 /*
159                  * We use this approach because of issues with gcc and pic code, see:
160                  * http://gcc.gnu.org/cgi-bin/gnatsweb.pl?cmd=view%20audit-trail&database=gcc&pr=7329
161                 __asm__ __volatile__ ("cpuid"
162                         : "=a" (*p_eax), "=b" (*p_ebx), "=c" (*p_ecx), "=d" (*p_edx)
163                         : "a" (id));
164                 */
165                 return 1;
166         }
167         return 0;
168 }
169
170 /*
171  * Initialize the cpu to execute managed code.
172  */
173 void
174 mono_arch_cpu_init (void)
175 {
176         guint16 fpcw;
177
178         /* spec compliance requires running with double precision */
179         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
180         fpcw &= ~X86_FPCW_PRECC_MASK;
181         fpcw |= X86_FPCW_PREC_DOUBLE;
182         __asm__  __volatile__ ("fldcw %0\n": : "m" (fpcw));
183         __asm__  __volatile__ ("fnstcw %0\n": "=m" (fpcw));
184
185 }
186
187 /*
188  * This function returns the optimizations supported on this cpu.
189  */
190 guint32
191 mono_arch_cpu_optimizazions (guint32 *exclude_mask)
192 {
193         int eax, ebx, ecx, edx;
194         guint32 opts = 0;
195         
196         *exclude_mask = 0;
197         /* Feature Flags function, flags returned in EDX. */
198         if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
199                 if (edx & (1 << 15)) {
200                         opts |= MONO_OPT_CMOV;
201                         if (edx & 1)
202                                 opts |= MONO_OPT_FCMOV;
203                         else
204                                 *exclude_mask |= MONO_OPT_FCMOV;
205                 } else
206                         *exclude_mask |= MONO_OPT_CMOV;
207         }
208         return opts;
209 }
210
211 static gboolean
212 is_regsize_var (MonoType *t) {
213         if (t->byref)
214                 return TRUE;
215         switch (t->type) {
216         case MONO_TYPE_I4:
217         case MONO_TYPE_U4:
218         case MONO_TYPE_I:
219         case MONO_TYPE_U:
220         case MONO_TYPE_PTR:
221                 return TRUE;
222         case MONO_TYPE_OBJECT:
223         case MONO_TYPE_STRING:
224         case MONO_TYPE_CLASS:
225         case MONO_TYPE_SZARRAY:
226         case MONO_TYPE_ARRAY:
227                 return TRUE;
228         case MONO_TYPE_VALUETYPE:
229                 if (t->data.klass->enumtype)
230                         return is_regsize_var (t->data.klass->enum_basetype);
231                 return FALSE;
232         }
233         return FALSE;
234 }
235
236 GList *
237 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
238 {
239         GList *vars = NULL;
240         int i;
241
242         for (i = 0; i < cfg->num_varinfo; i++) {
243                 MonoInst *ins = cfg->varinfo [i];
244                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
245
246                 /* unused vars */
247                 if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos)
248                         continue;
249
250                 if ((ins->flags & (MONO_INST_IS_DEAD|MONO_INST_VOLATILE|MONO_INST_INDIRECT)) || 
251                     (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG))
252                         continue;
253
254                 /* we dont allocate I1 to registers because there is no simply way to sign extend 
255                  * 8bit quantities in caller saved registers on x86 */
256                 if (is_regsize_var (ins->inst_vtype) || (ins->inst_vtype->type == MONO_TYPE_BOOLEAN) || 
257                     (ins->inst_vtype->type == MONO_TYPE_U1) || (ins->inst_vtype->type == MONO_TYPE_U2)||
258                     (ins->inst_vtype->type == MONO_TYPE_I2) || (ins->inst_vtype->type == MONO_TYPE_CHAR)) {
259                         g_assert (MONO_VARINFO (cfg, i)->reg == -1);
260                         g_assert (i == vmv->idx);
261                         vars = g_list_prepend (vars, vmv);
262                 }
263         }
264
265         vars = mono_varlist_sort (cfg, vars, 0);
266
267         return vars;
268 }
269
270 GList *
271 mono_arch_get_global_int_regs (MonoCompile *cfg)
272 {
273         GList *regs = NULL;
274
275         /* we can use 3 registers for global allocation */
276         regs = g_list_prepend (regs, (gpointer)X86_EBX);
277         regs = g_list_prepend (regs, (gpointer)X86_ESI);
278         regs = g_list_prepend (regs, (gpointer)X86_EDI);
279
280         return regs;
281 }
282
283 /*
284  * mono_arch_regalloc_cost:
285  *
286  *  Return the cost, in number of memory references, of the action of 
287  * allocating the variable VMV into a register during global register
288  * allocation.
289  */
290 guint32
291 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv)
292 {
293         MonoInst *ins = cfg->varinfo [vmv->idx];
294
295         if (cfg->method->save_lmf)
296                 /* The register is already saved */
297                 return (ins->opcode == OP_ARG) ? 1 : 0;
298         else
299                 /* push+pop+possible load if it is an argument */
300                 return (ins->opcode == OP_ARG) ? 3 : 2;
301 }
302  
303 /*
304  * Set var information according to the calling convention. X86 version.
305  * The locals var stuff should most likely be split in another method.
306  */
307 void
308 mono_arch_allocate_vars (MonoCompile *m)
309 {
310         MonoMethodSignature *sig;
311         MonoMethodHeader *header;
312         MonoInst *inst;
313         int i, offset, size, align, curinst;
314
315         header = ((MonoMethodNormal *)m->method)->header;
316
317         sig = m->method->signature;
318
319         offset = 8;
320         curinst = 0;
321         if (MONO_TYPE_ISSTRUCT (sig->ret)) {
322                 m->ret->opcode = OP_REGOFFSET;
323                 m->ret->inst_basereg = X86_EBP;
324                 m->ret->inst_offset = offset;
325                 offset += sizeof (gpointer);
326         } else {
327                 /* FIXME: handle long and FP values */
328                 switch (sig->ret->type) {
329                 case MONO_TYPE_VOID:
330                         break;
331                 default:
332                         m->ret->opcode = OP_REGVAR;
333                         m->ret->inst_c0 = X86_EAX;
334                         break;
335                 }
336         }
337         if (sig->hasthis) {
338                 inst = m->varinfo [curinst];
339                 if (inst->opcode != OP_REGVAR) {
340                         inst->opcode = OP_REGOFFSET;
341                         inst->inst_basereg = X86_EBP;
342                 }
343                 inst->inst_offset = offset;
344                 offset += sizeof (gpointer);
345                 curinst++;
346         }
347
348         if (sig->call_convention == MONO_CALL_VARARG) {
349                 m->sig_cookie = offset;
350                 offset += sizeof (gpointer);
351         }
352
353         for (i = 0; i < sig->param_count; ++i) {
354                 inst = m->varinfo [curinst];
355                 if (inst->opcode != OP_REGVAR) {
356                         inst->opcode = OP_REGOFFSET;
357                         inst->inst_basereg = X86_EBP;
358                 }
359                 inst->inst_offset = offset;
360                 size = mono_type_size (sig->params [i], &align);
361                 size += 4 - 1;
362                 size &= ~(4 - 1);
363                 offset += size;
364                 curinst++;
365         }
366
367         offset = 0;
368
369         /* reserve space to save LMF and caller saved registers */
370
371         if (m->method->save_lmf) {
372                 offset += sizeof (MonoLMF);
373         } else {
374                 if (m->used_int_regs & (1 << X86_EBX)) {
375                         offset += 4;
376                 }
377
378                 if (m->used_int_regs & (1 << X86_EDI)) {
379                         offset += 4;
380                 }
381
382                 if (m->used_int_regs & (1 << X86_ESI)) {
383                         offset += 4;
384                 }
385         }
386
387         for (i = curinst; i < m->num_varinfo; ++i) {
388                 inst = m->varinfo [i];
389
390                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR)
391                         continue;
392
393                 /* inst->unused indicates native sized value types, this is used by the
394                 * pinvoke wrappers when they call functions returning structure */
395                 if (inst->unused && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
396                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
397                 else
398                         size = mono_type_size (inst->inst_vtype, &align);
399
400                 offset += size;
401                 offset += align - 1;
402                 offset &= ~(align - 1);
403                 inst->opcode = OP_REGOFFSET;
404                 inst->inst_basereg = X86_EBP;
405                 inst->inst_offset = -offset;
406                 //g_print ("allocating local %d to %d\n", i, -offset);
407         }
408         offset += (MONO_ARCH_FRAME_ALIGNMENT - 1);
409         offset &= ~(MONO_ARCH_FRAME_ALIGNMENT - 1);
410
411         /* change sign? */
412         m->stack_offset = -offset;
413 }
414
415 /* Fixme: we need an alignment solution for enter_method and mono_arch_call_opcode,
416  * currently alignment in mono_arch_call_opcode is computed without arch_get_argument_info 
417  */
418
419 /* 
420  * take the arguments and generate the arch-specific
421  * instructions to properly call the function in call.
422  * This includes pushing, moving arguments to the right register
423  * etc.
424  * Issue: who does the spilling if needed, and when?
425  */
426 MonoCallInst*
427 mono_arch_call_opcode (MonoCompile *cfg, MonoBasicBlock* bb, MonoCallInst *call, int is_virtual) {
428         MonoInst *arg, *in;
429         MonoMethodSignature *sig;
430         int i, n, stack_size, type;
431         MonoType *ptype;
432
433         stack_size = 0;
434         /* add the vararg cookie before the non-implicit args */
435         if (call->signature->call_convention == MONO_CALL_VARARG) {
436                 MonoInst *sig_arg;
437                 /* FIXME: Add support for signature tokens to AOT */
438                 cfg->disable_aot = TRUE;
439                 MONO_INST_NEW (cfg, arg, OP_OUTARG);
440                 MONO_INST_NEW (cfg, sig_arg, OP_ICONST);
441                 sig_arg->inst_p0 = call->signature;
442                 arg->inst_left = sig_arg;
443                 arg->type = STACK_PTR;
444                 /* prepend, so they get reversed */
445                 arg->next = call->out_args;
446                 call->out_args = arg;
447                 stack_size += sizeof (gpointer);
448         }
449         sig = call->signature;
450         n = sig->param_count + sig->hasthis;
451
452         if (sig->ret && MONO_TYPE_ISSTRUCT (sig->ret))
453                 stack_size += sizeof (gpointer);
454         for (i = 0; i < n; ++i) {
455                 if (is_virtual && i == 0) {
456                         /* the argument will be attached to the call instrucion */
457                         in = call->args [i];
458                         stack_size += 4;
459                 } else {
460                         MONO_INST_NEW (cfg, arg, OP_OUTARG);
461                         in = call->args [i];
462                         arg->cil_code = in->cil_code;
463                         arg->inst_left = in;
464                         arg->type = in->type;
465                         /* prepend, so they get reversed */
466                         arg->next = call->out_args;
467                         call->out_args = arg;
468                         if (i >= sig->hasthis) {
469                                 ptype = sig->params [i - sig->hasthis];
470                                 if (ptype->byref)
471                                         type = MONO_TYPE_U;
472                                 else
473                                         type = ptype->type;
474 handle_enum:
475                                 /* FIXME: validate arguments... */
476                                 switch (type) {
477                                 case MONO_TYPE_I:
478                                 case MONO_TYPE_U:
479                                 case MONO_TYPE_BOOLEAN:
480                                 case MONO_TYPE_CHAR:
481                                 case MONO_TYPE_I1:
482                                 case MONO_TYPE_U1:
483                                 case MONO_TYPE_I2:
484                                 case MONO_TYPE_U2:
485                                 case MONO_TYPE_I4:
486                                 case MONO_TYPE_U4:
487                                 case MONO_TYPE_STRING:
488                                 case MONO_TYPE_CLASS:
489                                 case MONO_TYPE_OBJECT:
490                                 case MONO_TYPE_PTR:
491                                 case MONO_TYPE_FNPTR:
492                                 case MONO_TYPE_ARRAY:
493                                 case MONO_TYPE_SZARRAY:
494                                         stack_size += 4;
495                                         break;
496                                 case MONO_TYPE_I8:
497                                 case MONO_TYPE_U8:
498                                         stack_size += 8;
499                                         break;
500                                 case MONO_TYPE_R4:
501                                         stack_size += 4;
502                                         arg->opcode = OP_OUTARG_R4;
503                                         break;
504                                 case MONO_TYPE_R8:
505                                         stack_size += 8;
506                                         arg->opcode = OP_OUTARG_R8;
507                                         break;
508                                 case MONO_TYPE_VALUETYPE:
509                                         if (MONO_TYPE_ISSTRUCT (ptype)) {
510                                                 int size;
511                                                 if (sig->pinvoke) 
512                                                         size = mono_type_native_stack_size (&in->klass->byval_arg, NULL);
513                                                 else 
514                                                         size = mono_type_stack_size (&in->klass->byval_arg, NULL);
515
516                                                 stack_size += size;
517                                                 arg->opcode = OP_OUTARG_VT;
518                                                 arg->klass = in->klass;
519                                                 arg->unused = sig->pinvoke;
520                                                 arg->inst_imm = size; 
521                                         } else {
522                                                 type = ptype->data.klass->enum_basetype->type;
523                                                 goto handle_enum;
524                                         }
525                                         break;
526                                 case MONO_TYPE_TYPEDBYREF:
527                                         stack_size += sizeof (MonoTypedRef);
528                                         arg->opcode = OP_OUTARG_VT;
529                                         arg->klass = in->klass;
530                                         arg->unused = sig->pinvoke;
531                                         arg->inst_imm = sizeof (MonoTypedRef); 
532                                         break;
533                                 case MONO_TYPE_GENERICINST:
534                                         type = ptype->data.generic_inst->generic_type->type;
535                                         goto handle_enum;
536
537                                 default:
538                                         g_error ("unknown type 0x%02x in mono_arch_call_opcode\n", type);
539                                 }
540                         } else {
541                                 /* the this argument */
542                                 stack_size += 4;
543                         }
544                 }
545         }
546         /* if the function returns a struct, the called method already does a ret $0x4 */
547         if (sig->ret && MONO_TYPE_ISSTRUCT (sig->ret))
548                 stack_size -= 4;
549         call->stack_usage = stack_size;
550         /* 
551          * should set more info in call, such as the stack space
552          * used by the args that needs to be added back to esp
553          */
554
555         return call;
556 }
557
558 /*
559  * Allow tracing to work with this interface (with an optional argument)
560  */
561
562 /*
563  * This may be needed on some archs or for debugging support.
564  */
565 void
566 mono_arch_instrument_mem_needs (MonoMethod *method, int *stack, int *code)
567 {
568         /* no stack room needed now (may be needed for FASTCALL-trace support) */
569         *stack = 0;
570         /* split prolog-epilog requirements? */
571         *code = 50; /* max bytes needed: check this number */
572 }
573
574 void*
575 mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
576 {
577         guchar *code = p;
578
579         /* if some args are passed in registers, we need to save them here */
580         x86_push_reg (code, X86_EBP);
581         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, cfg->method);
582         x86_push_imm (code, cfg->method);
583         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_ABS, func);
584         x86_call_code (code, 0);
585         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8);
586
587         return code;
588 }
589
590 enum {
591         SAVE_NONE,
592         SAVE_STRUCT,
593         SAVE_EAX,
594         SAVE_EAX_EDX,
595         SAVE_FP
596 };
597
598 void*
599 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments)
600 {
601         guchar *code = p;
602         int arg_size = 0, save_mode = SAVE_NONE;
603         MonoMethod *method = cfg->method;
604         int rtype = method->signature->ret->type;
605         
606 handle_enum:
607         switch (rtype) {
608         case MONO_TYPE_VOID:
609                 /* special case string .ctor icall */
610                 if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class)
611                         save_mode = SAVE_EAX;
612                 else
613                         save_mode = SAVE_NONE;
614                 break;
615         case MONO_TYPE_I8:
616         case MONO_TYPE_U8:
617                 save_mode = SAVE_EAX_EDX;
618                 break;
619         case MONO_TYPE_R4:
620         case MONO_TYPE_R8:
621                 save_mode = SAVE_FP;
622                 break;
623         case MONO_TYPE_VALUETYPE:
624                 if (method->signature->ret->data.klass->enumtype) {
625                         rtype = method->signature->ret->data.klass->enum_basetype->type;
626                         goto handle_enum;
627                 }
628                 save_mode = SAVE_STRUCT;
629                 break;
630         default:
631                 save_mode = SAVE_EAX;
632                 break;
633         }
634
635         switch (save_mode) {
636         case SAVE_EAX_EDX:
637                 x86_push_reg (code, X86_EDX);
638                 x86_push_reg (code, X86_EAX);
639                 if (enable_arguments) {
640                         x86_push_reg (code, X86_EDX);
641                         x86_push_reg (code, X86_EAX);
642                         arg_size = 8;
643                 }
644                 break;
645         case SAVE_EAX:
646                 x86_push_reg (code, X86_EAX);
647                 if (enable_arguments) {
648                         x86_push_reg (code, X86_EAX);
649                         arg_size = 4;
650                 }
651                 break;
652         case SAVE_FP:
653                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
654                 x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE);
655                 if (enable_arguments) {
656                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
657                         x86_fst_membase (code, X86_ESP, 0, TRUE, TRUE);
658                         arg_size = 8;
659                 }
660                 break;
661         case SAVE_STRUCT:
662                 if (enable_arguments) {
663                         x86_push_membase (code, X86_EBP, 8);
664                         arg_size = 4;
665                 }
666                 break;
667         case SAVE_NONE:
668         default:
669                 break;
670         }
671
672
673         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_METHODCONST, method);
674         x86_push_imm (code, method);
675         mono_add_patch_info (cfg, code-cfg->native_code, MONO_PATCH_INFO_ABS, func);
676         x86_call_code (code, 0);
677         x86_alu_reg_imm (code, X86_ADD, X86_ESP, arg_size + 4);
678
679         switch (save_mode) {
680         case SAVE_EAX_EDX:
681                 x86_pop_reg (code, X86_EAX);
682                 x86_pop_reg (code, X86_EDX);
683                 break;
684         case SAVE_EAX:
685                 x86_pop_reg (code, X86_EAX);
686                 break;
687         case SAVE_FP:
688                 x86_fld_membase (code, X86_ESP, 0, TRUE);
689                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 8);
690                 break;
691         case SAVE_NONE:
692         default:
693                 break;
694         }
695
696         return code;
697 }
698
699 #define EMIT_COND_BRANCH(ins,cond,sign) \
700 if (ins->flags & MONO_INST_BRLABEL) { \
701         if (ins->inst_i0->inst_c0) { \
702                 x86_branch (code, cond, cfg->native_code + ins->inst_i0->inst_c0, sign); \
703         } else { \
704                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_LABEL, ins->inst_i0); \
705                 x86_branch32 (code, cond, 0, sign); \
706         } \
707 } else { \
708         if (ins->inst_true_bb->native_offset) { \
709                 x86_branch (code, cond, cfg->native_code + ins->inst_true_bb->native_offset, sign); \
710         } else { \
711                 mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); \
712                 if ((cfg->opt & MONO_OPT_BRANCH) && \
713                     x86_is_imm8 (ins->inst_true_bb->max_offset - cpos)) \
714                         x86_branch8 (code, cond, 0, sign); \
715                 else \
716                         x86_branch32 (code, cond, 0, sign); \
717         } \
718 }
719
720 /* emit an exception if condition is fail */
721 #define EMIT_COND_SYSTEM_EXCEPTION(cond,signed,exc_name)            \
722         do {                                                        \
723                 mono_add_patch_info (cfg, code - cfg->native_code,   \
724                                     MONO_PATCH_INFO_EXC, exc_name);  \
725                 x86_branch32 (code, cond, 0, signed);               \
726         } while (0); 
727
728 #define EMIT_FPCOMPARE(code) do { \
729         x86_fcompp (code); \
730         x86_fnstsw (code); \
731 } while (0); 
732
733 /* FIXME: Add more instructions */
734 #define INST_IGNORES_CFLAGS(ins) (((ins)->opcode == CEE_BR) || ((ins)->opcode == OP_STORE_MEMBASE_IMM))
735
736 static void
737 peephole_pass (MonoCompile *cfg, MonoBasicBlock *bb)
738 {
739         MonoInst *ins, *last_ins = NULL;
740         ins = bb->code;
741
742         while (ins) {
743
744                 switch (ins->opcode) {
745                 case OP_ICONST:
746                         /* reg = 0 -> XOR (reg, reg) */
747                         /* XOR sets cflags on x86, so we cant do it always */
748                         if (ins->inst_c0 == 0 && ins->next && INST_IGNORES_CFLAGS (ins->next)) {
749                                 ins->opcode = CEE_XOR;
750                                 ins->sreg1 = ins->dreg;
751                                 ins->sreg2 = ins->dreg;
752                         }
753                         break;
754                 case OP_MUL_IMM: 
755                         /* remove unnecessary multiplication with 1 */
756                         if (ins->inst_imm == 1) {
757                                 if (ins->dreg != ins->sreg1) {
758                                         ins->opcode = OP_MOVE;
759                                 } else {
760                                         last_ins->next = ins->next;                             
761                                         ins = ins->next;                                
762                                         continue;
763                                 }
764                         }
765                         break;
766                 case OP_COMPARE_IMM:
767                         /* OP_COMPARE_IMM (reg, 0) --> OP_X86_TEST_NULL (reg) */
768                         if (ins->inst_imm == 0 && ins->next &&
769                             (ins->next->opcode == CEE_BEQ || ins->next->opcode == CEE_BNE_UN ||
770                              ins->next->opcode == OP_CEQ)) {
771                                 ins->opcode = OP_X86_TEST_NULL;
772                         }     
773                         break;
774                 case OP_LOAD_MEMBASE:
775                 case OP_LOADI4_MEMBASE:
776                         /* 
777                          * OP_STORE_MEMBASE_REG reg, offset(basereg) 
778                          * OP_LOAD_MEMBASE offset(basereg), reg
779                          */
780                         if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG 
781                                          || last_ins->opcode == OP_STORE_MEMBASE_REG) &&
782                             ins->inst_basereg == last_ins->inst_destbasereg &&
783                             ins->inst_offset == last_ins->inst_offset) {
784                                 if (ins->dreg == last_ins->sreg1) {
785                                         last_ins->next = ins->next;                             
786                                         ins = ins->next;                                
787                                         continue;
788                                 } else {
789                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
790                                         ins->opcode = OP_MOVE;
791                                         ins->sreg1 = last_ins->sreg1;
792                                 }
793
794                         /* 
795                          * Note: reg1 must be different from the basereg in the second load
796                          * OP_LOAD_MEMBASE offset(basereg), reg1
797                          * OP_LOAD_MEMBASE offset(basereg), reg2
798                          * -->
799                          * OP_LOAD_MEMBASE offset(basereg), reg1
800                          * OP_MOVE reg1, reg2
801                          */
802                         } if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE
803                                            || last_ins->opcode == OP_LOAD_MEMBASE) &&
804                               ins->inst_basereg != last_ins->dreg &&
805                               ins->inst_basereg == last_ins->inst_basereg &&
806                               ins->inst_offset == last_ins->inst_offset) {
807
808                                 if (ins->dreg == last_ins->dreg) {
809                                         last_ins->next = ins->next;                             
810                                         ins = ins->next;                                
811                                         continue;
812                                 } else {
813                                         ins->opcode = OP_MOVE;
814                                         ins->sreg1 = last_ins->dreg;
815                                 }
816
817                                 //g_assert_not_reached ();
818
819 #if 0
820                         /* 
821                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
822                          * OP_LOAD_MEMBASE offset(basereg), reg
823                          * -->
824                          * OP_STORE_MEMBASE_IMM imm, offset(basereg) 
825                          * OP_ICONST reg, imm
826                          */
827                         } else if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM
828                                                 || last_ins->opcode == OP_STORE_MEMBASE_IMM) &&
829                                    ins->inst_basereg == last_ins->inst_destbasereg &&
830                                    ins->inst_offset == last_ins->inst_offset) {
831                                 //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
832                                 ins->opcode = OP_ICONST;
833                                 ins->inst_c0 = last_ins->inst_imm;
834                                 g_assert_not_reached (); // check this rule
835 #endif
836                         }
837                         break;
838                 case OP_LOADU1_MEMBASE:
839                 case OP_LOADI1_MEMBASE:
840                   /*
841                    * FIXME: Missing explanation
842                    */
843                         if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) &&
844                                         ins->inst_basereg == last_ins->inst_destbasereg &&
845                                         ins->inst_offset == last_ins->inst_offset) {
846                                 if (ins->dreg == last_ins->sreg1) {
847                                         last_ins->next = ins->next;                             
848                                         ins = ins->next;                                
849                                         continue;
850                                 } else {
851                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
852                                         ins->opcode = OP_MOVE;
853                                         ins->sreg1 = last_ins->sreg1;
854                                 }
855                         }
856                         break;
857                 case OP_LOADU2_MEMBASE:
858                 case OP_LOADI2_MEMBASE:
859                   /*
860                    * FIXME: Missing explanation
861                    */
862                         if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) &&
863                                         ins->inst_basereg == last_ins->inst_destbasereg &&
864                                         ins->inst_offset == last_ins->inst_offset) {
865                                 if (ins->dreg == last_ins->sreg1) {
866                                         last_ins->next = ins->next;                             
867                                         ins = ins->next;                                
868                                         continue;
869                                 } else {
870                                         //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++);
871                                         ins->opcode = OP_MOVE;
872                                         ins->sreg1 = last_ins->sreg1;
873                                 }
874                         }
875                         break;
876                 case CEE_CONV_I4:
877                 case CEE_CONV_U4:
878                 case OP_MOVE:
879                         /* 
880                          * OP_MOVE reg, reg 
881                          */
882                         if (ins->dreg == ins->sreg1) {
883                                 if (last_ins)
884                                         last_ins->next = ins->next;                             
885                                 ins = ins->next;
886                                 continue;
887                         }
888                         /* 
889                          * OP_MOVE sreg, dreg 
890                          * OP_MOVE dreg, sreg
891                          */
892                         if (last_ins && last_ins->opcode == OP_MOVE &&
893                             ins->sreg1 == last_ins->dreg &&
894                             ins->dreg == last_ins->sreg1) {
895                                 last_ins->next = ins->next;                             
896                                 ins = ins->next;                                
897                                 continue;
898                         }
899                         break;
900                 }
901                 last_ins = ins;
902                 ins = ins->next;
903         }
904         bb->last_ins = last_ins;
905 }
906
907 static const int 
908 branch_cc_table [] = {
909         X86_CC_EQ, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
910         X86_CC_NE, X86_CC_GE, X86_CC_GT, X86_CC_LE, X86_CC_LT,
911         X86_CC_O, X86_CC_NO, X86_CC_C, X86_CC_NC
912 };
913
914 #define DEBUG(a) if (cfg->verbose_level > 1) a
915 //#define DEBUG(a)
916
917 /*
918  * returns the offset used by spillvar. It allocates a new
919  * spill variable if necessary. 
920  */
921 static int
922 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
923 {
924         MonoSpillInfo **si, *info;
925         int i = 0;
926
927         si = &cfg->spill_info; 
928         
929         while (i <= spillvar) {
930
931                 if (!*si) {
932                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
933                         info->next = NULL;
934                         cfg->stack_offset -= sizeof (gpointer);
935                         info->offset = cfg->stack_offset;
936                 }
937
938                 if (i == spillvar)
939                         return (*si)->offset;
940
941                 i++;
942                 si = &(*si)->next;
943         }
944
945         g_assert_not_reached ();
946         return 0;
947 }
948
949 /*
950  * returns the offset used by spillvar. It allocates a new
951  * spill float variable if necessary. 
952  * (same as mono_spillvar_offset but for float)
953  */
954 static int
955 mono_spillvar_offset_float (MonoCompile *cfg, int spillvar)
956 {
957         MonoSpillInfo **si, *info;
958         int i = 0;
959
960         si = &cfg->spill_info_float; 
961         
962         while (i <= spillvar) {
963
964                 if (!*si) {
965                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
966                         info->next = NULL;
967                         cfg->stack_offset -= sizeof (double);
968                         info->offset = cfg->stack_offset;
969                 }
970
971                 if (i == spillvar)
972                         return (*si)->offset;
973
974                 i++;
975                 si = &(*si)->next;
976         }
977
978         g_assert_not_reached ();
979         return 0;
980 }
981
982 /*
983  * Creates a store for spilled floating point items
984  */
985 static MonoInst*
986 create_spilled_store_float (MonoCompile *cfg, int spill, int reg, MonoInst *ins)
987 {
988         MonoInst *store;
989         MONO_INST_NEW (cfg, store, OP_STORER8_MEMBASE_REG);
990         store->sreg1 = reg;
991         store->inst_destbasereg = X86_EBP;
992         store->inst_offset = mono_spillvar_offset_float (cfg, spill);
993
994         DEBUG (g_print ("SPILLED FLOAT STORE (%d at 0x%08x(%%sp)) (from %d)\n", spill, store->inst_offset, reg));
995         return store;
996 }
997
998 /*
999  * Creates a load for spilled floating point items 
1000  */
1001 static MonoInst*
1002 create_spilled_load_float (MonoCompile *cfg, int spill, int reg, MonoInst *ins)
1003 {
1004         MonoInst *load;
1005         MONO_INST_NEW (cfg, load, OP_LOADR8_SPILL_MEMBASE);
1006         load->dreg = reg;
1007         load->inst_basereg = X86_EBP;
1008         load->inst_offset = mono_spillvar_offset_float (cfg, spill);
1009
1010         DEBUG (g_print ("SPILLED FLOAT LOAD (%d at 0x%08x(%%sp)) (from %d)\n", spill, load->inst_offset, reg));
1011         return load;
1012 }
1013
1014 #define reg_is_freeable(r) ((r) >= 0 && (r) <= 7 && X86_IS_CALLEE ((r)))
1015
1016 typedef struct {
1017         int born_in;
1018         int killed_in;
1019         int last_use;
1020         int prev_use;
1021         int flags;              /* used to track fp spill/load */
1022 } RegTrack;
1023
1024 static const char*const * ins_spec = pentium_desc;
1025
1026 static void
1027 print_ins (int i, MonoInst *ins)
1028 {
1029         const char *spec = ins_spec [ins->opcode];
1030         g_print ("\t%-2d %s", i, mono_inst_name (ins->opcode));
1031         if (spec [MONO_INST_DEST]) {
1032                 if (ins->dreg >= MONO_MAX_IREGS)
1033                         g_print (" R%d <-", ins->dreg);
1034                 else
1035                         g_print (" %s <-", mono_arch_regname (ins->dreg));
1036         }
1037         if (spec [MONO_INST_SRC1]) {
1038                 if (ins->sreg1 >= MONO_MAX_IREGS)
1039                         g_print (" R%d", ins->sreg1);
1040                 else
1041                         g_print (" %s", mono_arch_regname (ins->sreg1));
1042         }
1043         if (spec [MONO_INST_SRC2]) {
1044                 if (ins->sreg2 >= MONO_MAX_IREGS)
1045                         g_print (" R%d", ins->sreg2);
1046                 else
1047                         g_print (" %s", mono_arch_regname (ins->sreg2));
1048         }
1049         if (spec [MONO_INST_CLOB])
1050                 g_print (" clobbers: %c", spec [MONO_INST_CLOB]);
1051         g_print ("\n");
1052 }
1053
1054 static void
1055 print_regtrack (RegTrack *t, int num)
1056 {
1057         int i;
1058         char buf [32];
1059         const char *r;
1060         
1061         for (i = 0; i < num; ++i) {
1062                 if (!t [i].born_in)
1063                         continue;
1064                 if (i >= MONO_MAX_IREGS) {
1065                         g_snprintf (buf, sizeof(buf), "R%d", i);
1066                         r = buf;
1067                 } else
1068                         r = mono_arch_regname (i);
1069                 g_print ("liveness: %s [%d - %d]\n", r, t [i].born_in, t[i].last_use);
1070         }
1071 }
1072
1073 typedef struct InstList InstList;
1074
1075 struct InstList {
1076         InstList *prev;
1077         InstList *next;
1078         MonoInst *data;
1079 };
1080
1081 static inline InstList*
1082 inst_list_prepend (MonoMemPool *pool, InstList *list, MonoInst *data)
1083 {
1084         InstList *item = mono_mempool_alloc (pool, sizeof (InstList));
1085         item->data = data;
1086         item->prev = NULL;
1087         item->next = list;
1088         if (list)
1089                 list->prev = item;
1090         return item;
1091 }
1092
1093 /*
1094  * Force the spilling of the variable in the symbolic register 'reg'.
1095  */
1096 static int
1097 get_register_force_spilling (MonoCompile *cfg, InstList *item, MonoInst *ins, int reg)
1098 {
1099         MonoInst *load;
1100         int i, sel, spill;
1101         
1102         sel = cfg->rs->iassign [reg];
1103         /*i = cfg->rs->isymbolic [sel];
1104         g_assert (i == reg);*/
1105         i = reg;
1106         spill = ++cfg->spill_count;
1107         cfg->rs->iassign [i] = -spill - 1;
1108         mono_regstate_free_int (cfg->rs, sel);
1109         /* we need to create a spill var and insert a load to sel after the current instruction */
1110         MONO_INST_NEW (cfg, load, OP_LOAD_MEMBASE);
1111         load->dreg = sel;
1112         load->inst_basereg = X86_EBP;
1113         load->inst_offset = mono_spillvar_offset (cfg, spill);
1114         if (item->prev) {
1115                 while (ins->next != item->prev->data)
1116                         ins = ins->next;
1117         }
1118         load->next = ins->next;
1119         ins->next = load;
1120         DEBUG (g_print ("SPILLED LOAD (%d at 0x%08x(%%ebp)) R%d (freed %s)\n", spill, load->inst_offset, i, mono_arch_regname (sel)));
1121         i = mono_regstate_alloc_int (cfg->rs, 1 << sel);
1122         g_assert (i == sel);
1123
1124         return sel;
1125 }
1126
1127 static int
1128 get_register_spilling (MonoCompile *cfg, InstList *item, MonoInst *ins, guint32 regmask, int reg)
1129 {
1130         MonoInst *load;
1131         int i, sel, spill;
1132
1133         DEBUG (g_print ("start regmask to assign R%d: 0x%08x (R%d <- R%d R%d)\n", reg, regmask, ins->dreg, ins->sreg1, ins->sreg2));
1134         /* exclude the registers in the current instruction */
1135         if (reg != ins->sreg1 && (reg_is_freeable (ins->sreg1) || (ins->sreg1 >= MONO_MAX_IREGS && cfg->rs->iassign [ins->sreg1] >= 0))) {
1136                 if (ins->sreg1 >= MONO_MAX_IREGS)
1137                         regmask &= ~ (1 << cfg->rs->iassign [ins->sreg1]);
1138                 else
1139                         regmask &= ~ (1 << ins->sreg1);
1140                 DEBUG (g_print ("excluding sreg1 %s\n", mono_arch_regname (ins->sreg1)));
1141         }
1142         if (reg != ins->sreg2 && (reg_is_freeable (ins->sreg2) || (ins->sreg2 >= MONO_MAX_IREGS && cfg->rs->iassign [ins->sreg2] >= 0))) {
1143                 if (ins->sreg2 >= MONO_MAX_IREGS)
1144                         regmask &= ~ (1 << cfg->rs->iassign [ins->sreg2]);
1145                 else
1146                         regmask &= ~ (1 << ins->sreg2);
1147                 DEBUG (g_print ("excluding sreg2 %s %d\n", mono_arch_regname (ins->sreg2), ins->sreg2));
1148         }
1149         if (reg != ins->dreg && reg_is_freeable (ins->dreg)) {
1150                 regmask &= ~ (1 << ins->dreg);
1151                 DEBUG (g_print ("excluding dreg %s\n", mono_arch_regname (ins->dreg)));
1152         }
1153
1154         DEBUG (g_print ("available regmask: 0x%08x\n", regmask));
1155         g_assert (regmask); /* need at least a register we can free */
1156         sel = -1;
1157         /* we should track prev_use and spill the register that's farther */
1158         for (i = 0; i < MONO_MAX_IREGS; ++i) {
1159                 if (regmask & (1 << i)) {
1160                         sel = i;
1161                         DEBUG (g_print ("selected register %s has assignment %d\n", mono_arch_regname (sel), cfg->rs->iassign [sel]));
1162                         break;
1163                 }
1164         }
1165         i = cfg->rs->isymbolic [sel];
1166         spill = ++cfg->spill_count;
1167         cfg->rs->iassign [i] = -spill - 1;
1168         mono_regstate_free_int (cfg->rs, sel);
1169         /* we need to create a spill var and insert a load to sel after the current instruction */
1170         MONO_INST_NEW (cfg, load, OP_LOAD_MEMBASE);
1171         load->dreg = sel;
1172         load->inst_basereg = X86_EBP;
1173         load->inst_offset = mono_spillvar_offset (cfg, spill);
1174         if (item->prev) {
1175                 while (ins->next != item->prev->data)
1176                         ins = ins->next;
1177         }
1178         load->next = ins->next;
1179         ins->next = load;
1180         DEBUG (g_print ("SPILLED LOAD (%d at 0x%08x(%%ebp)) R%d (freed %s)\n", spill, load->inst_offset, i, mono_arch_regname (sel)));
1181         i = mono_regstate_alloc_int (cfg->rs, 1 << sel);
1182         g_assert (i == sel);
1183         
1184         return sel;
1185 }
1186
1187 static MonoInst*
1188 create_copy_ins (MonoCompile *cfg, int dest, int src, MonoInst *ins)
1189 {
1190         MonoInst *copy;
1191         MONO_INST_NEW (cfg, copy, OP_MOVE);
1192         copy->dreg = dest;
1193         copy->sreg1 = src;
1194         if (ins) {
1195                 copy->next = ins->next;
1196                 ins->next = copy;
1197         }
1198         DEBUG (g_print ("\tforced copy from %s to %s\n", mono_arch_regname (src), mono_arch_regname (dest)));
1199         return copy;
1200 }
1201
1202 static MonoInst*
1203 create_spilled_store (MonoCompile *cfg, int spill, int reg, int prev_reg, MonoInst *ins)
1204 {
1205         MonoInst *store;
1206         MONO_INST_NEW (cfg, store, OP_STORE_MEMBASE_REG);
1207         store->sreg1 = reg;
1208         store->inst_destbasereg = X86_EBP;
1209         store->inst_offset = mono_spillvar_offset (cfg, spill);
1210         if (ins) {
1211                 store->next = ins->next;
1212                 ins->next = store;
1213         }
1214         DEBUG (g_print ("SPILLED STORE (%d at 0x%08x(%%ebp)) R%d (from %s)\n", spill, store->inst_offset, prev_reg, mono_arch_regname (reg)));
1215         return store;
1216 }
1217
1218 static void
1219 insert_before_ins (MonoInst *ins, InstList *item, MonoInst* to_insert)
1220 {
1221         MonoInst *prev;
1222         if (item->next) {
1223                 prev = item->next->data;
1224
1225                 while (prev->next != ins)
1226                         prev = prev->next;
1227                 to_insert->next = ins;
1228                 prev->next = to_insert;
1229         } else {
1230                 to_insert->next = ins;
1231         }
1232         /* 
1233          * needed otherwise in the next instruction we can add an ins to the 
1234          * end and that would get past this instruction.
1235          */
1236         item->data = to_insert; 
1237 }
1238
1239
1240 #if  0
1241 static int
1242 alloc_int_reg (MonoCompile *cfg, InstList *curinst, MonoInst *ins, int sym_reg, guint32 allow_mask)
1243 {
1244         int val = cfg->rs->iassign [sym_reg];
1245         if (val < 0) {
1246                 int spill = 0;
1247                 if (val < -1) {
1248                         /* the register gets spilled after this inst */
1249                         spill = -val -1;
1250                 }
1251                 val = mono_regstate_alloc_int (cfg->rs, allow_mask);
1252                 if (val < 0)
1253                         val = get_register_spilling (cfg, curinst, ins, allow_mask, sym_reg);
1254                 cfg->rs->iassign [sym_reg] = val;
1255                 /* add option to store before the instruction for src registers */
1256                 if (spill)
1257                         create_spilled_store (cfg, spill, val, sym_reg, ins);
1258         }
1259         cfg->rs->isymbolic [val] = sym_reg;
1260         return val;
1261 }
1262 #endif
1263
1264 /* flags used in reginfo->flags */
1265 #define MONO_X86_FP_NEEDS_LOAD_SPILL    1
1266 #define MONO_X86_FP_NEEDS_SPILL                 2
1267 #define MONO_X86_FP_NEEDS_LOAD                  4
1268
1269 /*#include "cprop.c"*/
1270
1271 /*
1272  * Local register allocation.
1273  * We first scan the list of instructions and we save the liveness info of
1274  * each register (when the register is first used, when it's value is set etc.).
1275  * We also reverse the list of instructions (in the InstList list) because assigning
1276  * registers backwards allows for more tricks to be used.
1277  */
1278 void
1279 mono_arch_local_regalloc (MonoCompile *cfg, MonoBasicBlock *bb)
1280 {
1281         MonoInst *ins;
1282         MonoRegState *rs = cfg->rs;
1283         int i, val, fpcount;
1284         RegTrack *reginfo, *reginfof;
1285         RegTrack *reginfo1, *reginfo2, *reginfod;
1286         InstList *tmp, *reversed = NULL;
1287         const char *spec;
1288         guint32 src1_mask, src2_mask, dest_mask;
1289         GList *fspill_list = NULL;
1290         int fspill = 0;
1291
1292         if (!bb->code)
1293                 return;
1294         rs->next_vireg = bb->max_ireg;
1295         rs->next_vfreg = bb->max_freg;
1296         mono_regstate_assign (rs);
1297         reginfo = g_malloc0 (sizeof (RegTrack) * rs->next_vireg);
1298         reginfof = g_malloc0 (sizeof (RegTrack) * rs->next_vfreg);
1299         rs->ifree_mask = X86_CALLEE_REGS;
1300
1301         ins = bb->code;
1302
1303         /*if (cfg->opt & MONO_OPT_COPYPROP)
1304                 local_copy_prop (cfg, ins);*/
1305
1306         i = 1;
1307         fpcount = 0;
1308         DEBUG (g_print ("LOCAL regalloc: basic block: %d\n", bb->block_num));
1309         /* forward pass on the instructions to collect register liveness info */
1310         while (ins) {
1311                 spec = ins_spec [ins->opcode];
1312                 
1313                 DEBUG (print_ins (i, ins));
1314
1315                 if (spec [MONO_INST_SRC1]) {
1316                         if (spec [MONO_INST_SRC1] == 'f') {
1317                                 GList *spill;
1318                                 reginfo1 = reginfof;
1319
1320                                 spill = g_list_first (fspill_list);
1321                                 if (spill && fpcount < MONO_MAX_FREGS) {
1322                                         reginfo1 [ins->sreg1].flags |= MONO_X86_FP_NEEDS_LOAD;
1323                                         fspill_list = g_list_remove (fspill_list, spill->data);
1324                                 } else
1325                                         fpcount--;
1326                         }
1327                         else
1328                                 reginfo1 = reginfo;
1329                         reginfo1 [ins->sreg1].prev_use = reginfo1 [ins->sreg1].last_use;
1330                         reginfo1 [ins->sreg1].last_use = i;
1331                         if (spec [MONO_INST_SRC1] == 'L') {
1332                                 /* The virtual register is allocated sequentially */
1333                                 reginfo1 [ins->sreg1 + 1].prev_use = reginfo1 [ins->sreg1 + 1].last_use;
1334                                 reginfo1 [ins->sreg1 + 1].last_use = i;
1335                                 if (reginfo1 [ins->sreg1 + 1].born_in == 0 || reginfo1 [ins->sreg1 + 1].born_in > i)
1336                                         reginfo1 [ins->sreg1 + 1].born_in = i;
1337                         }
1338                 } else {
1339                         ins->sreg1 = -1;
1340                 }
1341                 if (spec [MONO_INST_SRC2]) {
1342                         if (spec [MONO_INST_SRC2] == 'f') {
1343                                 GList *spill;
1344                                 reginfo2 = reginfof;
1345                                 spill = g_list_first (fspill_list);
1346                                 if (spill) {
1347                                         reginfo2 [ins->sreg2].flags |= MONO_X86_FP_NEEDS_LOAD;
1348                                         fspill_list = g_list_remove (fspill_list, spill->data);
1349                                         if (fpcount >= MONO_MAX_FREGS) {
1350                                                 fspill++;
1351                                                 fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1352                                                 reginfo2 [ins->sreg2].flags |= MONO_X86_FP_NEEDS_LOAD_SPILL;
1353                                         }
1354                                 } else
1355                                         fpcount--;
1356                         }
1357                         else
1358                                 reginfo2 = reginfo;
1359                         reginfo2 [ins->sreg2].prev_use = reginfo2 [ins->sreg2].last_use;
1360                         reginfo2 [ins->sreg2].last_use = i;
1361                         if (spec [MONO_INST_SRC2] == 'L') {
1362                                 /* The virtual register is allocated sequentially */
1363                                 reginfo2 [ins->sreg2 + 1].prev_use = reginfo2 [ins->sreg2 + 1].last_use;
1364                                 reginfo2 [ins->sreg2 + 1].last_use = i;
1365                                 if (reginfo2 [ins->sreg2 + 1].born_in == 0 || reginfo2 [ins->sreg2 + 1].born_in > i)
1366                                         reginfo2 [ins->sreg2 + 1].born_in = i;
1367                         }
1368                 } else {
1369                         ins->sreg2 = -1;
1370                 }
1371                 if (spec [MONO_INST_DEST]) {
1372                         if (spec [MONO_INST_DEST] == 'f') {
1373                                 reginfod = reginfof;
1374                                 if (fpcount >= MONO_MAX_FREGS) {
1375                                         reginfod [ins->dreg].flags |= MONO_X86_FP_NEEDS_SPILL;
1376                                         fspill++;
1377                                         fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1378                                         fpcount--;
1379                                 }
1380                                 fpcount++;
1381                         }
1382                         else
1383                                 reginfod = reginfo;
1384                         if (spec [MONO_INST_DEST] != 'b') /* it's not just a base register */
1385                                 reginfod [ins->dreg].killed_in = i;
1386                         reginfod [ins->dreg].prev_use = reginfod [ins->dreg].last_use;
1387                         reginfod [ins->dreg].last_use = i;
1388                         if (reginfod [ins->dreg].born_in == 0 || reginfod [ins->dreg].born_in > i)
1389                                 reginfod [ins->dreg].born_in = i;
1390                         if (spec [MONO_INST_DEST] == 'l' || spec [MONO_INST_DEST] == 'L') {
1391                                 /* The virtual register is allocated sequentially */
1392                                 reginfod [ins->dreg + 1].prev_use = reginfod [ins->dreg + 1].last_use;
1393                                 reginfod [ins->dreg + 1].last_use = i;
1394                                 if (reginfod [ins->dreg + 1].born_in == 0 || reginfod [ins->dreg + 1].born_in > i)
1395                                         reginfod [ins->dreg + 1].born_in = i;
1396                         } 
1397                 } else {
1398                         ins->dreg = -1;
1399                 }
1400                 reversed = inst_list_prepend (cfg->mempool, reversed, ins);
1401                 ++i;
1402                 ins = ins->next;
1403         }
1404
1405         // todo: check if we have anything left on fp stack, in verify mode?
1406         fspill = 0;
1407
1408         DEBUG (print_regtrack (reginfo, rs->next_vireg));
1409         DEBUG (print_regtrack (reginfof, rs->next_vfreg));
1410         tmp = reversed;
1411         while (tmp) {
1412                 int prev_dreg, prev_sreg1, prev_sreg2, clob_dreg;
1413                 dest_mask = src1_mask = src2_mask = X86_CALLEE_REGS;
1414                 --i;
1415                 ins = tmp->data;
1416                 spec = ins_spec [ins->opcode];
1417                 prev_dreg = -1;
1418                 clob_dreg = -1;
1419                 DEBUG (g_print ("processing:"));
1420                 DEBUG (print_ins (i, ins));
1421                 if (spec [MONO_INST_CLOB] == 's') {
1422                         if (rs->ifree_mask & (1 << X86_ECX)) {
1423                                 DEBUG (g_print ("\tshortcut assignment of R%d to ECX\n", ins->sreg2));
1424                                 rs->iassign [ins->sreg2] = X86_ECX;
1425                                 rs->isymbolic [X86_ECX] = ins->sreg2;
1426                                 ins->sreg2 = X86_ECX;
1427                                 rs->ifree_mask &= ~ (1 << X86_ECX);
1428                         } else {
1429                                 int need_ecx_spill = TRUE;
1430                                 /* 
1431                                  * we first check if src1/dreg is already assigned a register
1432                                  * and then we force a spill of the var assigned to ECX.
1433                                  */
1434                                 /* the destination register can't be ECX */
1435                                 dest_mask &= ~ (1 << X86_ECX);
1436                                 src1_mask &= ~ (1 << X86_ECX);
1437                                 val = rs->iassign [ins->dreg];
1438                                 /* 
1439                                  * the destination register is already assigned to ECX:
1440                                  * we need to allocate another register for it and then
1441                                  * copy from this to ECX.
1442                                  */
1443                                 if (val == X86_ECX && ins->dreg != ins->sreg2) {
1444                                         int new_dest = mono_regstate_alloc_int (rs, dest_mask);
1445                                         if (new_dest < 0)
1446                                                 new_dest = get_register_spilling (cfg, tmp, ins, dest_mask, ins->dreg);
1447                                         g_assert (new_dest >= 0);
1448                                         DEBUG (g_print ("\tclob:s changing dreg from R%d to %s (val = %d)\n", ins->dreg, mono_arch_regname (new_dest), val));
1449                                         clob_dreg = ins->dreg;
1450                                         ins->dreg = new_dest;
1451                                         create_copy_ins (cfg, X86_ECX, new_dest, ins);
1452                                         need_ecx_spill = FALSE;
1453                                         /*DEBUG (g_print ("\tforced spill of R%d\n", ins->dreg));
1454                                         val = get_register_force_spilling (cfg, tmp, ins, ins->dreg);
1455                                         rs->iassign [ins->dreg] = val;
1456                                         rs->isymbolic [val] = prev_dreg;
1457                                         ins->dreg = val;*/
1458                                 }
1459                                 val = rs->iassign [ins->sreg1];
1460                                 if (val == X86_ECX) {
1461                                         g_assert_not_reached ();
1462                                 } else if (val >= 0) {
1463                                         /* 
1464                                          * the first src reg was already assigned to a register,
1465                                          * we need to copy it to the dest register because the 
1466                                          * shift instruction clobbers the first operand.
1467                                          */
1468                                         MonoInst *copy = create_copy_ins (cfg, ins->dreg, val, NULL);
1469                                         DEBUG (g_print ("\tclob:s moved sreg1 from R%d to R%d\n", val, ins->dreg));
1470                                         insert_before_ins (ins, tmp, copy);
1471                                 }
1472                                 val = rs->iassign [ins->sreg2];
1473                                 if (val >= 0 && val != X86_ECX) {
1474                                         MonoInst *move = create_copy_ins (cfg, X86_ECX, val, NULL);
1475                                         DEBUG (g_print ("\tmoved arg from R%d (%d) to ECX\n", val, ins->sreg2));
1476                                         move->next = ins;
1477                                         g_assert_not_reached ();
1478                                         /* FIXME: where is move connected to the instruction list? */
1479                                         //tmp->prev->data->next = move;
1480                                 }
1481                                 if (need_ecx_spill && !(rs->ifree_mask & (1 << X86_ECX))) {
1482                                         DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [X86_ECX]));
1483                                         get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_ECX]);
1484                                         mono_regstate_free_int (rs, X86_ECX);
1485                                 }
1486                                 /* force-set sreg2 */
1487                                 rs->iassign [ins->sreg2] = X86_ECX;
1488                                 rs->isymbolic [X86_ECX] = ins->sreg2;
1489                                 ins->sreg2 = X86_ECX;
1490                                 rs->ifree_mask &= ~ (1 << X86_ECX);
1491                         }
1492                 } else if (spec [MONO_INST_CLOB] == 'd') { /* division */
1493                         int dest_reg = X86_EAX;
1494                         int clob_reg = X86_EDX;
1495                         if (spec [MONO_INST_DEST] == 'd') {
1496                                 dest_reg = X86_EDX; /* reminder */
1497                                 clob_reg = X86_EAX;
1498                         }
1499                         val = rs->iassign [ins->dreg];
1500                         if (0 && val >= 0 && val != dest_reg && !(rs->ifree_mask & (1 << dest_reg))) {
1501                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [dest_reg]));
1502                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [dest_reg]);
1503                                 mono_regstate_free_int (rs, dest_reg);
1504                         }
1505                         if (val < 0) {
1506                                 if (val < -1) {
1507                                         /* the register gets spilled after this inst */
1508                                         int spill = -val -1;
1509                                         dest_mask = 1 << clob_reg;
1510                                         prev_dreg = ins->dreg;
1511                                         val = mono_regstate_alloc_int (rs, dest_mask);
1512                                         if (val < 0)
1513                                                 val = get_register_spilling (cfg, tmp, ins, dest_mask, ins->dreg);
1514                                         rs->iassign [ins->dreg] = val;
1515                                         if (spill)
1516                                                 create_spilled_store (cfg, spill, val, prev_dreg, ins);
1517                                         DEBUG (g_print ("\tassigned dreg %s to dest R%d\n", mono_arch_regname (val), ins->dreg));
1518                                         rs->isymbolic [val] = prev_dreg;
1519                                         ins->dreg = val;
1520                                         if (val != dest_reg) { /* force a copy */
1521                                                 create_copy_ins (cfg, val, dest_reg, ins);
1522                                         }
1523                                 } else {
1524                                         DEBUG (g_print ("\tshortcut assignment of R%d to %s\n", ins->dreg, mono_arch_regname (dest_reg)));
1525                                         prev_dreg = ins->dreg;
1526                                         rs->iassign [ins->dreg] = dest_reg;
1527                                         rs->isymbolic [dest_reg] = ins->dreg;
1528                                         ins->dreg = dest_reg;
1529                                         rs->ifree_mask &= ~ (1 << dest_reg);
1530                                 }
1531                         } else {
1532                                 //DEBUG (g_print ("dest reg in div assigned: %s\n", mono_arch_regname (val)));
1533                                 if (val != dest_reg) { /* force a copy */
1534                                         create_copy_ins (cfg, val, dest_reg, ins);
1535                                         if (!(rs->ifree_mask & (1 << dest_reg)) && rs->isymbolic [dest_reg] >= MONO_MAX_IREGS) {
1536                                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [dest_reg]));
1537                                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [dest_reg]);
1538                                                 mono_regstate_free_int (rs, dest_reg);
1539                                         }
1540                                 }
1541                         }
1542                         if (!(rs->ifree_mask & (1 << clob_reg)) && (clob_reg != val) && (rs->isymbolic [clob_reg] >= 8)) {
1543                                 DEBUG (g_print ("\tforced spill of clobbered reg R%d\n", rs->isymbolic [clob_reg]));
1544                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [clob_reg]);
1545                                 mono_regstate_free_int (rs, clob_reg);
1546                         }
1547                         src1_mask = 1 << X86_EAX;
1548                         src2_mask = 1 << X86_ECX;
1549                 }
1550                 if (spec [MONO_INST_DEST] == 'l') {
1551                         if (!(rs->ifree_mask & (1 << X86_EAX))) {
1552                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [X86_EAX]));
1553                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_EAX]);
1554                                 mono_regstate_free_int (rs, X86_EAX);
1555                         }
1556                         if (!(rs->ifree_mask & (1 << X86_EDX))) {
1557                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [X86_EDX]));
1558                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_EDX]);
1559                                 mono_regstate_free_int (rs, X86_EDX);
1560                         }
1561                 }
1562
1563                 /* Track dreg */
1564                 if (spec [MONO_INST_DEST] == 'f') {
1565                         if (reginfof [ins->dreg].flags & MONO_X86_FP_NEEDS_SPILL) {
1566                                 GList *spill_node;
1567                                 MonoInst *store;
1568                                 spill_node = g_list_first (fspill_list);
1569                                 g_assert (spill_node);
1570
1571                                 store = create_spilled_store_float (cfg, GPOINTER_TO_INT (spill_node->data), ins->dreg, ins);
1572                                 insert_before_ins (ins, tmp, store);
1573                                 fspill_list = g_list_remove (fspill_list, spill_node->data);
1574                                 fspill--;
1575                         }
1576                 } else if (spec [MONO_INST_DEST] == 'L') {
1577                         int hreg;
1578                         val = rs->iassign [ins->dreg];
1579                         /* check special case when dreg have been moved from ecx (clob shift) */
1580                         if (spec [MONO_INST_CLOB] == 's' && clob_dreg != -1)
1581                                 hreg = clob_dreg + 1;
1582                         else
1583                                 hreg = ins->dreg + 1;
1584
1585                         /* base prev_dreg on fixed hreg, handle clob case */
1586                         prev_dreg = hreg - 1;
1587
1588                         if (val < 0) {
1589                                 int spill = 0;
1590                                 if (val < -1) {
1591                                         /* the register gets spilled after this inst */
1592                                         spill = -val -1;
1593                                 }
1594                                 val = mono_regstate_alloc_int (rs, dest_mask);
1595                                 if (val < 0) /* todo: should we force reg into eax, for opt reasons? */
1596                                         val = get_register_spilling (cfg, tmp, ins, dest_mask, ins->dreg);
1597                                 rs->iassign [ins->dreg] = val;
1598                                 if (spill)
1599                                         create_spilled_store (cfg, spill, val, prev_dreg, ins);
1600                         }
1601
1602                         DEBUG (g_print ("\tassigned dreg (long) %s to dest R%d\n", mono_arch_regname (val), hreg - 1));
1603
1604                         rs->isymbolic [val] = hreg - 1;
1605                         ins->dreg = val;
1606                         
1607                         val = rs->iassign [hreg];
1608                         if (val < 0) {
1609                                 int spill = 0;
1610                                 if (val < -1) {
1611                                         /* the register gets spilled after this inst */
1612                                         spill = -val -1;
1613                                 }
1614                                 val = mono_regstate_alloc_int (rs, dest_mask);
1615                                 if (val < 0) /* todo: should we force reg into edx, for opt reasons? */
1616                                         val = get_register_spilling (cfg, tmp, ins, dest_mask, hreg);
1617                                 rs->iassign [hreg] = val;
1618                                 if (spill)
1619                                         create_spilled_store (cfg, spill, val, hreg, ins);
1620                         }
1621
1622                         DEBUG (g_print ("\tassigned hreg (long) %s to dest R%d\n", mono_arch_regname (val), hreg));
1623                         rs->isymbolic [val] = hreg;
1624                         /* save reg allocating into unused */
1625                         ins->unused = val;
1626
1627                         if (reg_is_freeable (val) && hreg >= 0 && reginfo [hreg].born_in >= i) {
1628                                 DEBUG (g_print ("\tfreeable %s (R%d)\n", mono_arch_regname (val), hreg));
1629                                 mono_regstate_free_int (rs, val);
1630                         }
1631                 }
1632                 else if (ins->dreg >= MONO_MAX_IREGS) {
1633                         val = rs->iassign [ins->dreg];
1634                         prev_dreg = ins->dreg;
1635                         if (val < 0) {
1636                                 int spill = 0;
1637                                 if (val < -1) {
1638                                         /* the register gets spilled after this inst */
1639                                         spill = -val -1;
1640                                 }
1641                                 val = mono_regstate_alloc_int (rs, dest_mask);
1642                                 if (val < 0)
1643                                         val = get_register_spilling (cfg, tmp, ins, dest_mask, ins->dreg);
1644                                 rs->iassign [ins->dreg] = val;
1645                                 if (spill)
1646                                         create_spilled_store (cfg, spill, val, prev_dreg, ins);
1647                         }
1648                         DEBUG (g_print ("\tassigned dreg %s to dest R%d\n", mono_arch_regname (val), ins->dreg));
1649                         rs->isymbolic [val] = prev_dreg;
1650                         ins->dreg = val;
1651                         /* handle cases where lreg needs to be eax:edx */
1652                         if (spec [MONO_INST_DEST] == 'l') {
1653                                 int hreg = prev_dreg + 1;
1654                                 val = rs->iassign [hreg];
1655                                 if (val < 0) {
1656                                         int spill = 0;
1657                                         if (val < -1) {
1658                                                 /* the register gets spilled after this inst */
1659                                                 spill = -val -1;
1660                                         }
1661                                         val = mono_regstate_alloc_int (rs, dest_mask);
1662                                         if (val < 0)
1663                                                 val = get_register_spilling (cfg, tmp, ins, dest_mask, hreg);
1664                                         rs->iassign [hreg] = val;
1665                                         if (spill)
1666                                                 create_spilled_store (cfg, spill, val, hreg, ins);
1667                                 }
1668                                 DEBUG (g_print ("\tassigned hreg %s to dest R%d\n", mono_arch_regname (val), hreg));
1669                                 rs->isymbolic [val] = hreg;
1670                                 if (ins->dreg == X86_EAX) {
1671                                         if (val != X86_EDX)
1672                                                 create_copy_ins (cfg, val, X86_EDX, ins);
1673                                 } else if (ins->dreg == X86_EDX) {
1674                                         if (val == X86_EAX) {
1675                                                 /* swap */
1676                                                 g_assert_not_reached ();
1677                                         } else {
1678                                                 /* two forced copies */
1679                                                 create_copy_ins (cfg, val, X86_EDX, ins);
1680                                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1681                                         }
1682                                 } else {
1683                                         if (val == X86_EDX) {
1684                                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1685                                         } else {
1686                                                 /* two forced copies */
1687                                                 create_copy_ins (cfg, val, X86_EDX, ins);
1688                                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1689                                         }
1690                                 }
1691                                 if (reg_is_freeable (val) && hreg >= 0 && reginfo [hreg].born_in >= i) {
1692                                         DEBUG (g_print ("\tfreeable %s (R%d)\n", mono_arch_regname (val), hreg));
1693                                         mono_regstate_free_int (rs, val);
1694                                 }
1695                         } else if (spec [MONO_INST_DEST] == 'a' && ins->dreg != X86_EAX && spec [MONO_INST_CLOB] != 'd') {
1696                                 /* this instruction only outputs to EAX, need to copy */
1697                                 create_copy_ins (cfg, ins->dreg, X86_EAX, ins);
1698                         } else if (spec [MONO_INST_DEST] == 'd' && ins->dreg != X86_EDX && spec [MONO_INST_CLOB] != 'd') {
1699                                 create_copy_ins (cfg, ins->dreg, X86_EDX, ins);
1700                         }
1701                 }
1702                 if (spec [MONO_INST_DEST] != 'f' && reg_is_freeable (ins->dreg) && prev_dreg >= 0 && reginfo [prev_dreg].born_in >= i) {
1703                         DEBUG (g_print ("\tfreeable %s (R%d) (born in %d)\n", mono_arch_regname (ins->dreg), prev_dreg, reginfo [prev_dreg].born_in));
1704                         mono_regstate_free_int (rs, ins->dreg);
1705                 }
1706                 /* put src1 in EAX if it needs to be */
1707                 if (spec [MONO_INST_SRC1] == 'a') {
1708                         if (!(rs->ifree_mask & (1 << X86_EAX))) {
1709                                 DEBUG (g_print ("\tforced spill of R%d\n", rs->isymbolic [X86_EAX]));
1710                                 get_register_force_spilling (cfg, tmp, ins, rs->isymbolic [X86_EAX]);
1711                                 mono_regstate_free_int (rs, X86_EAX);
1712                         }
1713                         /* force-set sreg1 */
1714                         rs->iassign [ins->sreg1] = X86_EAX;
1715                         rs->isymbolic [X86_EAX] = ins->sreg1;
1716                         ins->sreg1 = X86_EAX;
1717                         rs->ifree_mask &= ~ (1 << X86_EAX);
1718                 }
1719
1720                 /* Track sreg1 */
1721                 if (spec [MONO_INST_SRC1] == 'f') {
1722                         if (reginfof [ins->sreg1].flags & MONO_X86_FP_NEEDS_LOAD) {
1723                                 MonoInst *load;
1724                                 MonoInst *store = NULL;
1725
1726                                 if (reginfof [ins->sreg1].flags & MONO_X86_FP_NEEDS_LOAD_SPILL) {
1727                                         GList *spill_node;
1728                                         spill_node = g_list_first (fspill_list);
1729                                         g_assert (spill_node);
1730
1731                                         store = create_spilled_store_float (cfg, GPOINTER_TO_INT (spill_node->data), ins->sreg1, ins);          
1732                                         fspill_list = g_list_remove (fspill_list, spill_node->data);
1733                                 }
1734
1735                                 fspill++;
1736                                 fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1737                                 load = create_spilled_load_float (cfg, fspill, ins->sreg1, ins);
1738                                 insert_before_ins (ins, tmp, load);
1739                                 if (store) 
1740                                         insert_before_ins (load, tmp, store);
1741                         }
1742                 } else if ((spec [MONO_INST_DEST] == 'L') && (spec [MONO_INST_SRC1] == 'L')) {
1743                         /* force source to be same as dest */
1744                         rs->iassign [ins->sreg1] = ins->dreg;
1745                         rs->iassign [ins->sreg1 + 1] = ins->unused;
1746
1747                         DEBUG (g_print ("\tassigned sreg1 (long) %s to sreg1 R%d\n", mono_arch_regname (ins->dreg), ins->sreg1));
1748                         DEBUG (g_print ("\tassigned sreg1 (long-high) %s to sreg1 R%d\n", mono_arch_regname (ins->unused), ins->sreg1 + 1));
1749
1750                         ins->sreg1 = ins->dreg;
1751                         /* no need for this, we know that src1=dest in this cases */
1752                         /*ins->inst_c0 = ins->unused;*/
1753
1754                         /* make sure that we remove them from free mask */
1755                         rs->ifree_mask &= ~ (1 << ins->dreg);
1756                         rs->ifree_mask &= ~ (1 << ins->unused);
1757                 }
1758                 else if (ins->sreg1 >= MONO_MAX_IREGS) {
1759                         val = rs->iassign [ins->sreg1];
1760                         prev_sreg1 = ins->sreg1;
1761                         if (val < 0) {
1762                                 int spill = 0;
1763                                 if (val < -1) {
1764                                         /* the register gets spilled after this inst */
1765                                         spill = -val -1;
1766                                 }
1767                                 if (0 && ins->opcode == OP_MOVE) {
1768                                         /* 
1769                                          * small optimization: the dest register is already allocated
1770                                          * but the src one is not: we can simply assign the same register
1771                                          * here and peephole will get rid of the instruction later.
1772                                          * This optimization may interfere with the clobbering handling:
1773                                          * it removes a mov operation that will be added again to handle clobbering.
1774                                          * There are also some other issues that should with make testjit.
1775                                          */
1776                                         mono_regstate_alloc_int (rs, 1 << ins->dreg);
1777                                         val = rs->iassign [ins->sreg1] = ins->dreg;
1778                                         //g_assert (val >= 0);
1779                                         DEBUG (g_print ("\tfast assigned sreg1 %s to R%d\n", mono_arch_regname (val), ins->sreg1));
1780                                 } else {
1781                                         //g_assert (val == -1); /* source cannot be spilled */
1782                                         val = mono_regstate_alloc_int (rs, src1_mask);
1783                                         if (val < 0)
1784                                                 val = get_register_spilling (cfg, tmp, ins, src1_mask, ins->sreg1);
1785                                         rs->iassign [ins->sreg1] = val;
1786                                         DEBUG (g_print ("\tassigned sreg1 %s to R%d\n", mono_arch_regname (val), ins->sreg1));
1787                                 }
1788                                 if (spill) {
1789                                         MonoInst *store = create_spilled_store (cfg, spill, val, prev_sreg1, NULL);
1790                                         insert_before_ins (ins, tmp, store);
1791                                 }
1792                         }
1793                         rs->isymbolic [val] = prev_sreg1;
1794                         ins->sreg1 = val;
1795                 } else {
1796                         prev_sreg1 = -1;
1797                 }
1798                 /* handle clobbering of sreg1 */
1799                 if ((spec [MONO_INST_CLOB] == '1' || spec [MONO_INST_CLOB] == 's') && ins->dreg != ins->sreg1) {
1800                         MonoInst *copy = create_copy_ins (cfg, ins->dreg, ins->sreg1, NULL);
1801                         DEBUG (g_print ("\tneed to copy sreg1 %s to dreg %s\n", mono_arch_regname (ins->sreg1), mono_arch_regname (ins->dreg)));
1802                         if (ins->sreg2 == -1 || spec [MONO_INST_CLOB] == 's') {
1803                                 /* note: the copy is inserted before the current instruction! */
1804                                 insert_before_ins (ins, tmp, copy);
1805                                 /* we set sreg1 to dest as well */
1806                                 prev_sreg1 = ins->sreg1 = ins->dreg;
1807                         } else {
1808                                 /* inserted after the operation */
1809                                 copy->next = ins->next;
1810                                 ins->next = copy;
1811                         }
1812                 }
1813                 /* track sreg2 */
1814                 if (spec [MONO_INST_SRC2] == 'f') {
1815                         if (reginfof [ins->sreg2].flags & MONO_X86_FP_NEEDS_LOAD) {
1816                                 MonoInst *load;
1817                                 MonoInst *store = NULL;
1818
1819                                 if (reginfof [ins->sreg2].flags & MONO_X86_FP_NEEDS_LOAD_SPILL) {
1820                                         GList *spill_node;
1821
1822                                         spill_node = g_list_first (fspill_list);
1823                                         g_assert (spill_node);
1824                                         if (spec [MONO_INST_SRC1] == 'f' && (reginfof [ins->sreg1].flags & MONO_X86_FP_NEEDS_LOAD_SPILL))
1825                                                 spill_node = g_list_next (spill_node);
1826         
1827                                         store = create_spilled_store_float (cfg, GPOINTER_TO_INT (spill_node->data), ins->sreg2, ins);
1828                                         fspill_list = g_list_remove (fspill_list, spill_node->data);
1829                                 } 
1830                                 
1831                                 fspill++;
1832                                 fspill_list = g_list_prepend (fspill_list, GINT_TO_POINTER(fspill));
1833                                 load = create_spilled_load_float (cfg, fspill, ins->sreg2, ins);
1834                                 insert_before_ins (ins, tmp, load);
1835                                 if (store) 
1836                                         insert_before_ins (load, tmp, store);
1837                         }
1838                 } 
1839                 else if (ins->sreg2 >= MONO_MAX_IREGS) {
1840                         val = rs->iassign [ins->sreg2];
1841                         prev_sreg2 = ins->sreg2;
1842                         if (val < 0) {
1843                                 int spill = 0;
1844                                 if (val < -1) {
1845                                         /* the register gets spilled after this inst */
1846                                         spill = -val -1;
1847                                 }
1848                                 val = mono_regstate_alloc_int (rs, src2_mask);
1849                                 if (val < 0)
1850                                         val = get_register_spilling (cfg, tmp, ins, src2_mask, ins->sreg2);
1851                                 rs->iassign [ins->sreg2] = val;
1852                                 DEBUG (g_print ("\tassigned sreg2 %s to R%d\n", mono_arch_regname (val), ins->sreg2));
1853                                 if (spill)
1854                                         create_spilled_store (cfg, spill, val, prev_sreg2, ins);
1855                         }
1856                         rs->isymbolic [val] = prev_sreg2;
1857                         ins->sreg2 = val;
1858                         if (spec [MONO_INST_CLOB] == 's' && ins->sreg2 != X86_ECX) {
1859                                 DEBUG (g_print ("\tassigned sreg2 %s to R%d, but ECX is needed (R%d)\n", mono_arch_regname (val), ins->sreg2, rs->iassign [X86_ECX]));
1860                         }
1861                 } else {
1862                         prev_sreg2 = -1;
1863                 }
1864
1865                 if (spec [MONO_INST_CLOB] == 'c') {
1866                         int j, s;
1867                         guint32 clob_mask = X86_CALLEE_REGS;
1868                         for (j = 0; j < MONO_MAX_IREGS; ++j) {
1869                                 s = 1 << j;
1870                                 if ((clob_mask & s) && !(rs->ifree_mask & s) && j != ins->sreg1) {
1871                                         //g_warning ("register %s busy at call site\n", mono_arch_regname (j));
1872                                 }
1873                         }
1874                 }
1875                 /*if (reg_is_freeable (ins->sreg1) && prev_sreg1 >= 0 && reginfo [prev_sreg1].born_in >= i) {
1876                         DEBUG (g_print ("freeable %s\n", mono_arch_regname (ins->sreg1)));
1877                         mono_regstate_free_int (rs, ins->sreg1);
1878                 }
1879                 if (reg_is_freeable (ins->sreg2) && prev_sreg2 >= 0 && reginfo [prev_sreg2].born_in >= i) {
1880                         DEBUG (g_print ("freeable %s\n", mono_arch_regname (ins->sreg2)));
1881                         mono_regstate_free_int (rs, ins->sreg2);
1882                 }*/
1883         
1884                 //DEBUG (print_ins (i, ins));
1885                 /* this may result from a insert_before call */
1886                 if (!tmp->next)
1887                         bb->code = tmp->data;
1888                 tmp = tmp->next;
1889         }
1890
1891         g_free (reginfo);
1892         g_free (reginfof);
1893         g_list_free (fspill_list);
1894 }
1895
1896 static unsigned char*
1897 emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int size, gboolean is_signed)
1898 {
1899         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4);
1900         x86_fnstcw_membase(code, X86_ESP, 0);
1901         x86_mov_reg_membase (code, dreg, X86_ESP, 0, 2);
1902         x86_alu_reg_imm (code, X86_OR, dreg, 0xc00);
1903         x86_mov_membase_reg (code, X86_ESP, 2, dreg, 2);
1904         x86_fldcw_membase (code, X86_ESP, 2);
1905         if (size == 8) {
1906                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
1907                 x86_fist_pop_membase (code, X86_ESP, 0, TRUE);
1908                 x86_pop_reg (code, dreg);
1909                 /* FIXME: need the high register 
1910                  * x86_pop_reg (code, dreg_high);
1911                  */
1912         } else {
1913                 x86_push_reg (code, X86_EAX); // SP = SP - 4
1914                 x86_fist_pop_membase (code, X86_ESP, 0, FALSE);
1915                 x86_pop_reg (code, dreg);
1916         }
1917         x86_fldcw_membase (code, X86_ESP, 0);
1918         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
1919
1920         if (size == 1)
1921                 x86_widen_reg (code, dreg, dreg, is_signed, FALSE);
1922         else if (size == 2)
1923                 x86_widen_reg (code, dreg, dreg, is_signed, TRUE);
1924         return code;
1925 }
1926
1927 static unsigned char*
1928 mono_emit_stack_alloc (guchar *code, MonoInst* tree)
1929 {
1930         int sreg = tree->sreg1;
1931 #ifdef PLATFORM_WIN32
1932         guint8* br[5];
1933
1934         /*
1935          * Under Windows:
1936          * If requested stack size is larger than one page,
1937          * perform stack-touch operation
1938          */
1939         /*
1940          * Generate stack probe code.
1941          * Under Windows, it is necessary to allocate one page at a time,
1942          * "touching" stack after each successful sub-allocation. This is
1943          * because of the way stack growth is implemented - there is a
1944          * guard page before the lowest stack page that is currently commited.
1945          * Stack normally grows sequentially so OS traps access to the
1946          * guard page and commits more pages when needed.
1947          */
1948         x86_test_reg_imm (code, sreg, ~0xFFF);
1949         br[0] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
1950
1951         br[2] = code; /* loop */
1952         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x1000);
1953         x86_test_membase_reg (code, X86_ESP, 0, X86_ESP);
1954         x86_alu_reg_imm (code, X86_SUB, sreg, 0x1000);
1955         x86_alu_reg_imm (code, X86_CMP, sreg, 0x1000);
1956         br[3] = code; x86_branch8 (code, X86_CC_AE, 0, FALSE);
1957         x86_patch (br[3], br[2]);
1958         x86_test_reg_reg (code, sreg, sreg);
1959         br[4] = code; x86_branch8 (code, X86_CC_Z, 0, FALSE);
1960         x86_alu_reg_reg (code, X86_SUB, X86_ESP, sreg);
1961
1962         br[1] = code; x86_jump8 (code, 0);
1963
1964         x86_patch (br[0], code);
1965         x86_alu_reg_reg (code, X86_SUB, X86_ESP, sreg);
1966         x86_patch (br[1], code);
1967         x86_patch (br[4], code);
1968 #else /* PLATFORM_WIN32 */
1969         x86_alu_reg_reg (code, X86_SUB, X86_ESP, tree->sreg1);
1970 #endif
1971         if (tree->flags & MONO_INST_INIT) {
1972                 int offset = 0;
1973                 if (tree->dreg != X86_EAX && sreg != X86_EAX) {
1974                         x86_push_reg (code, X86_EAX);
1975                         offset += 4;
1976                 }
1977                 if (tree->dreg != X86_ECX && sreg != X86_ECX) {
1978                         x86_push_reg (code, X86_ECX);
1979                         offset += 4;
1980                 }
1981                 if (tree->dreg != X86_EDI && sreg != X86_EDI) {
1982                         x86_push_reg (code, X86_EDI);
1983                         offset += 4;
1984                 }
1985                 
1986                 x86_shift_reg_imm (code, X86_SHR, sreg, 2);
1987                 if (sreg != X86_ECX)
1988                         x86_mov_reg_reg (code, X86_ECX, sreg, 4);
1989                 x86_alu_reg_reg (code, X86_XOR, X86_EAX, X86_EAX);
1990                                 
1991                 x86_lea_membase (code, X86_EDI, X86_ESP, offset);
1992                 x86_cld (code);
1993                 x86_prefix (code, X86_REP_PREFIX);
1994                 x86_stosl (code);
1995                 
1996                 if (tree->dreg != X86_EDI && sreg != X86_EDI)
1997                         x86_pop_reg (code, X86_EDI);
1998                 if (tree->dreg != X86_ECX && sreg != X86_ECX)
1999                         x86_pop_reg (code, X86_ECX);
2000                 if (tree->dreg != X86_EAX && sreg != X86_EAX)
2001                         x86_pop_reg (code, X86_EAX);
2002         }
2003         return code;
2004 }
2005
2006 #define REAL_PRINT_REG(text,reg) \
2007 mono_assert (reg >= 0); \
2008 x86_push_reg (code, X86_EAX); \
2009 x86_push_reg (code, X86_EDX); \
2010 x86_push_reg (code, X86_ECX); \
2011 x86_push_reg (code, reg); \
2012 x86_push_imm (code, reg); \
2013 x86_push_imm (code, text " %d %p\n"); \
2014 x86_mov_reg_imm (code, X86_EAX, printf); \
2015 x86_call_reg (code, X86_EAX); \
2016 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 3*4); \
2017 x86_pop_reg (code, X86_ECX); \
2018 x86_pop_reg (code, X86_EDX); \
2019 x86_pop_reg (code, X86_EAX);
2020
2021 void
2022 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
2023 {
2024         MonoInst *ins;
2025         MonoCallInst *call;
2026         guint offset;
2027         guint8 *code = cfg->native_code + cfg->code_len;
2028         MonoInst *last_ins = NULL;
2029         guint last_offset = 0;
2030         int max_len, cpos;
2031
2032         if (cfg->opt & MONO_OPT_PEEPHOLE)
2033                 peephole_pass (cfg, bb);
2034
2035         if (cfg->opt & MONO_OPT_LOOP) {
2036                 int pad, align = 8;
2037                 /* set alignment depending on cpu */
2038                 if (bb->nesting && (bb->in_count == 1) && (pad = (cfg->code_len & (align - 1)))) {
2039                         pad = align - pad;
2040                         /*g_print ("adding %d pad at %x to loop in %s\n", pad, cfg->code_len, cfg->method->name);*/
2041                         x86_padding (code, pad);
2042                         cfg->code_len += pad;
2043                         bb->native_offset = cfg->code_len;
2044                 }
2045         }
2046
2047         if (cfg->verbose_level > 2)
2048                 g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset);
2049
2050         cpos = bb->max_offset;
2051
2052         if (cfg->prof_options & MONO_PROFILE_COVERAGE) {
2053                 MonoProfileCoverageInfo *cov = cfg->coverage_info;
2054                 g_assert (!mono_compile_aot);
2055                 cpos += 6;
2056
2057                 cov->data [bb->dfn].cil_code = bb->cil_code;
2058                 /* this is not thread save, but good enough */
2059                 x86_inc_mem (code, &cov->data [bb->dfn].count); 
2060         }
2061
2062         offset = code - cfg->native_code;
2063
2064         ins = bb->code;
2065         while (ins) {
2066                 offset = code - cfg->native_code;
2067
2068                 max_len = ((guint8 *)ins_spec [ins->opcode])[MONO_INST_LEN];
2069
2070                 if (offset > (cfg->code_size - max_len - 16)) {
2071                         cfg->code_size *= 2;
2072                         cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
2073                         code = cfg->native_code + offset;
2074                         mono_jit_stats.code_reallocs++;
2075                 }
2076
2077                 mono_debug_record_line_number (cfg, ins, offset);
2078
2079                 switch (ins->opcode) {
2080                 case OP_BIGMUL:
2081                         x86_mul_reg (code, ins->sreg2, TRUE);
2082                         break;
2083                 case OP_BIGMUL_UN:
2084                         x86_mul_reg (code, ins->sreg2, FALSE);
2085                         break;
2086                 case OP_X86_SETEQ_MEMBASE:
2087                         x86_set_membase (code, X86_CC_EQ, ins->inst_basereg, ins->inst_offset, TRUE);
2088                         break;
2089                 case OP_STOREI1_MEMBASE_IMM:
2090                         x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 1);
2091                         break;
2092                 case OP_STOREI2_MEMBASE_IMM:
2093                         x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 2);
2094                         break;
2095                 case OP_STORE_MEMBASE_IMM:
2096                 case OP_STOREI4_MEMBASE_IMM:
2097                         x86_mov_membase_imm (code, ins->inst_destbasereg, ins->inst_offset, ins->inst_imm, 4);
2098                         break;
2099                 case OP_STOREI1_MEMBASE_REG:
2100                         x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 1);
2101                         break;
2102                 case OP_STOREI2_MEMBASE_REG:
2103                         x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 2);
2104                         break;
2105                 case OP_STORE_MEMBASE_REG:
2106                 case OP_STOREI4_MEMBASE_REG:
2107                         x86_mov_membase_reg (code, ins->inst_destbasereg, ins->inst_offset, ins->sreg1, 4);
2108                         break;
2109                 case CEE_LDIND_I:
2110                 case CEE_LDIND_I4:
2111                 case CEE_LDIND_U4:
2112                         x86_mov_reg_mem (code, ins->dreg, ins->inst_p0, 4);
2113                         break;
2114                 case OP_LOADU4_MEM:
2115                         x86_mov_reg_imm (code, ins->dreg, ins->inst_p0);
2116                         x86_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4);
2117                         break;
2118                 case OP_LOAD_MEMBASE:
2119                 case OP_LOADI4_MEMBASE:
2120                 case OP_LOADU4_MEMBASE:
2121                         x86_mov_reg_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, 4);
2122                         break;
2123                 case OP_LOADU1_MEMBASE:
2124                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, FALSE);
2125                         break;
2126                 case OP_LOADI1_MEMBASE:
2127                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, FALSE);
2128                         break;
2129                 case OP_LOADU2_MEMBASE:
2130                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, FALSE, TRUE);
2131                         break;
2132                 case OP_LOADI2_MEMBASE:
2133                         x86_widen_membase (code, ins->dreg, ins->inst_basereg, ins->inst_offset, TRUE, TRUE);
2134                         break;
2135                 case CEE_CONV_I1:
2136                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
2137                         break;
2138                 case CEE_CONV_I2:
2139                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
2140                         break;
2141                 case CEE_CONV_U1:
2142                         x86_widen_reg (code, ins->dreg, ins->sreg1, FALSE, FALSE);
2143                         break;
2144                 case CEE_CONV_U2:
2145                         x86_widen_reg (code, ins->dreg, ins->sreg1, FALSE, TRUE);
2146                         break;
2147                 case OP_COMPARE:
2148                         x86_alu_reg_reg (code, X86_CMP, ins->sreg1, ins->sreg2);
2149                         break;
2150                 case OP_COMPARE_IMM:
2151                         x86_alu_reg_imm (code, X86_CMP, ins->sreg1, ins->inst_imm);
2152                         break;
2153                 case OP_X86_COMPARE_MEMBASE_REG:
2154                         x86_alu_membase_reg (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->sreg2);
2155                         break;
2156                 case OP_X86_COMPARE_MEMBASE_IMM:
2157                         x86_alu_membase_imm (code, X86_CMP, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2158                         break;
2159                 case OP_X86_COMPARE_REG_MEMBASE:
2160                         x86_alu_reg_membase (code, X86_CMP, ins->sreg1, ins->sreg2, ins->inst_offset);
2161                         break;
2162                 case OP_X86_TEST_NULL:
2163                         x86_test_reg_reg (code, ins->sreg1, ins->sreg1);
2164                         break;
2165                 case OP_X86_ADD_MEMBASE_IMM:
2166                         x86_alu_membase_imm (code, X86_ADD, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2167                         break;
2168                 case OP_X86_ADD_MEMBASE:
2169                         x86_alu_reg_membase (code, X86_ADD, ins->sreg1, ins->sreg2, ins->inst_offset);
2170                         break;
2171                 case OP_X86_SUB_MEMBASE_IMM:
2172                         x86_alu_membase_imm (code, X86_SUB, ins->inst_basereg, ins->inst_offset, ins->inst_imm);
2173                         break;
2174                 case OP_X86_SUB_MEMBASE:
2175                         x86_alu_reg_membase (code, X86_SUB, ins->sreg1, ins->sreg2, ins->inst_offset);
2176                         break;
2177                 case OP_X86_INC_MEMBASE:
2178                         x86_inc_membase (code, ins->inst_basereg, ins->inst_offset);
2179                         break;
2180                 case OP_X86_INC_REG:
2181                         x86_inc_reg (code, ins->dreg);
2182                         break;
2183                 case OP_X86_DEC_MEMBASE:
2184                         x86_dec_membase (code, ins->inst_basereg, ins->inst_offset);
2185                         break;
2186                 case OP_X86_DEC_REG:
2187                         x86_dec_reg (code, ins->dreg);
2188                         break;
2189                 case OP_X86_MUL_MEMBASE:
2190                         x86_imul_reg_membase (code, ins->sreg1, ins->sreg2, ins->inst_offset);
2191                         break;
2192                 case CEE_BREAK:
2193                         x86_breakpoint (code);
2194                         break;
2195                 case OP_ADDCC:
2196                 case CEE_ADD:
2197                         x86_alu_reg_reg (code, X86_ADD, ins->sreg1, ins->sreg2);
2198                         break;
2199                 case OP_ADC:
2200                         x86_alu_reg_reg (code, X86_ADC, ins->sreg1, ins->sreg2);
2201                         break;
2202                 case OP_ADD_IMM:
2203                         x86_alu_reg_imm (code, X86_ADD, ins->dreg, ins->inst_imm);
2204                         break;
2205                 case OP_ADC_IMM:
2206                         x86_alu_reg_imm (code, X86_ADC, ins->dreg, ins->inst_imm);
2207                         break;
2208                 case OP_SUBCC:
2209                 case CEE_SUB:
2210                         x86_alu_reg_reg (code, X86_SUB, ins->sreg1, ins->sreg2);
2211                         break;
2212                 case OP_SBB:
2213                         x86_alu_reg_reg (code, X86_SBB, ins->sreg1, ins->sreg2);
2214                         break;
2215                 case OP_SUB_IMM:
2216                         x86_alu_reg_imm (code, X86_SUB, ins->dreg, ins->inst_imm);
2217                         break;
2218                 case OP_SBB_IMM:
2219                         x86_alu_reg_imm (code, X86_SBB, ins->dreg, ins->inst_imm);
2220                         break;
2221                 case CEE_AND:
2222                         x86_alu_reg_reg (code, X86_AND, ins->sreg1, ins->sreg2);
2223                         break;
2224                 case OP_AND_IMM:
2225                         x86_alu_reg_imm (code, X86_AND, ins->sreg1, ins->inst_imm);
2226                         break;
2227                 case CEE_DIV:
2228                         x86_cdq (code);
2229                         x86_div_reg (code, ins->sreg2, TRUE);
2230                         break;
2231                 case CEE_DIV_UN:
2232                         x86_alu_reg_reg (code, X86_XOR, X86_EDX, X86_EDX);
2233                         x86_div_reg (code, ins->sreg2, FALSE);
2234                         break;
2235                 case OP_DIV_IMM:
2236                         x86_mov_reg_imm (code, ins->sreg2, ins->inst_imm);
2237                         x86_cdq (code);
2238                         x86_div_reg (code, ins->sreg2, TRUE);
2239                         break;
2240                 case CEE_REM:
2241                         x86_cdq (code);
2242                         x86_div_reg (code, ins->sreg2, TRUE);
2243                         break;
2244                 case CEE_REM_UN:
2245                         x86_alu_reg_reg (code, X86_XOR, X86_EDX, X86_EDX);
2246                         x86_div_reg (code, ins->sreg2, FALSE);
2247                         break;
2248                 case OP_REM_IMM:
2249                         x86_mov_reg_imm (code, ins->sreg2, ins->inst_imm);
2250                         x86_cdq (code);
2251                         x86_div_reg (code, ins->sreg2, TRUE);
2252                         break;
2253                 case CEE_OR:
2254                         x86_alu_reg_reg (code, X86_OR, ins->sreg1, ins->sreg2);
2255                         break;
2256                 case OP_OR_IMM:
2257                         x86_alu_reg_imm (code, X86_OR, ins->sreg1, ins->inst_imm);
2258                         break;
2259                 case CEE_XOR:
2260                         x86_alu_reg_reg (code, X86_XOR, ins->sreg1, ins->sreg2);
2261                         break;
2262                 case OP_XOR_IMM:
2263                         x86_alu_reg_imm (code, X86_XOR, ins->sreg1, ins->inst_imm);
2264                         break;
2265                 case CEE_SHL:
2266                         g_assert (ins->sreg2 == X86_ECX);
2267                         x86_shift_reg (code, X86_SHL, ins->dreg);
2268                         break;
2269                 case CEE_SHR:
2270                         g_assert (ins->sreg2 == X86_ECX);
2271                         x86_shift_reg (code, X86_SAR, ins->dreg);
2272                         break;
2273                 case OP_SHR_IMM:
2274                         x86_shift_reg_imm (code, X86_SAR, ins->dreg, ins->inst_imm);
2275                         break;
2276                 case OP_SHR_UN_IMM:
2277                         x86_shift_reg_imm (code, X86_SHR, ins->dreg, ins->inst_imm);
2278                         break;
2279                 case CEE_SHR_UN:
2280                         g_assert (ins->sreg2 == X86_ECX);
2281                         x86_shift_reg (code, X86_SHR, ins->dreg);
2282                         break;
2283                 case OP_SHL_IMM:
2284                         x86_shift_reg_imm (code, X86_SHL, ins->dreg, ins->inst_imm);
2285                         break;
2286                 case OP_LSHL: {
2287                         guint8 *jump_to_large_shift;
2288                         guint8 *jump_to_end;
2289
2290                         /* handle shifts bellow 32 bits */
2291                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 32);
2292                         jump_to_large_shift = code; x86_branch8 (code, X86_CC_GE, 0, TRUE);
2293
2294                         x86_shld_reg (code, ins->unused, ins->sreg1);
2295                         x86_shift_reg (code, X86_SHL, ins->sreg1);
2296
2297                         jump_to_end = code; x86_jump8 (code, 0);
2298
2299                         x86_patch (jump_to_large_shift, code);
2300
2301                         /* handle shifts over 31 bits */
2302                         x86_mov_reg_reg (code, ins->unused, ins->sreg1, 4);
2303                         x86_clear_reg (code, ins->sreg1);
2304                         x86_alu_reg_imm (code, X86_AND, X86_ECX, 0x1f);
2305                         x86_shift_reg (code, X86_SHL, ins->unused);
2306                         
2307                         x86_patch (jump_to_end, code);
2308                         }
2309                         break;
2310                 case OP_LSHR: {
2311                         guint8 *jump_to_large_shift;
2312                         guint8 *jump_to_end;
2313
2314                         /* handle shifts bellow 32 bits */
2315                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 32);
2316                         jump_to_large_shift = code; x86_branch8 (code, X86_CC_GE, 0, TRUE);
2317
2318                         x86_shrd_reg (code, ins->sreg1, ins->unused);
2319                         x86_shift_reg (code, X86_SAR, ins->unused);
2320
2321                         jump_to_end = code; x86_jump8 (code, 0);
2322
2323                         x86_patch (jump_to_large_shift, code);
2324
2325                         /* handle shifts over 31 bits */
2326                         x86_mov_reg_reg (code, ins->sreg1, ins->unused,  4);
2327                         x86_shift_reg_imm (code, X86_SAR, ins->unused, 0x1f);
2328                         x86_alu_reg_imm (code, X86_AND, X86_ECX, 0x1f);
2329                         x86_shift_reg (code, X86_SAR, ins->sreg1);
2330                         
2331                         x86_patch (jump_to_end, code);
2332                         }
2333                         break;
2334                 case OP_LSHR_UN: {
2335                         guint8 *jump_to_large_shift;
2336                         guint8 *jump_to_end;
2337
2338                         /* handle shifts bellow 32 bits */
2339                         x86_alu_reg_imm (code, X86_CMP, X86_ECX, 32);
2340                         jump_to_large_shift = code; x86_branch8 (code, X86_CC_GE, 0, TRUE);
2341
2342                         x86_shrd_reg (code, ins->sreg1, ins->unused);
2343                         x86_shift_reg (code, X86_SHR, ins->unused);
2344
2345                         jump_to_end = code; x86_jump8 (code, 0);
2346
2347                         x86_patch (jump_to_large_shift, code);
2348
2349                         /* handle shifts over 31 bits */
2350                         x86_mov_reg_reg (code, ins->sreg1, ins->unused, 4);
2351                         x86_clear_reg (code, ins->unused);
2352                         x86_alu_reg_imm (code, X86_AND, X86_ECX, 0x1f);
2353                         x86_shift_reg (code, X86_SHR, ins->sreg1);
2354                         
2355                         x86_patch (jump_to_end, code);
2356                         }
2357                         break;
2358                 case OP_LSHL_IMM:
2359                         if (ins->inst_imm >= 32) {
2360                                 x86_mov_reg_reg (code, ins->unused, ins->sreg1, 4);
2361                                 x86_clear_reg (code, ins->sreg1);
2362                                 x86_shift_reg_imm (code, X86_SHL, ins->unused, ins->inst_imm & 0x1f);
2363                         } else {
2364                                 x86_shld_reg_imm (code, ins->unused, ins->sreg1, ins->inst_imm);
2365                                 x86_shift_reg_imm (code, X86_SHL, ins->sreg1, ins->inst_imm);
2366                         }
2367                         break;
2368                 case OP_LSHR_IMM:
2369                         if (ins->inst_imm >= 32) {
2370                                 x86_mov_reg_reg (code, ins->sreg1, ins->unused,  4);
2371                                 x86_shift_reg_imm (code, X86_SAR, ins->unused, 0x1f);
2372                                 x86_shift_reg_imm (code, X86_SAR, ins->sreg1, ins->inst_imm & 0x1f);
2373                         } else {
2374                                 x86_shrd_reg_imm (code, ins->sreg1, ins->unused, ins->inst_imm);
2375                                 x86_shift_reg_imm (code, X86_SAR, ins->unused, ins->inst_imm);
2376                         }
2377                         break;
2378                 case OP_LSHR_UN_IMM:
2379                         if (ins->inst_imm >= 32) {
2380                                 x86_mov_reg_reg (code, ins->sreg1, ins->unused, 4);
2381                                 x86_clear_reg (code, ins->unused);
2382                                 x86_shift_reg_imm (code, X86_SHR, ins->sreg1, ins->inst_imm & 0x1f);
2383                         } else {
2384                                 x86_shrd_reg_imm (code, ins->sreg1, ins->unused, ins->inst_imm);
2385                                 x86_shift_reg_imm (code, X86_SHR, ins->unused, ins->inst_imm);
2386                         }
2387                         break;
2388                 case CEE_NOT:
2389                         x86_not_reg (code, ins->sreg1);
2390                         break;
2391                 case CEE_NEG:
2392                         x86_neg_reg (code, ins->sreg1);
2393                         break;
2394                 case OP_SEXT_I1:
2395                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, FALSE);
2396                         break;
2397                 case OP_SEXT_I2:
2398                         x86_widen_reg (code, ins->dreg, ins->sreg1, TRUE, TRUE);
2399                         break;
2400                 case CEE_MUL:
2401                         x86_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2402                         break;
2403                 case OP_MUL_IMM:
2404                         x86_imul_reg_reg_imm (code, ins->dreg, ins->sreg1, ins->inst_imm);
2405                         break;
2406                 case CEE_MUL_OVF:
2407                         x86_imul_reg_reg (code, ins->sreg1, ins->sreg2);
2408                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
2409                         break;
2410                 case CEE_MUL_OVF_UN: {
2411                         /* the mul operation and the exception check should most likely be split */
2412                         int non_eax_reg, saved_eax = FALSE, saved_edx = FALSE;
2413                         /*g_assert (ins->sreg2 == X86_EAX);
2414                         g_assert (ins->dreg == X86_EAX);*/
2415                         if (ins->sreg2 == X86_EAX) {
2416                                 non_eax_reg = ins->sreg1;
2417                         } else if (ins->sreg1 == X86_EAX) {
2418                                 non_eax_reg = ins->sreg2;
2419                         } else {
2420                                 /* no need to save since we're going to store to it anyway */
2421                                 if (ins->dreg != X86_EAX) {
2422                                         saved_eax = TRUE;
2423                                         x86_push_reg (code, X86_EAX);
2424                                 }
2425                                 x86_mov_reg_reg (code, X86_EAX, ins->sreg1, 4);
2426                                 non_eax_reg = ins->sreg2;
2427                         }
2428                         if (ins->dreg == X86_EDX) {
2429                                 if (!saved_eax) {
2430                                         saved_eax = TRUE;
2431                                         x86_push_reg (code, X86_EAX);
2432                                 }
2433                         } else if (ins->dreg != X86_EAX) {
2434                                 saved_edx = TRUE;
2435                                 x86_push_reg (code, X86_EDX);
2436                         }
2437                         x86_mul_reg (code, non_eax_reg, FALSE);
2438                         /* save before the check since pop and mov don't change the flags */
2439                         if (ins->dreg != X86_EAX)
2440                                 x86_mov_reg_reg (code, ins->dreg, X86_EAX, 4);
2441                         if (saved_edx)
2442                                 x86_pop_reg (code, X86_EDX);
2443                         if (saved_eax)
2444                                 x86_pop_reg (code, X86_EAX);
2445                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_O, FALSE, "OverflowException");
2446                         break;
2447                 }
2448                 case OP_ICONST:
2449                         x86_mov_reg_imm (code, ins->dreg, ins->inst_c0);
2450                         break;
2451                 case OP_AOTCONST:
2452                         mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0);
2453                         x86_mov_reg_imm (code, ins->dreg, 0);
2454                         break;
2455                 case CEE_CONV_I4:
2456                 case OP_MOVE:
2457                         x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4);
2458                         break;
2459                 case CEE_CONV_U4:
2460                         g_assert_not_reached ();
2461                 case CEE_JMP: {
2462                         /*
2463                          * Note: this 'frame destruction' logic is useful for tail calls, too.
2464                          * Keep in sync with the code in emit_epilog.
2465                          */
2466                         int pos = 0;
2467
2468                         /* FIXME: no tracing support... */
2469                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
2470                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
2471                         /* reset offset to make max_len work */
2472                         offset = code - cfg->native_code;
2473
2474                         g_assert (!cfg->method->save_lmf);
2475
2476                         if (cfg->used_int_regs & (1 << X86_EBX))
2477                                 pos -= 4;
2478                         if (cfg->used_int_regs & (1 << X86_EDI))
2479                                 pos -= 4;
2480                         if (cfg->used_int_regs & (1 << X86_ESI))
2481                                 pos -= 4;
2482                         if (pos)
2483                                 x86_lea_membase (code, X86_ESP, X86_EBP, pos);
2484         
2485                         if (cfg->used_int_regs & (1 << X86_ESI))
2486                                 x86_pop_reg (code, X86_ESI);
2487                         if (cfg->used_int_regs & (1 << X86_EDI))
2488                                 x86_pop_reg (code, X86_EDI);
2489                         if (cfg->used_int_regs & (1 << X86_EBX))
2490                                 x86_pop_reg (code, X86_EBX);
2491         
2492                         /* restore ESP/EBP */
2493                         x86_leave (code);
2494                         offset = code - cfg->native_code;
2495                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0);
2496                         x86_jump32 (code, 0);
2497                         break;
2498                 }
2499                 case OP_CHECK_THIS:
2500                         /* ensure ins->sreg1 is not NULL */
2501                         x86_alu_membase_imm (code, X86_CMP, ins->sreg1, 0, 0);
2502                         break;
2503                 case OP_ARGLIST: {
2504                         int hreg = ins->sreg1 == X86_EAX? X86_ECX: X86_EAX;
2505                         x86_push_reg (code, hreg);
2506                         x86_lea_membase (code, hreg, X86_EBP, cfg->sig_cookie);
2507                         x86_mov_membase_reg (code, ins->sreg1, 0, hreg, 4);
2508                         x86_pop_reg (code, hreg);
2509                         break;
2510                 }
2511                 case OP_FCALL:
2512                 case OP_LCALL:
2513                 case OP_VCALL:
2514                 case OP_VOIDCALL:
2515                 case CEE_CALL:
2516                         call = (MonoCallInst*)ins;
2517                         if (ins->flags & MONO_INST_HAS_METHOD)
2518                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD, call->method);
2519                         else {
2520                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_ABS, call->fptr);
2521                         }
2522                         x86_call_code (code, 0);
2523                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
2524                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, call->stack_usage);
2525                         break;
2526                 case OP_FCALL_REG:
2527                 case OP_LCALL_REG:
2528                 case OP_VCALL_REG:
2529                 case OP_VOIDCALL_REG:
2530                 case OP_CALL_REG:
2531                         call = (MonoCallInst*)ins;
2532                         x86_call_reg (code, ins->sreg1);
2533                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
2534                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, call->stack_usage);
2535                         break;
2536                 case OP_FCALL_MEMBASE:
2537                 case OP_LCALL_MEMBASE:
2538                 case OP_VCALL_MEMBASE:
2539                 case OP_VOIDCALL_MEMBASE:
2540                 case OP_CALL_MEMBASE:
2541                         call = (MonoCallInst*)ins;
2542                         x86_call_membase (code, ins->sreg1, ins->inst_offset);
2543                         if (call->stack_usage && !CALLCONV_IS_STDCALL (call->signature->call_convention))
2544                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, call->stack_usage);
2545                         break;
2546                 case OP_OUTARG:
2547                 case OP_X86_PUSH:
2548                         x86_push_reg (code, ins->sreg1);
2549                         break;
2550                 case OP_X86_PUSH_IMM:
2551                         x86_push_imm (code, ins->inst_imm);
2552                         break;
2553                 case OP_X86_PUSH_MEMBASE:
2554                         x86_push_membase (code, ins->inst_basereg, ins->inst_offset);
2555                         break;
2556                 case OP_X86_PUSH_OBJ: 
2557                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, ins->inst_imm);
2558                         x86_push_reg (code, X86_EDI);
2559                         x86_push_reg (code, X86_ESI);
2560                         x86_push_reg (code, X86_ECX);
2561                         if (ins->inst_offset)
2562                                 x86_lea_membase (code, X86_ESI, ins->inst_basereg, ins->inst_offset);
2563                         else
2564                                 x86_mov_reg_reg (code, X86_ESI, ins->inst_basereg, 4);
2565                         x86_lea_membase (code, X86_EDI, X86_ESP, 12);
2566                         x86_mov_reg_imm (code, X86_ECX, (ins->inst_imm >> 2));
2567                         x86_cld (code);
2568                         x86_prefix (code, X86_REP_PREFIX);
2569                         x86_movsd (code);
2570                         x86_pop_reg (code, X86_ECX);
2571                         x86_pop_reg (code, X86_ESI);
2572                         x86_pop_reg (code, X86_EDI);
2573                         break;
2574                 case OP_X86_LEA:
2575                         x86_lea_memindex (code, ins->dreg, ins->sreg1, ins->inst_imm, ins->sreg2, ins->unused);
2576                         break;
2577                 case OP_X86_LEA_MEMBASE:
2578                         x86_lea_membase (code, ins->dreg, ins->sreg1, ins->inst_imm);
2579                         break;
2580                 case OP_X86_XCHG:
2581                         x86_xchg_reg_reg (code, ins->sreg1, ins->sreg2, 4);
2582                         break;
2583                 case OP_LOCALLOC:
2584                         /* keep alignment */
2585                         x86_alu_reg_imm (code, X86_ADD, ins->sreg1, MONO_ARCH_FRAME_ALIGNMENT - 1);
2586                         x86_alu_reg_imm (code, X86_AND, ins->sreg1, ~(MONO_ARCH_FRAME_ALIGNMENT - 1));
2587                         code = mono_emit_stack_alloc (code, ins);
2588                         x86_mov_reg_reg (code, ins->dreg, X86_ESP, 4);
2589                         break;
2590                 case CEE_RET:
2591                         x86_ret (code);
2592                         break;
2593                 case CEE_THROW: {
2594                         x86_push_reg (code, ins->sreg1);
2595                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, 
2596                                              (gpointer)"mono_arch_throw_exception");
2597                         x86_call_code (code, 0);
2598                         break;
2599                 }
2600                 case OP_CALL_HANDLER: 
2601                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
2602                         x86_call_imm (code, 0);
2603                         break;
2604                 case OP_LABEL:
2605                         ins->inst_c0 = code - cfg->native_code;
2606                         break;
2607                 case CEE_BR:
2608                         //g_print ("target: %p, next: %p, curr: %p, last: %p\n", ins->inst_target_bb, bb->next_bb, ins, bb->last_ins);
2609                         //if ((ins->inst_target_bb == bb->next_bb) && ins == bb->last_ins)
2610                         //break;
2611                         if (ins->flags & MONO_INST_BRLABEL) {
2612                                 if (ins->inst_i0->inst_c0) {
2613                                         x86_jump_code (code, cfg->native_code + ins->inst_i0->inst_c0);
2614                                 } else {
2615                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_LABEL, ins->inst_i0);
2616                                         x86_jump32 (code, 0);
2617                                 }
2618                         } else {
2619                                 if (ins->inst_target_bb->native_offset) {
2620                                         x86_jump_code (code, cfg->native_code + ins->inst_target_bb->native_offset); 
2621                                 } else {
2622                                         mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb);
2623                                         if ((cfg->opt & MONO_OPT_BRANCH) &&
2624                                             x86_is_imm8 (ins->inst_target_bb->max_offset - cpos))
2625                                                 x86_jump8 (code, 0);
2626                                         else 
2627                                                 x86_jump32 (code, 0);
2628                                 } 
2629                         }
2630                         break;
2631                 case OP_BR_REG:
2632                         x86_jump_reg (code, ins->sreg1);
2633                         break;
2634                 case OP_CEQ:
2635                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
2636                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2637                         break;
2638                 case OP_CLT:
2639                         x86_set_reg (code, X86_CC_LT, ins->dreg, TRUE);
2640                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2641                         break;
2642                 case OP_CLT_UN:
2643                         x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
2644                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2645                         break;
2646                 case OP_CGT:
2647                         x86_set_reg (code, X86_CC_GT, ins->dreg, TRUE);
2648                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2649                         break;
2650                 case OP_CGT_UN:
2651                         x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
2652                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2653                         break;
2654                 case OP_COND_EXC_EQ:
2655                 case OP_COND_EXC_NE_UN:
2656                 case OP_COND_EXC_LT:
2657                 case OP_COND_EXC_LT_UN:
2658                 case OP_COND_EXC_GT:
2659                 case OP_COND_EXC_GT_UN:
2660                 case OP_COND_EXC_GE:
2661                 case OP_COND_EXC_GE_UN:
2662                 case OP_COND_EXC_LE:
2663                 case OP_COND_EXC_LE_UN:
2664                 case OP_COND_EXC_OV:
2665                 case OP_COND_EXC_NO:
2666                 case OP_COND_EXC_C:
2667                 case OP_COND_EXC_NC:
2668                         EMIT_COND_SYSTEM_EXCEPTION (branch_cc_table [ins->opcode - OP_COND_EXC_EQ], 
2669                                                     (ins->opcode < OP_COND_EXC_NE_UN), ins->inst_p1);
2670                         break;
2671                 case CEE_BEQ:
2672                 case CEE_BNE_UN:
2673                 case CEE_BLT:
2674                 case CEE_BLT_UN:
2675                 case CEE_BGT:
2676                 case CEE_BGT_UN:
2677                 case CEE_BGE:
2678                 case CEE_BGE_UN:
2679                 case CEE_BLE:
2680                 case CEE_BLE_UN:
2681                         EMIT_COND_BRANCH (ins, branch_cc_table [ins->opcode - CEE_BEQ], (ins->opcode < CEE_BNE_UN));
2682                         break;
2683
2684                 /* floating point opcodes */
2685                 case OP_R8CONST: {
2686                         double d = *(double *)ins->inst_p0;
2687
2688                         if ((d == 0.0) && (mono_signbit (d) == 0)) {
2689                                 x86_fldz (code);
2690                         } else if (d == 1.0) {
2691                                 x86_fld1 (code);
2692                         } else {
2693                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R8, ins->inst_p0);
2694                                 x86_fld (code, NULL, TRUE);
2695                         }
2696                         break;
2697                 }
2698                 case OP_R4CONST: {
2699                         float f = *(float *)ins->inst_p0;
2700
2701                         if ((f == 0.0) && (mono_signbit (f) == 0)) {
2702                                 x86_fldz (code);
2703                         } else if (f == 1.0) {
2704                                 x86_fld1 (code);
2705                         } else {
2706                                 mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_R4, ins->inst_p0);
2707                                 x86_fld (code, NULL, FALSE);
2708                         }
2709                         break;
2710                 }
2711                 case OP_STORER8_MEMBASE_REG:
2712                         x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, TRUE, TRUE);
2713                         break;
2714                 case OP_LOADR8_SPILL_MEMBASE:
2715                         x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
2716                         x86_fxch (code, 1);
2717                         break;
2718                 case OP_LOADR8_MEMBASE:
2719                         x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
2720                         break;
2721                 case OP_STORER4_MEMBASE_REG:
2722                         x86_fst_membase (code, ins->inst_destbasereg, ins->inst_offset, FALSE, TRUE);
2723                         break;
2724                 case OP_LOADR4_MEMBASE:
2725                         x86_fld_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
2726                         break;
2727                 case CEE_CONV_R4: /* FIXME: change precision */
2728                 case CEE_CONV_R8:
2729                         x86_push_reg (code, ins->sreg1);
2730                         x86_fild_membase (code, X86_ESP, 0, FALSE);
2731                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
2732                         break;
2733                 case OP_X86_FP_LOAD_I8:
2734                         x86_fild_membase (code, ins->inst_basereg, ins->inst_offset, TRUE);
2735                         break;
2736                 case OP_X86_FP_LOAD_I4:
2737                         x86_fild_membase (code, ins->inst_basereg, ins->inst_offset, FALSE);
2738                         break;
2739                 case OP_FCONV_TO_I1:
2740                         code = emit_float_to_int (cfg, code, ins->dreg, 1, TRUE);
2741                         break;
2742                 case OP_FCONV_TO_U1:
2743                         code = emit_float_to_int (cfg, code, ins->dreg, 1, FALSE);
2744                         break;
2745                 case OP_FCONV_TO_I2:
2746                         code = emit_float_to_int (cfg, code, ins->dreg, 2, TRUE);
2747                         break;
2748                 case OP_FCONV_TO_U2:
2749                         code = emit_float_to_int (cfg, code, ins->dreg, 2, FALSE);
2750                         break;
2751                 case OP_FCONV_TO_I4:
2752                 case OP_FCONV_TO_I:
2753                         code = emit_float_to_int (cfg, code, ins->dreg, 4, TRUE);
2754                         break;
2755                 case OP_FCONV_TO_I8:
2756                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 4);
2757                         x86_fnstcw_membase(code, X86_ESP, 0);
2758                         x86_mov_reg_membase (code, ins->dreg, X86_ESP, 0, 2);
2759                         x86_alu_reg_imm (code, X86_OR, ins->dreg, 0xc00);
2760                         x86_mov_membase_reg (code, X86_ESP, 2, ins->dreg, 2);
2761                         x86_fldcw_membase (code, X86_ESP, 2);
2762                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 8);
2763                         x86_fist_pop_membase (code, X86_ESP, 0, TRUE);
2764                         x86_pop_reg (code, ins->dreg);
2765                         x86_pop_reg (code, ins->unused);
2766                         x86_fldcw_membase (code, X86_ESP, 0);
2767                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
2768                         break;
2769                 case OP_LCONV_TO_R_UN: { 
2770                         static guint8 mn[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x40 };
2771                         guint8 *br;
2772
2773                         /* load 64bit integer to FP stack */
2774                         x86_push_imm (code, 0);
2775                         x86_push_reg (code, ins->sreg2);
2776                         x86_push_reg (code, ins->sreg1);
2777                         x86_fild_membase (code, X86_ESP, 0, TRUE);
2778                         /* store as 80bit FP value */
2779                         x86_fst80_membase (code, X86_ESP, 0);
2780                         
2781                         /* test if lreg is negative */
2782                         x86_test_reg_reg (code, ins->sreg2, ins->sreg2);
2783                         br = code; x86_branch8 (code, X86_CC_GEZ, 0, TRUE);
2784         
2785                         /* add correction constant mn */
2786                         x86_fld80_mem (code, mn);
2787                         x86_fld80_membase (code, X86_ESP, 0);
2788                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
2789                         x86_fst80_membase (code, X86_ESP, 0);
2790
2791                         x86_patch (br, code);
2792
2793                         x86_fld80_membase (code, X86_ESP, 0);
2794                         x86_alu_reg_imm (code, X86_ADD, X86_ESP, 12);
2795
2796                         break;
2797                 }
2798                 case OP_LCONV_TO_OVF_I: {
2799                         guint8 *br [3], *label [1];
2800
2801                         /* 
2802                          * Valid ints: 0xffffffff:8000000 to 00000000:0x7f000000
2803                          */
2804                         x86_test_reg_reg (code, ins->sreg1, ins->sreg1);
2805
2806                         /* If the low word top bit is set, see if we are negative */
2807                         br [0] = code; x86_branch8 (code, X86_CC_LT, 0, TRUE);
2808                         /* We are not negative (no top bit set, check for our top word to be zero */
2809                         x86_test_reg_reg (code, ins->sreg2, ins->sreg2);
2810                         br [1] = code; x86_branch8 (code, X86_CC_EQ, 0, TRUE);
2811                         label [0] = code;
2812
2813                         /* throw exception */
2814                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC, "OverflowException");
2815                         x86_jump32 (code, 0);
2816         
2817                         x86_patch (br [0], code);
2818                         /* our top bit is set, check that top word is 0xfffffff */
2819                         x86_alu_reg_imm (code, X86_CMP, ins->sreg2, 0xffffffff);
2820                 
2821                         x86_patch (br [1], code);
2822                         /* nope, emit exception */
2823                         br [2] = code; x86_branch8 (code, X86_CC_NE, 0, TRUE);
2824                         x86_patch (br [2], label [0]);
2825
2826                         if (ins->dreg != ins->sreg1)
2827                                 x86_mov_reg_reg (code, ins->dreg, ins->sreg1, 4);
2828                         break;
2829                 }
2830                 case OP_FADD:
2831                         x86_fp_op_reg (code, X86_FADD, 1, TRUE);
2832                         break;
2833                 case OP_FSUB:
2834                         x86_fp_op_reg (code, X86_FSUB, 1, TRUE);
2835                         break;          
2836                 case OP_FMUL:
2837                         x86_fp_op_reg (code, X86_FMUL, 1, TRUE);
2838                         break;          
2839                 case OP_FDIV:
2840                         x86_fp_op_reg (code, X86_FDIV, 1, TRUE);
2841                         break;          
2842                 case OP_FNEG:
2843                         x86_fchs (code);
2844                         break;          
2845                 case OP_SIN:
2846                         x86_fsin (code);
2847                         break;          
2848                 case OP_COS:
2849                         x86_fcos (code);
2850                         break;          
2851                 case OP_ABS:
2852                         x86_fabs (code);
2853                         break;          
2854                 case OP_TAN: {
2855                         /* 
2856                          * it really doesn't make sense to inline all this code,
2857                          * it's here just to show that things may not be as simple 
2858                          * as they appear.
2859                          */
2860                         guchar *check_pos, *end_tan, *pop_jump;
2861                         x86_push_reg (code, X86_EAX);
2862                         x86_fptan (code);
2863                         x86_fnstsw (code);
2864                         x86_test_reg_imm (code, X86_EAX, X86_FP_C2);
2865                         check_pos = code;
2866                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
2867                         x86_fstp (code, 0); /* pop the 1.0 */
2868                         end_tan = code;
2869                         x86_jump8 (code, 0);
2870                         x86_fldpi (code);
2871                         x86_fp_op (code, X86_FADD, 0);
2872                         x86_fxch (code, 1);
2873                         x86_fprem1 (code);
2874                         x86_fstsw (code);
2875                         x86_test_reg_imm (code, X86_EAX, X86_FP_C2);
2876                         pop_jump = code;
2877                         x86_branch8 (code, X86_CC_NE, 0, FALSE);
2878                         x86_fstp (code, 1);
2879                         x86_fptan (code);
2880                         x86_patch (pop_jump, code);
2881                         x86_fstp (code, 0); /* pop the 1.0 */
2882                         x86_patch (check_pos, code);
2883                         x86_patch (end_tan, code);
2884                         x86_pop_reg (code, X86_EAX);
2885                         break;
2886                 }
2887                 case OP_ATAN:
2888                         x86_fld1 (code);
2889                         x86_fpatan (code);
2890                         break;          
2891                 case OP_SQRT:
2892                         x86_fsqrt (code);
2893                         break;          
2894                 case OP_X86_FPOP:
2895                         x86_fstp (code, 0);
2896                         break;          
2897                 case OP_FREM: {
2898                         guint8 *l1, *l2;
2899
2900                         x86_push_reg (code, X86_EAX);
2901                         /* we need to exchange ST(0) with ST(1) */
2902                         x86_fxch (code, 1);
2903
2904                         /* this requires a loop, because fprem somtimes 
2905                          * returns a partial remainder */
2906                         l1 = code;
2907                         /* looks like MS is using fprem instead of the IEEE compatible fprem1 */
2908                         /* x86_fprem1 (code); */
2909                         x86_fprem (code);
2910                         x86_fnstsw (code);
2911                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_C2);
2912                         l2 = code + 2;
2913                         x86_branch8 (code, X86_CC_NE, l1 - l2, FALSE);
2914
2915                         /* pop result */
2916                         x86_fstp (code, 1);
2917
2918                         x86_pop_reg (code, X86_EAX);
2919                         break;
2920                 }
2921                 case OP_FCOMPARE:
2922                         if (cfg->opt & MONO_OPT_FCMOV) {
2923                                 x86_fcomip (code, 1);
2924                                 x86_fstp (code, 0);
2925                                 break;
2926                         }
2927                         /* this overwrites EAX */
2928                         EMIT_FPCOMPARE(code);
2929                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
2930                         break;
2931                 case OP_FCEQ:
2932                         if (cfg->opt & MONO_OPT_FCMOV) {
2933                                 /* zeroing the register at the start results in 
2934                                  * shorter and faster code (we can also remove the widening op)
2935                                  */
2936                                 guchar *unordered_check;
2937                                 x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
2938                                 x86_fcomip (code, 1);
2939                                 x86_fstp (code, 0);
2940                                 unordered_check = code;
2941                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
2942                                 x86_set_reg (code, X86_CC_EQ, ins->dreg, FALSE);
2943                                 x86_patch (unordered_check, code);
2944                                 break;
2945                         }
2946                         if (ins->dreg != X86_EAX) 
2947                                 x86_push_reg (code, X86_EAX);
2948
2949                         EMIT_FPCOMPARE(code);
2950                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
2951                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4000);
2952                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
2953                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
2954
2955                         if (ins->dreg != X86_EAX) 
2956                                 x86_pop_reg (code, X86_EAX);
2957                         break;
2958                 case OP_FCLT:
2959                 case OP_FCLT_UN:
2960                         if (cfg->opt & MONO_OPT_FCMOV) {
2961                                 /* zeroing the register at the start results in 
2962                                  * shorter and faster code (we can also remove the widening op)
2963                                  */
2964                                 x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
2965                                 x86_fcomip (code, 1);
2966                                 x86_fstp (code, 0);
2967                                 if (ins->opcode == OP_FCLT_UN) {
2968                                         guchar *unordered_check = code;
2969                                         guchar *jump_to_end;
2970                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
2971                                         x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
2972                                         jump_to_end = code;
2973                                         x86_jump8 (code, 0);
2974                                         x86_patch (unordered_check, code);
2975                                         x86_inc_reg (code, ins->dreg);
2976                                         x86_patch (jump_to_end, code);
2977                                 } else {
2978                                         x86_set_reg (code, X86_CC_GT, ins->dreg, FALSE);
2979                                 }
2980                                 break;
2981                         }
2982                         if (ins->dreg != X86_EAX) 
2983                                 x86_push_reg (code, X86_EAX);
2984
2985                         EMIT_FPCOMPARE(code);
2986                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
2987                         if (ins->opcode == OP_FCLT_UN) {
2988                                 guchar *is_not_zero_check, *end_jump;
2989                                 is_not_zero_check = code;
2990                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
2991                                 end_jump = code;
2992                                 x86_jump8 (code, 0);
2993                                 x86_patch (is_not_zero_check, code);
2994                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
2995
2996                                 x86_patch (end_jump, code);
2997                         }
2998                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
2999                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3000
3001                         if (ins->dreg != X86_EAX) 
3002                                 x86_pop_reg (code, X86_EAX);
3003                         break;
3004                 case OP_FCGT:
3005                 case OP_FCGT_UN:
3006                         if (cfg->opt & MONO_OPT_FCMOV) {
3007                                 /* zeroing the register at the start results in 
3008                                  * shorter and faster code (we can also remove the widening op)
3009                                  */
3010                                 guchar *unordered_check;
3011                                 x86_alu_reg_reg (code, X86_XOR, ins->dreg, ins->dreg);
3012                                 x86_fcomip (code, 1);
3013                                 x86_fstp (code, 0);
3014                                 if (ins->opcode == OP_FCGT) {
3015                                         unordered_check = code;
3016                                         x86_branch8 (code, X86_CC_P, 0, FALSE);
3017                                         x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
3018                                         x86_patch (unordered_check, code);
3019                                 } else {
3020                                         x86_set_reg (code, X86_CC_LT, ins->dreg, FALSE);
3021                                 }
3022                                 break;
3023                         }
3024                         if (ins->dreg != X86_EAX) 
3025                                 x86_push_reg (code, X86_EAX);
3026
3027                         EMIT_FPCOMPARE(code);
3028                         x86_alu_reg_imm (code, X86_AND, X86_EAX, X86_FP_CC_MASK);
3029                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3030                         if (ins->opcode == OP_FCGT_UN) {
3031                                 guchar *is_not_zero_check, *end_jump;
3032                                 is_not_zero_check = code;
3033                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3034                                 end_jump = code;
3035                                 x86_jump8 (code, 0);
3036                                 x86_patch (is_not_zero_check, code);
3037                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3038
3039                                 x86_patch (end_jump, code);
3040                         }
3041                         x86_set_reg (code, X86_CC_EQ, ins->dreg, TRUE);
3042                         x86_widen_reg (code, ins->dreg, ins->dreg, FALSE, FALSE);
3043
3044                         if (ins->dreg != X86_EAX) 
3045                                 x86_pop_reg (code, X86_EAX);
3046                         break;
3047                 case OP_FBEQ:
3048                         if (cfg->opt & MONO_OPT_FCMOV) {
3049                                 guchar *jump = code;
3050                                 x86_branch8 (code, X86_CC_P, 0, TRUE);
3051                                 EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3052                                 x86_patch (jump, code);
3053                                 break;
3054                         }
3055                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0x4000);
3056                         EMIT_COND_BRANCH (ins, X86_CC_EQ, TRUE);
3057                         break;
3058                 case OP_FBNE_UN:
3059                         /* Branch if C013 != 100 */
3060                         if (cfg->opt & MONO_OPT_FCMOV) {
3061                                 /* branch if !ZF or (PF|CF) */
3062                                 EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3063                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
3064                                 EMIT_COND_BRANCH (ins, X86_CC_B, FALSE);
3065                                 break;
3066                         }
3067                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C3);
3068                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3069                         break;
3070                 case OP_FBLT:
3071                         if (cfg->opt & MONO_OPT_FCMOV) {
3072                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
3073                                 break;
3074                         }
3075                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3076                         break;
3077                 case OP_FBLT_UN:
3078                         if (cfg->opt & MONO_OPT_FCMOV) {
3079                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
3080                                 EMIT_COND_BRANCH (ins, X86_CC_GT, FALSE);
3081                                 break;
3082                         }
3083                         if (ins->opcode == OP_FBLT_UN) {
3084                                 guchar *is_not_zero_check, *end_jump;
3085                                 is_not_zero_check = code;
3086                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3087                                 end_jump = code;
3088                                 x86_jump8 (code, 0);
3089                                 x86_patch (is_not_zero_check, code);
3090                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3091
3092                                 x86_patch (end_jump, code);
3093                         }
3094                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3095                         break;
3096                 case OP_FBGT:
3097                 case OP_FBGT_UN:
3098                         if (cfg->opt & MONO_OPT_FCMOV) {
3099                                 EMIT_COND_BRANCH (ins, X86_CC_LT, FALSE);
3100                                 break;
3101                         }
3102                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3103                         if (ins->opcode == OP_FBGT_UN) {
3104                                 guchar *is_not_zero_check, *end_jump;
3105                                 is_not_zero_check = code;
3106                                 x86_branch8 (code, X86_CC_NZ, 0, TRUE);
3107                                 end_jump = code;
3108                                 x86_jump8 (code, 0);
3109                                 x86_patch (is_not_zero_check, code);
3110                                 x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_CC_MASK);
3111
3112                                 x86_patch (end_jump, code);
3113                         }
3114                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3115                         break;
3116                 case OP_FBGE:
3117                         /* Branch if C013 == 100 or 001 */
3118                         if (cfg->opt & MONO_OPT_FCMOV) {
3119                                 guchar *br1;
3120
3121                                 /* skip branch if C1=1 */
3122                                 br1 = code;
3123                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3124                                 /* branch if (C0 | C3) = 1 */
3125                                 EMIT_COND_BRANCH (ins, X86_CC_BE, FALSE);
3126                                 x86_patch (br1, code);
3127                                 break;
3128                         }
3129                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3130                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3131                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C3);
3132                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3133                         break;
3134                 case OP_FBGE_UN:
3135                         /* Branch if C013 == 000 */
3136                         if (cfg->opt & MONO_OPT_FCMOV) {
3137                                 EMIT_COND_BRANCH (ins, X86_CC_LE, FALSE);
3138                                 break;
3139                         }
3140                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3141                         break;
3142                 case OP_FBLE:
3143                         /* Branch if C013=000 or 100 */
3144                         if (cfg->opt & MONO_OPT_FCMOV) {
3145                                 guchar *br1;
3146
3147                                 /* skip branch if C1=1 */
3148                                 br1 = code;
3149                                 x86_branch8 (code, X86_CC_P, 0, FALSE);
3150                                 /* branch if C0=0 */
3151                                 EMIT_COND_BRANCH (ins, X86_CC_NB, FALSE);
3152                                 x86_patch (br1, code);
3153                                 break;
3154                         }
3155                         x86_alu_reg_imm (code, X86_AND, X86_EAX, (X86_FP_C0|X86_FP_C1));
3156                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, 0);
3157                         EMIT_COND_BRANCH (ins, X86_CC_EQ, FALSE);
3158                         break;
3159                 case OP_FBLE_UN:
3160                         /* Branch if C013 != 001 */
3161                         if (cfg->opt & MONO_OPT_FCMOV) {
3162                                 EMIT_COND_BRANCH (ins, X86_CC_P, FALSE);
3163                                 EMIT_COND_BRANCH (ins, X86_CC_GE, FALSE);
3164                                 break;
3165                         }
3166                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3167                         EMIT_COND_BRANCH (ins, X86_CC_NE, FALSE);
3168                         break;
3169                 case CEE_CKFINITE: {
3170                         x86_push_reg (code, X86_EAX);
3171                         x86_fxam (code);
3172                         x86_fnstsw (code);
3173                         x86_alu_reg_imm (code, X86_AND, X86_EAX, 0x4100);
3174                         x86_alu_reg_imm (code, X86_CMP, X86_EAX, X86_FP_C0);
3175                         x86_pop_reg (code, X86_EAX);
3176                         EMIT_COND_SYSTEM_EXCEPTION (X86_CC_EQ, FALSE, "ArithmeticException");
3177                         break;
3178                 }
3179                 default:
3180                         g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__);
3181                         g_assert_not_reached ();
3182                 }
3183
3184                 if ((code - cfg->native_code - offset) > max_len) {
3185                         g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %d)",
3186                                    mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset);
3187                         g_assert_not_reached ();
3188                 }
3189                
3190                 cpos += max_len;
3191
3192                 last_ins = ins;
3193                 last_offset = offset;
3194                 
3195                 ins = ins->next;
3196         }
3197
3198         cfg->code_len = code - cfg->native_code;
3199 }
3200
3201 void
3202 mono_arch_register_lowlevel_calls (void)
3203 {
3204         mono_register_jit_icall (mono_arch_get_lmf_addr, "mono_arch_get_lmf_addr", NULL, TRUE);
3205 }
3206
3207 void
3208 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gboolean run_cctors)
3209 {
3210         MonoJumpInfo *patch_info;
3211
3212         for (patch_info = ji; patch_info; patch_info = patch_info->next) {
3213                 unsigned char *ip = patch_info->ip.i + code;
3214                 const unsigned char *target;
3215
3216                 target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors);
3217
3218                 switch (patch_info->type) {
3219                 case MONO_PATCH_INFO_IP:
3220                         *((gconstpointer *)(ip)) = target;
3221                         continue;
3222                 case MONO_PATCH_INFO_METHOD_REL:
3223                         *((gconstpointer *)(ip)) = target;
3224                         continue;
3225                 case MONO_PATCH_INFO_SWITCH: {
3226                         *((gconstpointer *)(ip + 2)) = target;
3227                         /* we put into the table the absolute address, no need for x86_patch in this case */
3228                         continue;
3229                 }
3230                 case MONO_PATCH_INFO_IID:
3231                         *((guint32 *)(ip + 1)) = (guint32)target;
3232                         continue;                       
3233                 case MONO_PATCH_INFO_CLASS_INIT: {
3234                         guint8 *code = ip;
3235                         /* Might already been changed to a nop */
3236                         x86_call_imm (code, 0);
3237                         break;
3238                 }
3239                 case MONO_PATCH_INFO_R4:
3240                 case MONO_PATCH_INFO_R8:
3241                         *((gconstpointer *)(ip + 2)) = target;
3242                         continue;
3243                 case MONO_PATCH_INFO_METHODCONST:
3244                 case MONO_PATCH_INFO_CLASS:
3245                 case MONO_PATCH_INFO_IMAGE:
3246                 case MONO_PATCH_INFO_FIELD:
3247                 case MONO_PATCH_INFO_VTABLE:
3248                 case MONO_PATCH_INFO_SFLDA:
3249                 case MONO_PATCH_INFO_EXC_NAME:
3250                 case MONO_PATCH_INFO_LDSTR:
3251                 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3252                 case MONO_PATCH_INFO_LDTOKEN:
3253                         *((gconstpointer *)(ip + 1)) = target;
3254                         continue;
3255                 default:
3256                         break;
3257                 }
3258                 x86_patch (ip, target);
3259         }
3260 }
3261
3262 int
3263 mono_arch_max_epilog_size (MonoCompile *cfg)
3264 {
3265         int exc_count = 0, max_epilog_size = 16;
3266         MonoJumpInfo *patch_info;
3267         
3268         if (cfg->method->save_lmf)
3269                 max_epilog_size += 128;
3270         
3271         if (mono_jit_trace_calls != NULL)
3272                 max_epilog_size += 50;
3273
3274         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3275                 max_epilog_size += 50;
3276
3277         /* count the number of exception infos */
3278      
3279         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3280                 if (patch_info->type == MONO_PATCH_INFO_EXC)
3281                         exc_count++;
3282         }
3283
3284         /* 
3285          * make sure we have enough space for exceptions
3286          * 16 is the size of two push_imm instructions and a call
3287          */
3288         max_epilog_size += exc_count*16;
3289
3290         return max_epilog_size;
3291 }
3292
3293 guint8 *
3294 mono_arch_emit_prolog (MonoCompile *cfg)
3295 {
3296         MonoMethod *method = cfg->method;
3297         MonoBasicBlock *bb;
3298         MonoMethodSignature *sig;
3299         MonoInst *inst;
3300         int alloc_size, pos, max_offset, i;
3301         guint8 *code;
3302
3303         cfg->code_size =  MAX (((MonoMethodNormal *)method)->header->code_size * 4, 256);
3304         code = cfg->native_code = g_malloc (cfg->code_size);
3305
3306         x86_push_reg (code, X86_EBP);
3307         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
3308
3309         alloc_size = - cfg->stack_offset;
3310         pos = 0;
3311
3312         if (method->save_lmf) {
3313                 pos += sizeof (MonoLMF);
3314
3315                 /* save the current IP */
3316                 mono_add_patch_info (cfg, code + 1 - cfg->native_code, MONO_PATCH_INFO_IP, NULL);
3317                 x86_push_imm (code, 0);
3318
3319                 /* save all caller saved regs */
3320                 x86_push_reg (code, X86_EBX);
3321                 x86_push_reg (code, X86_EDI);
3322                 x86_push_reg (code, X86_ESI);
3323                 x86_push_reg (code, X86_EBP);
3324
3325                 /* save method info */
3326                 x86_push_imm (code, method);
3327
3328                 /* get the address of lmf for the current thread */
3329                 /* 
3330                  * This is performance critical so we try to use some tricks to make
3331                  * it fast.
3332                  */
3333                 if (lmf_tls_offset != -1) {
3334                         /* Load lmf quicky using the GS register */
3335                         x86_prefix (code, X86_GS_PREFIX);
3336                         x86_mov_reg_mem (code, X86_EAX, 0, 4);
3337                         x86_mov_reg_membase (code, X86_EAX, X86_EAX, lmf_tls_offset, 4);
3338                 }
3339                 else {
3340 #ifdef HAVE_KW_THREAD
3341                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3342                                                                  (gpointer)"mono_arch_get_lmf_addr");
3343 #else
3344                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, 
3345                                                                  (gpointer)"mono_get_lmf_addr");
3346 #endif
3347                         x86_call_code (code, 0);
3348                 }
3349
3350                 /* push lmf */
3351                 x86_push_reg (code, X86_EAX); 
3352                 /* push *lfm (previous_lmf) */
3353                 x86_push_membase (code, X86_EAX, 0);
3354                 /* *(lmf) = ESP */
3355                 x86_mov_membase_reg (code, X86_EAX, 0, X86_ESP, 4);
3356         } else {
3357
3358                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3359                         x86_push_reg (code, X86_EBX);
3360                         pos += 4;
3361                 }
3362
3363                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3364                         x86_push_reg (code, X86_EDI);
3365                         pos += 4;
3366                 }
3367
3368                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3369                         x86_push_reg (code, X86_ESI);
3370                         pos += 4;
3371                 }
3372         }
3373
3374         alloc_size -= pos;
3375
3376         if (alloc_size) {
3377                 /* See mono_emit_stack_alloc */
3378 #ifdef PLATFORM_WIN32
3379                 guint32 remaining_size = alloc_size;
3380                 while (remaining_size >= 0x1000) {
3381                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, 0x1000);
3382                         x86_test_membase_reg (code, X86_ESP, 0, X86_ESP);
3383                         remaining_size -= 0x1000;
3384                 }
3385                 if (remaining_size)
3386                         x86_alu_reg_imm (code, X86_SUB, X86_ESP, remaining_size);
3387 #else
3388                 x86_alu_reg_imm (code, X86_SUB, X86_ESP, alloc_size);
3389 #endif
3390         }
3391
3392         /* compute max_offset in order to use short forward jumps */
3393         max_offset = 0;
3394         if (cfg->opt & MONO_OPT_BRANCH) {
3395                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3396                         MonoInst *ins = bb->code;
3397                         bb->max_offset = max_offset;
3398
3399                         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
3400                                 max_offset += 6; 
3401
3402                         while (ins) {
3403                                 max_offset += ((guint8 *)ins_spec [ins->opcode])[MONO_INST_LEN];
3404                                 ins = ins->next;
3405                         }
3406                 }
3407         }
3408
3409         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
3410                 code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE);
3411
3412         /* load arguments allocated to register from the stack */
3413         sig = method->signature;
3414         pos = 0;
3415
3416         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3417                 inst = cfg->varinfo [pos];
3418                 if (inst->opcode == OP_REGVAR) {
3419                         x86_mov_reg_membase (code, inst->dreg, X86_EBP, inst->inst_offset, 4);
3420                         if (cfg->verbose_level > 2)
3421                                 g_print ("Argument %d assigned to register %s\n", pos, mono_arch_regname (inst->dreg));
3422                 }
3423                 pos++;
3424         }
3425
3426         cfg->code_len = code - cfg->native_code;
3427
3428         return code;
3429 }
3430
3431 void
3432 mono_arch_emit_epilog (MonoCompile *cfg)
3433 {
3434         MonoJumpInfo *patch_info;
3435         MonoMethod *method = cfg->method;
3436         MonoMethodSignature *sig = method->signature;
3437         int pos;
3438         guint32 stack_to_pop;
3439         guint8 *code;
3440
3441         code = cfg->native_code + cfg->code_len;
3442
3443         if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
3444                 code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE);
3445
3446         /* the code restoring the registers must be kept in sync with CEE_JMP */
3447         pos = 0;
3448         
3449         if (method->save_lmf) {
3450                 pos = -sizeof (MonoLMF);
3451         } else {
3452                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3453                         pos -= 4;
3454                 }
3455                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3456                         pos -= 4;
3457                 }
3458                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3459                         pos -= 4;
3460                 }
3461         }
3462
3463         if (pos)
3464                 x86_lea_membase (code, X86_ESP, X86_EBP, pos);
3465         
3466         if (method->save_lmf) {
3467                 /* ebx = previous_lmf */
3468                 x86_pop_reg (code, X86_EBX);
3469                 /* edi = lmf */
3470                 x86_pop_reg (code, X86_EDI);
3471                 /* *(lmf) = previous_lmf */
3472                 x86_mov_membase_reg (code, X86_EDI, 0, X86_EBX, 4);
3473
3474                 /* discard method info */
3475                 x86_pop_reg (code, X86_ESI);
3476
3477                 /* restore caller saved regs */
3478                 x86_pop_reg (code, X86_EBP);
3479                 x86_pop_reg (code, X86_ESI);
3480                 x86_pop_reg (code, X86_EDI);
3481                 x86_pop_reg (code, X86_EBX);
3482
3483         } else {
3484
3485                 if (cfg->used_int_regs & (1 << X86_ESI)) {
3486                         x86_pop_reg (code, X86_ESI);
3487                 }
3488                 if (cfg->used_int_regs & (1 << X86_EDI)) {
3489                         x86_pop_reg (code, X86_EDI);
3490                 }
3491                 if (cfg->used_int_regs & (1 << X86_EBX)) {
3492                         x86_pop_reg (code, X86_EBX);
3493                 }
3494         }
3495
3496         x86_leave (code);
3497
3498         if (CALLCONV_IS_STDCALL (sig->call_convention)) {
3499                 MonoJitArgumentInfo *arg_info = alloca (sizeof (MonoJitArgumentInfo) * (sig->param_count + 1));
3500
3501                 stack_to_pop = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
3502         } else if (MONO_TYPE_ISSTRUCT (cfg->method->signature->ret))
3503                 stack_to_pop = 4;
3504         else
3505                 stack_to_pop = 0;
3506
3507         if (stack_to_pop)
3508                 x86_ret_imm (code, stack_to_pop);
3509         else
3510                 x86_ret (code);
3511
3512         /* add code to raise exceptions */
3513         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3514                 switch (patch_info->type) {
3515                 case MONO_PATCH_INFO_EXC:
3516                         x86_patch (patch_info->ip.i + cfg->native_code, code);
3517                         mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_EXC_NAME, patch_info->data.target);
3518                         x86_push_imm (code, patch_info->data.target);
3519                         mono_add_patch_info (cfg, code + 1 - cfg->native_code, MONO_PATCH_INFO_METHOD_REL, (gpointer)patch_info->ip.i);
3520                         x86_push_imm (code, patch_info->ip.i + cfg->native_code);
3521                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
3522                         patch_info->data.name = "mono_arch_throw_exception_by_name";
3523                         patch_info->ip.i = code - cfg->native_code;
3524                         x86_jump_code (code, 0);
3525                         break;
3526                 default:
3527                         /* do nothing */
3528                         break;
3529                 }
3530         }
3531
3532         cfg->code_len = code - cfg->native_code;
3533
3534         g_assert (cfg->code_len < cfg->code_size);
3535
3536 }
3537
3538 void
3539 mono_arch_flush_icache (guint8 *code, gint size)
3540 {
3541         /* not needed */
3542 }
3543
3544 void
3545 mono_arch_flush_register_windows (void)
3546 {
3547 }
3548
3549 /*
3550  * Support for fast access to the thread-local lmf structure using the GS
3551  * segment register on NPTL + kernel 2.6.x.
3552  */
3553
3554 static gboolean tls_offset_inited = FALSE;
3555
3556 #ifdef HAVE_KW_THREAD
3557 static __thread gpointer mono_lmf_addr;
3558 #endif
3559
3560 static gpointer
3561 mono_arch_get_lmf_addr (void)
3562 {
3563 #ifdef HAVE_KW_THREAD
3564         return mono_lmf_addr;
3565 #else
3566         g_assert_not_reached ();
3567         return NULL;
3568 #endif
3569 }
3570
3571 void
3572 mono_arch_setup_jit_tls_data (MonoJitTlsData *tls)
3573 {
3574 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
3575         pthread_t self = pthread_self();
3576         pthread_attr_t attr;
3577         void *staddr = NULL;
3578         size_t stsize = 0;
3579         struct sigaltstack sa;
3580 #endif
3581
3582         if (!tls_offset_inited) {
3583                 guint8 *code;
3584
3585                 tls_offset_inited = TRUE;
3586
3587                 if (getenv ("MONO_NPTL")) {
3588                         /* 
3589                          * Determine the offset of mono_lfm_addr inside the TLS structures
3590                          * by disassembling the function above.
3591                          */
3592                         code = (guint8*)&mono_arch_get_lmf_addr;
3593
3594                         /* This is generated by gcc 3.3.2 */
3595                         if ((code [0] == 0x55) && (code [1] == 0x89) && (code [2] == 0xe5) &&
3596                                 (code [3] == 0x65) && (code [4] == 0xa1) && (code [5] == 0x00) &&
3597                                 (code [6] == 0x00) && (code [7] == 0x00) && (code [8] == 0x00) &&
3598                                 (code [9] == 0x8b) && (code [10] == 0x80)) {
3599                                 lmf_tls_offset = *(int*)&(code [11]);
3600                         }
3601                 }
3602         }               
3603
3604 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
3605
3606         /* Determine stack boundaries */
3607         if (!mono_running_on_valgrind ()) {
3608 #ifdef HAVE_PTHREAD_GETATTR_NP
3609                 pthread_getattr_np( self, &attr );
3610 #else
3611 #ifdef HAVE_PTHREAD_ATTR_GET_NP
3612                 pthread_attr_get_np( self, &attr );
3613 #else
3614 #error "Not implemented"
3615 #endif
3616 #endif
3617                 pthread_attr_getstack( &attr, &staddr, &stsize );
3618         }
3619
3620         /* 
3621          * staddr seems to be wrong for the main thread, so we keep the value in
3622          * tls->end_of_stack
3623          */
3624         tls->stack_size = stsize;
3625
3626         /* Setup an alternate signal stack */
3627         tls->signal_stack = g_malloc (SIGNAL_STACK_SIZE);
3628         tls->signal_stack_size = SIGNAL_STACK_SIZE;
3629
3630         sa.ss_sp = tls->signal_stack;
3631         sa.ss_size = SIGNAL_STACK_SIZE;
3632         sa.ss_flags = SS_ONSTACK;
3633         sigaltstack (&sa, NULL);
3634 #endif
3635
3636 #ifdef HAVE_KW_THREAD
3637         mono_lmf_addr = &tls->lmf;
3638 #endif
3639 }
3640
3641 void
3642 mono_arch_free_jit_tls_data (MonoJitTlsData *tls)
3643 {
3644 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
3645         struct sigaltstack sa;
3646
3647         sa.ss_sp = tls->signal_stack;
3648         sa.ss_size = SIGNAL_STACK_SIZE;
3649         sa.ss_flags = SS_DISABLE;
3650         sigaltstack  (&sa, NULL);
3651
3652         if (tls->signal_stack)
3653                 g_free (tls->signal_stack);
3654 #endif
3655 }
3656
3657 void
3658 mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg)
3659 {
3660
3661         /* add the this argument */
3662         if (this_reg != -1) {
3663                 MonoInst *this;
3664                 MONO_INST_NEW (cfg, this, OP_OUTARG);
3665                 this->type = this_type;
3666                 this->sreg1 = this_reg;
3667                 mono_bblock_add_inst (cfg->cbb, this);
3668         }
3669
3670         if (vt_reg != -1) {
3671                 MonoInst *vtarg;
3672                 MONO_INST_NEW (cfg, vtarg, OP_OUTARG);
3673                 vtarg->type = STACK_MP;
3674                 vtarg->sreg1 = vt_reg;
3675                 mono_bblock_add_inst (cfg->cbb, vtarg);
3676         }
3677 }
3678
3679
3680 gint
3681 mono_arch_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3682 {
3683         if (cmethod->klass == mono_defaults.math_class) {
3684                 if (strcmp (cmethod->name, "Sin") == 0)
3685                         return OP_SIN;
3686                 else if (strcmp (cmethod->name, "Cos") == 0)
3687                         return OP_COS;
3688                 else if (strcmp (cmethod->name, "Tan") == 0)
3689                         return OP_TAN;
3690                 else if (strcmp (cmethod->name, "Atan") == 0)
3691                         return OP_ATAN;
3692                 else if (strcmp (cmethod->name, "Sqrt") == 0)
3693                         return OP_SQRT;
3694                 else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8)
3695                         return OP_ABS;
3696 #if 0
3697                 /* OP_FREM is not IEEE compatible */
3698                 else if (strcmp (cmethod->name, "IEEERemainder") == 0)
3699                         return OP_FREM;
3700 #endif
3701                 else
3702                         return -1;
3703         } else {
3704                 return -1;
3705         }
3706         return -1;
3707 }
3708
3709
3710 gboolean
3711 mono_arch_print_tree (MonoInst *tree, int arity)
3712 {
3713         return 0;
3714 }