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