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