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