- add alignment of stack parameter to be parameters set
[libfirm] / ir / be / arm / bearch_arm.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   The main arm backend driver file.
23  * @author  Oliver Richter, Tobias Gneist
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include "lc_opts.h"
29 #include "lc_opts_enum.h"
30
31 #include "pseudo_irg.h"
32 #include "irgwalk.h"
33 #include "irprog.h"
34 #include "irprintf.h"
35 #include "ircons.h"
36 #include "irgmod.h"
37 #include "irgopt.h"
38 #include "iroptimize.h"
39 #include "lowering.h"
40 #include "error.h"
41
42 #include "bitset.h"
43 #include "debug.h"
44 #include "array_t.h"
45 #include "irtools.h"
46
47 #include "../bearch_t.h"                /* the general register allocator interface */
48 #include "../benode_t.h"
49 #include "../belower.h"
50 #include "../besched_t.h"
51 #include "be.h"
52 #include "../beabi.h"
53 #include "../bemachine.h"
54 #include "../beilpsched.h"
55 #include "../bemodule.h"
56 #include "../beirg_t.h"
57 #include "../bespillslots.h"
58 #include "../begnuas.h"
59
60 #include "bearch_arm_t.h"
61
62 #include "arm_new_nodes.h"           /* arm nodes interface */
63 #include "gen_arm_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
64 #include "arm_transform.h"
65 #include "arm_optimize.h"
66 #include "arm_emitter.h"
67 #include "arm_map_regs.h"
68
69 #define DEBUG_MODULE "firm.be.arm.isa"
70
71 /* TODO: ugly, but we need it to get access to the registers assigned to Phi nodes */
72 static set *cur_reg_set = NULL;
73
74 /**************************************************
75  *                         _ _              _  __
76  *                        | | |            (_)/ _|
77  *  _ __ ___  __ _    __ _| | | ___   ___   _| |_
78  * | '__/ _ \/ _` |  / _` | | |/ _ \ / __| | |  _|
79  * | | |  __/ (_| | | (_| | | | (_) | (__  | | |
80  * |_|  \___|\__, |  \__,_|_|_|\___/ \___| |_|_|
81  *            __/ |
82  *           |___/
83  **************************************************/
84
85 /**
86  * Return register requirements for a arm node.
87  * If the node returns a tuple (mode_T) then the proj's
88  * will be asked for this information.
89  */
90 static const arch_register_req_t *arm_get_irn_reg_req(const ir_node *node,
91                                                       int pos)
92 {
93         long               node_pos = pos == -1 ? 0 : pos;
94         ir_mode           *mode     = get_irn_mode(node);
95
96         if (is_Block(node) || mode == mode_X) {
97                 return arch_no_register_req;
98         }
99
100         if (mode == mode_T && pos < 0) {
101                 return arch_no_register_req;
102         }
103
104         if (is_Proj(node)) {
105                 if(mode == mode_M)
106                         return arch_no_register_req;
107
108                 if(pos >= 0) {
109                         return arch_no_register_req;
110                 }
111
112                 node_pos = (pos == -1) ? get_Proj_proj(node) : pos;
113                 node     = skip_Proj_const(node);
114         }
115
116         /* get requirements for our own nodes */
117         if (is_arm_irn(node)) {
118                 const arch_register_req_t *req;
119                 if (pos >= 0) {
120                         req = get_arm_in_req(node, pos);
121                 } else {
122                         req = get_arm_out_req(node, node_pos);
123                 }
124
125                 return req;
126         }
127
128         /* unknown should be transformed by now */
129         assert(!is_Unknown(node));
130         return arch_no_register_req;
131 }
132
133 static arch_irn_class_t arm_classify(const ir_node *irn)
134 {
135         irn = skip_Proj_const(irn);
136
137         if (is_cfop(irn)) {
138                 return arch_irn_class_branch;
139         }
140
141         return 0;
142 }
143
144 static ir_entity *arm_get_frame_entity(const ir_node *irn) {
145         /* we do NOT transform be_Spill or be_Reload nodes, so we never
146            have frame access using ARM nodes. */
147         (void) irn;
148         return NULL;
149 }
150
151 static void arm_set_frame_entity(ir_node *irn, ir_entity *ent) {
152         (void) irn;
153         (void) ent;
154         panic("arm_set_frame_entity() called. This should not happen.");
155 }
156
157 /**
158  * This function is called by the generic backend to correct offsets for
159  * nodes accessing the stack.
160  */
161 static void arm_set_stack_bias(ir_node *irn, int bias)
162 {
163         (void) irn;
164         (void) bias;
165         /* TODO: correct offset if irn accesses the stack */
166 }
167
168 static int arm_get_sp_bias(const ir_node *irn)
169 {
170         (void) irn;
171         return 0;
172 }
173
174 /* fill register allocator interface */
175
176 static const arch_irn_ops_t arm_irn_ops = {
177         arm_get_irn_reg_req,
178         arm_classify,
179         arm_get_frame_entity,
180         arm_set_frame_entity,
181         arm_set_stack_bias,
182         arm_get_sp_bias,
183         NULL,    /* get_inverse             */
184         NULL,    /* get_op_estimated_cost   */
185         NULL,    /* possible_memory_operand */
186         NULL,    /* perform_memory_operand  */
187 };
188
189 /**************************************************
190  *                _                         _  __
191  *               | |                       (_)/ _|
192  *   ___ ___   __| | ___  __ _  ___ _ __    _| |_
193  *  / __/ _ \ / _` |/ _ \/ _` |/ _ \ '_ \  | |  _|
194  * | (_| (_) | (_| |  __/ (_| |  __/ | | | | | |
195  *  \___\___/ \__,_|\___|\__, |\___|_| |_| |_|_|
196  *                        __/ |
197  *                       |___/
198  **************************************************/
199
200 /**
201  * Transforms the standard Firm graph into
202  * a ARM firm graph.
203  */
204 static void arm_prepare_graph(void *self) {
205         arm_code_gen_t *cg = self;
206
207         /* transform nodes into assembler instructions */
208         arm_transform_graph(cg);
209
210         /* do local optimizations (mainly CSE) */
211         local_optimize_graph(cg->irg);
212
213         if (cg->dump)
214                 be_dump(cg->irg, "-transformed", dump_ir_block_graph_sched);
215
216         /* do code placement, to optimize the position of constants */
217         place_code(cg->irg);
218
219         if (cg->dump)
220                 be_dump(cg->irg, "-place", dump_ir_block_graph_sched);
221 }
222
223 /**
224  * Called immediately before emit phase.
225  */
226 static void arm_finish_irg(void *self)
227 {
228         arm_code_gen_t *cg = self;
229
230         /* do peephole optimizations and fix stack offsets */
231         arm_peephole_optimization(cg);
232 }
233
234
235 static void arm_before_ra(void *self)
236 {
237         (void) self;
238         /* Some stuff you need to do immediately after register allocation */
239 }
240
241 /**
242  * We transform Spill and Reload here. This needs to be done before
243  * stack biasing otherwise we would miss the corrected offset for these nodes.
244  */
245 static void arm_after_ra(void *self)
246 {
247         arm_code_gen_t *cg = self;
248         be_coalesce_spillslots(cg->birg);
249 }
250
251 /**
252  * Emits the code, closes the output file and frees
253  * the code generator interface.
254  */
255 static void arm_emit_and_done(void *self) {
256         arm_code_gen_t *cg = self;
257         ir_graph       *irg = cg->irg;
258
259         arm_gen_routine(cg, irg);
260
261         cur_reg_set = NULL;
262
263         /* de-allocate code generator */
264         del_set(cg->reg_set);
265         free(self);
266 }
267
268 /**
269  * Move a double floating point value into an integer register.
270  * Place the move operation into block bl.
271  *
272  * Handle some special cases here:
273  * 1.) A constant: simply split into two
274  * 2.) A load: simply split into two
275  */
276 static ir_node *convert_dbl_to_int(ir_node *bl, ir_node *arg, ir_node *mem,
277                                    ir_node **resH, ir_node **resL) {
278         if (is_Const(arg)) {
279                 tarval *tv = get_Const_tarval(arg);
280                 unsigned v;
281
282                 /* get the upper 32 bits */
283                 v =            get_tarval_sub_bits(tv, 7);
284                 v = (v << 8) | get_tarval_sub_bits(tv, 6);
285                 v = (v << 8) | get_tarval_sub_bits(tv, 5);
286                 v = (v << 8) | get_tarval_sub_bits(tv, 4);
287                 *resH = new_Const_long(mode_Is, v);
288
289                 /* get the lower 32 bits */
290                 v =            get_tarval_sub_bits(tv, 3);
291                 v = (v << 8) | get_tarval_sub_bits(tv, 2);
292                 v = (v << 8) | get_tarval_sub_bits(tv, 1);
293                 v = (v << 8) | get_tarval_sub_bits(tv, 0);
294                 *resL = new_Const_long(mode_Is, v);
295         } else if (is_Load(skip_Proj(arg))) {
296                 /* FIXME: handling of low/high depends on LE/BE here */
297                 panic("Unimplemented convert_dbl_to_int() case");
298         }
299         else {
300                 ir_graph *irg = current_ir_graph;
301                 ir_node *conv;
302
303                 conv = new_bd_arm_fpaDbl2GP(NULL, bl, arg, mem);
304                 /* move high/low */
305                 *resL = new_r_Proj(irg, bl, conv, mode_Is, pn_arm_fpaDbl2GP_low);
306                 *resH = new_r_Proj(irg, bl, conv, mode_Is, pn_arm_fpaDbl2GP_high);
307                 mem   = new_r_Proj(irg, bl, conv, mode_M,  pn_arm_fpaDbl2GP_M);
308         }
309         return mem;
310 }
311
312 /**
313  * Move a single floating point value into an integer register.
314  * Place the move operation into block bl.
315  *
316  * Handle some special cases here:
317  * 1.) A constant: simply move
318  * 2.) A load: simply load
319  */
320 static ir_node *convert_sng_to_int(ir_node *bl, ir_node *arg)
321 {
322         (void) bl;
323
324         if (is_Const(arg)) {
325                 tarval *tv = get_Const_tarval(arg);
326                 unsigned v;
327
328                 /* get the lower 32 bits */
329                 v =            get_tarval_sub_bits(tv, 3);
330                 v = (v << 8) | get_tarval_sub_bits(tv, 2);
331                 v = (v << 8) | get_tarval_sub_bits(tv, 1);
332                 v = (v << 8) | get_tarval_sub_bits(tv, 0);
333                 return new_Const_long(mode_Is, v);
334         } else if (is_Load(skip_Proj(arg))) {
335                 ir_node *load;
336
337                 load = skip_Proj(arg);
338         }
339         panic("Unimplemented convert_sng_to_int() case");
340 }
341
342 /**
343  * Convert the arguments of a call to support the
344  * ARM calling convention of general purpose AND floating
345  * point arguments.
346  */
347 static void handle_calls(ir_node *call, void *env)
348 {
349         arm_code_gen_t *cg = env;
350         int i, j, n, size, idx, flag, n_param, n_res, first_variadic;
351         ir_type *mtp, *new_mtd, *new_tp[5];
352         ir_node *new_in[5], **in;
353         ir_node *bl;
354
355         if (! is_Call(call))
356                 return;
357
358         /* check, if we need conversions */
359         n = get_Call_n_params(call);
360         mtp = get_Call_type(call);
361         assert(get_method_n_params(mtp) == n);
362
363         /* it's always enough to handle the first 4 parameters */
364         if (n > 4)
365                 n = 4;
366         flag = size = idx = 0;
367         bl = get_nodes_block(call);
368         for (i = 0; i < n; ++i) {
369                 ir_type *param_tp = get_method_param_type(mtp, i);
370
371                 if (is_compound_type(param_tp)) {
372                         /* an aggregate parameter: bad case */
373                         assert(0);
374                 }
375                 else {
376                         /* a primitive parameter */
377                         ir_mode *mode = get_type_mode(param_tp);
378
379                         if (mode_is_float(mode)) {
380                                 if (get_mode_size_bits(mode) > 32) {
381                                         ir_node *mem = get_Call_mem(call);
382
383                                         /* Beware: ARM wants the high part first */
384                                         size += 2 * 4;
385                                         new_tp[idx]   = cg->int_tp;
386                                         new_tp[idx+1] = cg->int_tp;
387                                         mem = convert_dbl_to_int(bl, get_Call_param(call, i), mem, &new_in[idx], &new_in[idx+1]);
388                                         idx += 2;
389                                         set_Call_mem(call, mem);
390                                 }
391                                 else {
392                                         size += 4;
393                                         new_tp[idx] = cg->int_tp;
394                                         new_in[idx] = convert_sng_to_int(bl, get_Call_param(call, i));
395                                         ++idx;
396                                 }
397                                 flag = 1;
398                         }
399                         else {
400                                 size += 4;
401                                 new_tp[idx] = param_tp;
402                                 new_in[idx] = get_Call_param(call, i);
403                                 ++idx;
404                         }
405                 }
406
407                 if (size >= 16)
408                         break;
409         }
410
411         /* if flag is NOT set, no need to translate the method type */
412         if (! flag)
413                 return;
414
415         /* construct a new method type */
416         n       = i;
417         n_param = get_method_n_params(mtp) - n + idx;
418         n_res   = get_method_n_ress(mtp);
419         new_mtd = new_d_type_method(get_type_ident(mtp), n_param, n_res, get_type_dbg_info(mtp));
420
421         for (i = 0; i < idx; ++i)
422                 set_method_param_type(new_mtd, i, new_tp[i]);
423         for (i = n, j = idx; i < get_method_n_params(mtp); ++i)
424                 set_method_param_type(new_mtd, j++, get_method_param_type(mtp, i));
425         for (i = 0; i < n_res; ++i)
426                 set_method_res_type(new_mtd, i, get_method_res_type(mtp, i));
427
428         set_method_calling_convention(new_mtd, get_method_calling_convention(mtp));
429         first_variadic = get_method_first_variadic_param_index(mtp);
430         if (first_variadic >= 0)
431                 set_method_first_variadic_param_index(new_mtd, first_variadic);
432
433         if (is_lowered_type(mtp)) {
434                 mtp = get_associated_type(mtp);
435         }
436         set_lowered_type(mtp, new_mtd);
437
438         set_Call_type(call, new_mtd);
439
440         /* calculate new in array of the Call */
441         NEW_ARR_A(ir_node *, in, n_param + 2);
442         for (i = 0; i < idx; ++i)
443                 in[2 + i] = new_in[i];
444         for (i = n, j = idx; i < get_method_n_params(mtp); ++i)
445                 in[2 + j++] = get_Call_param(call, i);
446
447         in[0] = get_Call_mem(call);
448         in[1] = get_Call_ptr(call);
449
450         /* finally, change the call inputs */
451         set_irn_in(call, n_param + 2, in);
452 }
453
454 /**
455  * Handle graph transformations before the abi converter does its work.
456  */
457 static void arm_before_abi(void *self) {
458         arm_code_gen_t *cg = self;
459
460         irg_walk_graph(cg->irg, NULL, handle_calls, cg);
461 }
462
463 /* forward */
464 static void *arm_cg_init(be_irg_t *birg);
465
466 static const arch_code_generator_if_t arm_code_gen_if = {
467         arm_cg_init,
468         NULL,               /* get_pic_base */
469         arm_before_abi,     /* before abi introduce */
470         arm_prepare_graph,
471         NULL,               /* spill */
472         arm_before_ra,      /* before register allocation hook */
473         arm_after_ra,
474         arm_finish_irg,
475         arm_emit_and_done,
476 };
477
478 /**
479  * Initializes the code generator.
480  */
481 static void *arm_cg_init(be_irg_t *birg) {
482         static ir_type *int_tp = NULL;
483         arm_isa_t      *isa = (arm_isa_t *)birg->main_env->arch_env;
484         arm_code_gen_t *cg;
485
486         if (! int_tp) {
487                 /* create an integer type with machine size */
488                 int_tp = new_type_primitive(new_id_from_chars("int", 3), mode_Is);
489         }
490
491         cg = XMALLOC(arm_code_gen_t);
492         cg->impl         = &arm_code_gen_if;
493         cg->irg          = birg->irg;
494         cg->reg_set      = new_set(arm_cmp_irn_reg_assoc, 1024);
495         cg->isa          = isa;
496         cg->birg         = birg;
497         cg->int_tp       = int_tp;
498         cg->have_fp_insn = 0;
499         cg->unknown_gp   = NULL;
500         cg->unknown_fpa  = NULL;
501         cg->dump         = (birg->main_env->options->dump_flags & DUMP_BE) ? 1 : 0;
502
503         FIRM_DBG_REGISTER(cg->mod, "firm.be.arm.cg");
504
505         cur_reg_set = cg->reg_set;
506
507         /* enter the current code generator */
508         isa->cg = cg;
509
510         return (arch_code_generator_t *)cg;
511 }
512
513
514 /**
515  * Maps all intrinsic calls that the backend support
516  * and map all instructions the backend did not support
517  * to runtime calls.
518  */
519 static void arm_handle_intrinsics(void) {
520         ir_type *tp, *int_tp, *uint_tp;
521         i_record records[8];
522         int n_records = 0;
523
524         runtime_rt rt_iDiv, rt_uDiv, rt_iMod, rt_uMod;
525
526 #define ID(x) new_id_from_chars(x, sizeof(x)-1)
527
528         int_tp  = new_type_primitive(ID("int"), mode_Is);
529         uint_tp = new_type_primitive(ID("uint"), mode_Iu);
530
531         /* ARM has neither a signed div instruction ... */
532         {
533                 i_instr_record *map_Div = &records[n_records++].i_instr;
534
535                 tp = new_type_method(ID("rt_iDiv"), 2, 1);
536                 set_method_param_type(tp, 0, int_tp);
537                 set_method_param_type(tp, 1, int_tp);
538                 set_method_res_type(tp, 0, int_tp);
539
540                 rt_iDiv.ent             = new_entity(get_glob_type(), ID("__divsi3"), tp);
541                 set_entity_ld_ident(rt_iDiv.ent, ID("__divsi3"));
542                 rt_iDiv.mode            = mode_T;
543                 rt_iDiv.res_mode        = mode_Is;
544                 rt_iDiv.mem_proj_nr     = pn_Div_M;
545                 rt_iDiv.regular_proj_nr = pn_Div_X_regular;
546                 rt_iDiv.exc_proj_nr     = pn_Div_X_except;
547                 rt_iDiv.exc_mem_proj_nr = pn_Div_M;
548                 rt_iDiv.res_proj_nr     = pn_Div_res;
549
550                 set_entity_visibility(rt_iDiv.ent, visibility_external_allocated);
551
552                 map_Div->kind     = INTRINSIC_INSTR;
553                 map_Div->op       = op_Div;
554                 map_Div->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
555                 map_Div->ctx      = &rt_iDiv;
556         }
557         /* ... nor an unsigned div instruction ... */
558         {
559                 i_instr_record *map_Div = &records[n_records++].i_instr;
560
561                 tp = new_type_method(ID("rt_uDiv"), 2, 1);
562                 set_method_param_type(tp, 0, uint_tp);
563                 set_method_param_type(tp, 1, uint_tp);
564                 set_method_res_type(tp, 0, uint_tp);
565
566                 rt_uDiv.ent             = new_entity(get_glob_type(), ID("__udivsi3"), tp);
567                 set_entity_ld_ident(rt_uDiv.ent, ID("__udivsi3"));
568                 rt_uDiv.mode            = mode_T;
569                 rt_uDiv.res_mode        = mode_Iu;
570                 rt_uDiv.mem_proj_nr     = pn_Div_M;
571                 rt_uDiv.regular_proj_nr = pn_Div_X_regular;
572                 rt_uDiv.exc_proj_nr     = pn_Div_X_except;
573                 rt_uDiv.exc_mem_proj_nr = pn_Div_M;
574                 rt_uDiv.res_proj_nr     = pn_Div_res;
575
576                 set_entity_visibility(rt_uDiv.ent, visibility_external_allocated);
577
578                 map_Div->kind     = INTRINSIC_INSTR;
579                 map_Div->op       = op_Div;
580                 map_Div->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
581                 map_Div->ctx      = &rt_uDiv;
582         }
583         /* ... nor a signed mod instruction ... */
584         {
585                 i_instr_record *map_Mod = &records[n_records++].i_instr;
586
587                 tp = new_type_method(ID("rt_iMod"), 2, 1);
588                 set_method_param_type(tp, 0, int_tp);
589                 set_method_param_type(tp, 1, int_tp);
590                 set_method_res_type(tp, 0, int_tp);
591
592                 rt_iMod.ent             = new_entity(get_glob_type(), ID("__modsi3"), tp);
593                 set_entity_ld_ident(rt_iMod.ent, ID("__modsi3"));
594                 rt_iMod.mode            = mode_T;
595                 rt_iMod.res_mode        = mode_Is;
596                 rt_iMod.mem_proj_nr     = pn_Mod_M;
597                 rt_iMod.regular_proj_nr = pn_Mod_X_regular;
598                 rt_iMod.exc_proj_nr     = pn_Mod_X_except;
599                 rt_iMod.exc_mem_proj_nr = pn_Mod_M;
600                 rt_iMod.res_proj_nr     = pn_Mod_res;
601
602                 set_entity_visibility(rt_iMod.ent, visibility_external_allocated);
603
604                 map_Mod->kind     = INTRINSIC_INSTR;
605                 map_Mod->op       = op_Mod;
606                 map_Mod->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
607                 map_Mod->ctx      = &rt_iMod;
608         }
609         /* ... nor an unsigned mod. */
610         {
611                 i_instr_record *map_Mod = &records[n_records++].i_instr;
612
613                 tp = new_type_method(ID("rt_uMod"), 2, 1);
614                 set_method_param_type(tp, 0, uint_tp);
615                 set_method_param_type(tp, 1, uint_tp);
616                 set_method_res_type(tp, 0, uint_tp);
617
618                 rt_uMod.ent             = new_entity(get_glob_type(), ID("__umodsi3"), tp);
619                 set_entity_ld_ident(rt_uMod.ent, ID("__umodsi3"));
620                 rt_uMod.mode            = mode_T;
621                 rt_uMod.res_mode        = mode_Iu;
622                 rt_uMod.mem_proj_nr     = pn_Mod_M;
623                 rt_uMod.regular_proj_nr = pn_Mod_X_regular;
624                 rt_uMod.exc_proj_nr     = pn_Mod_X_except;
625                 rt_uMod.exc_mem_proj_nr = pn_Mod_M;
626                 rt_uMod.res_proj_nr     = pn_Mod_res;
627
628                 set_entity_visibility(rt_uMod.ent, visibility_external_allocated);
629
630                 map_Mod->kind     = INTRINSIC_INSTR;
631                 map_Mod->op       = op_Mod;
632                 map_Mod->i_mapper = (i_mapper_func)i_mapper_RuntimeCall;
633                 map_Mod->ctx      = &rt_uMod;
634         }
635
636         if (n_records > 0)
637                 lower_intrinsics(records, n_records, /*part_block_used=*/0);
638 }
639
640 /*****************************************************************
641  *  ____             _                  _   _____  _____
642  * |  _ \           | |                | | |_   _|/ ____|  /\
643  * | |_) | __ _  ___| | _____ _ __   __| |   | | | (___   /  \
644  * |  _ < / _` |/ __| |/ / _ \ '_ \ / _` |   | |  \___ \ / /\ \
645  * | |_) | (_| | (__|   <  __/ | | | (_| |  _| |_ ____) / ____ \
646  * |____/ \__,_|\___|_|\_\___|_| |_|\__,_| |_____|_____/_/    \_\
647  *
648  *****************************************************************/
649
650 static arm_isa_t arm_isa_template = {
651         {
652                 &arm_isa_if,           /* isa interface */
653                 &arm_gp_regs[REG_SP],  /* stack pointer */
654                 &arm_gp_regs[REG_R11], /* base pointer */
655                 -1,                    /* stack direction */
656                 2,                     /* power of two stack alignment for calls, 2^2 == 4 */
657                 NULL,                  /* main environment */
658                 7,                     /* spill costs */
659                 5,                     /* reload costs */
660         },
661         0,                     /* use generic register names instead of SP, LR, PC */
662         ARM_FPU_ARCH_FPE,      /* FPU architecture */
663         NULL,                  /* current code generator */
664 };
665
666 /**
667  * Initializes the backend ISA and opens the output file.
668  */
669 static arch_env_t *arm_init(FILE *file_handle) {
670         static int inited = 0;
671         arm_isa_t *isa;
672
673         if (inited)
674                 return NULL;
675
676         isa = XMALLOC(arm_isa_t);
677         memcpy(isa, &arm_isa_template, sizeof(*isa));
678
679         arm_register_init();
680
681         isa->cg  = NULL;
682         be_emit_init(file_handle);
683
684         arm_create_opcodes(&arm_irn_ops);
685         arm_handle_intrinsics();
686
687         /* needed for the debug support */
688         be_gas_emit_switch_section(GAS_SECTION_TEXT);
689         be_emit_cstring(".Ltext0:\n");
690         be_emit_write_line();
691
692         /* we mark referenced global entities, so we can only emit those which
693          * are actually referenced. (Note: you mustn't use the type visited flag
694          * elsewhere in the backend)
695          */
696         inc_master_type_visited();
697
698         inited = 1;
699         return &isa->arch_env;
700 }
701
702
703
704 /**
705  * Closes the output file and frees the ISA structure.
706  */
707 static void arm_done(void *self) {
708         arm_isa_t *isa = self;
709
710         be_gas_emit_decls(isa->arch_env.main_env, 1);
711
712         be_emit_exit();
713         free(self);
714 }
715
716
717 /**
718  * Report the number of register classes.
719  * If we don't have fp instructions, report only GP
720  * here to speed up register allocation (and makes dumps
721  * smaller and more readable).
722  */
723 static unsigned arm_get_n_reg_class(const void *self) {
724         (void) self;
725         return N_CLASSES;
726 }
727
728 /**
729  * Return the register class with requested index.
730  */
731 static const arch_register_class_t *arm_get_reg_class(const void *self,
732                                                       unsigned i) {
733         (void) self;
734         assert(i < N_CLASSES);
735         return &arm_reg_classes[i];
736 }
737
738 /**
739  * Get the register class which shall be used to store a value of a given mode.
740  * @param self The this pointer.
741  * @param mode The mode in question.
742  * @return A register class which can hold values of the given mode.
743  */
744 const arch_register_class_t *arm_get_reg_class_for_mode(const void *self, const ir_mode *mode) {
745         (void) self;
746         if (mode_is_float(mode))
747                 return &arm_reg_classes[CLASS_arm_fpa];
748         else
749                 return &arm_reg_classes[CLASS_arm_gp];
750 }
751
752 /**
753  * Produces the type which sits between the stack args and the locals on the stack.
754  * it will contain the return address and space to store the old base pointer.
755  * @return The Firm type modeling the ABI between type.
756  */
757 static ir_type *arm_get_between_type(void *self) {
758         static ir_type *between_type = NULL;
759         static ir_entity *old_bp_ent = NULL;
760         (void) self;
761
762         if (between_type == NULL) {
763                 ir_entity *ret_addr_ent;
764                 ir_type *ret_addr_type = new_type_primitive(new_id_from_str("return_addr"), mode_P);
765                 ir_type *old_bp_type   = new_type_primitive(new_id_from_str("bp"), mode_P);
766
767                 between_type           = new_type_class(new_id_from_str("arm_between_type"));
768                 old_bp_ent             = new_entity(between_type, new_id_from_str("old_bp"), old_bp_type);
769                 ret_addr_ent           = new_entity(between_type, new_id_from_str("old_bp"), ret_addr_type);
770
771                 set_entity_offset(old_bp_ent, 0);
772                 set_entity_offset(ret_addr_ent, get_type_size_bytes(old_bp_type));
773                 set_type_size_bytes(between_type, get_type_size_bytes(old_bp_type) + get_type_size_bytes(ret_addr_type));
774         }
775
776         return between_type;
777 }
778
779
780 typedef struct {
781         be_abi_call_flags_bits_t flags;
782         const arch_env_t *arch_env;
783         ir_graph *irg;
784 } arm_abi_env_t;
785
786 static void *arm_abi_init(const be_abi_call_t *call, const arch_env_t *arch_env, ir_graph *irg)
787 {
788         arm_abi_env_t       *env = XMALLOC(arm_abi_env_t);
789         be_abi_call_flags_t  fl  = be_abi_call_get_flags(call);
790         env->flags    = fl.bits;
791         env->irg      = irg;
792         env->arch_env = arch_env;
793         return env;
794 }
795
796 /**
797  * Generate the routine prologue.
798  *
799  * @param self       The callback object.
800  * @param mem        A pointer to the mem node. Update this if you define new memory.
801  * @param reg_map    A map mapping all callee_save/ignore/parameter registers to their defining nodes.
802  * @param stack_bias Points to the current stack bias, can be modified if needed.
803  *
804  * @return        The register which shall be used as a stack frame base.
805  *
806  * All nodes which define registers in @p reg_map must keep @p reg_map current.
807  */
808 static const arch_register_t *arm_abi_prologue(void *self, ir_node **mem, pmap *reg_map, int *stack_bias) {
809         arm_abi_env_t         *env = self;
810         ir_node               *keep, *store;
811         ir_graph              *irg;
812         ir_node               *block;
813         arch_register_class_t *gp;
814
815         ir_node               *fp, *ip, *lr, *pc;
816         ir_node               *sp = be_abi_reg_map_get(reg_map, env->arch_env->sp);
817
818         (void) stack_bias;
819
820         if (env->flags.try_omit_fp)
821                 return env->arch_env->sp;
822
823         fp = be_abi_reg_map_get(reg_map, env->arch_env->bp);
824         ip = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_R12]);
825         lr = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_LR]);
826         pc = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_PC]);
827
828         gp    = &arm_reg_classes[CLASS_arm_gp];
829         irg   = env->irg;
830         block = get_irg_start_block(irg);
831
832         ip = be_new_Copy(gp, irg, block, sp);
833         be_set_constr_single_reg_out(ip, 0, &arm_gp_regs[REG_R12], arch_register_req_type_produces_sp);
834
835         store = new_bd_arm_StoreStackM4Inc(NULL, block, sp, fp, ip, lr, pc, *mem);
836
837         sp = new_r_Proj(irg, block, store, env->arch_env->sp->reg_class->mode, pn_arm_StoreStackM4Inc_ptr);
838         arch_set_irn_register(sp, env->arch_env->sp);
839         *mem = new_r_Proj(irg, block, store, mode_M, pn_arm_StoreStackM4Inc_M);
840
841         keep = be_new_CopyKeep_single(gp, irg, block, ip, sp, get_irn_mode(ip));
842         be_node_set_reg_class_in(keep, 1, gp);
843         be_set_constr_single_reg_out(keep, 0, &arm_gp_regs[REG_R12], arch_register_req_type_produces_sp);
844
845         fp = new_bd_arm_Sub_i(NULL, block, keep, get_irn_mode(fp), 4);
846         arch_set_irn_register(fp, env->arch_env->bp);
847         fp = be_new_Copy(gp, irg, block, fp); // XXX Gammelfix: only be_ have custom register requirements
848         be_set_constr_single_reg_out(fp, 0, env->arch_env->bp, 0);
849
850         be_abi_reg_map_set(reg_map, env->arch_env->bp, fp);
851         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_R12], keep);
852         be_abi_reg_map_set(reg_map, env->arch_env->sp, sp);
853         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_LR], lr);
854         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_PC], pc);
855
856         return env->arch_env->bp;
857 }
858
859 /**
860  * Builds the ARM epilogue
861  */
862 static void arm_abi_epilogue(void *self, ir_node *bl, ir_node **mem, pmap *reg_map) {
863         arm_abi_env_t *env = self;
864         ir_node *curr_sp = be_abi_reg_map_get(reg_map, env->arch_env->sp);
865         ir_node *curr_bp = be_abi_reg_map_get(reg_map, env->arch_env->bp);
866         ir_node *curr_pc = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_PC]);
867         ir_node *curr_lr = be_abi_reg_map_get(reg_map, &arm_gp_regs[REG_LR]);
868
869         // TODO: Activate Omit fp in epilogue
870         if (env->flags.try_omit_fp) {
871                 curr_sp = be_new_IncSP(env->arch_env->sp, env->irg, bl, curr_sp, BE_STACK_FRAME_SIZE_SHRINK, 0);
872
873                 curr_lr = be_new_CopyKeep_single(&arm_reg_classes[CLASS_arm_gp], env->irg, bl, curr_lr, curr_sp, get_irn_mode(curr_lr));
874                 be_set_constr_single_reg_out(curr_lr, 0, &arm_gp_regs[REG_LR], 0);
875
876                 curr_pc = be_new_Copy(&arm_reg_classes[CLASS_arm_gp], env->irg, bl, curr_lr );
877                 be_set_constr_single_reg_out(curr_pc, BE_OUT_POS(0), &arm_gp_regs[REG_PC], 0);
878         } else {
879                 ir_node *sub12_node;
880                 ir_node *load_node;
881                 sub12_node = new_bd_arm_Sub_i(NULL, bl, curr_bp, mode_Iu, 12);
882                 // FIXME
883                 //set_arm_req_out_all(sub12_node, sub12_req);
884                 arch_set_irn_register(sub12_node, env->arch_env->sp);
885                 load_node = new_bd_arm_LoadStackM3(NULL, bl, sub12_node, *mem);
886                 // FIXME
887                 //set_arm_req_out(load_node, &arm_default_req_arm_gp_r11, 0);
888                 //set_arm_req_out(load_node, &arm_default_req_arm_gp_sp, 1);
889                 //set_arm_req_out(load_node, &arm_default_req_arm_gp_pc, 2);
890                 curr_bp = new_r_Proj(env->irg, bl, load_node, env->arch_env->bp->reg_class->mode, pn_arm_LoadStackM3_res0);
891                 curr_sp = new_r_Proj(env->irg, bl, load_node, env->arch_env->sp->reg_class->mode, pn_arm_LoadStackM3_res1);
892                 curr_pc = new_r_Proj(env->irg, bl, load_node, mode_Iu, pn_arm_LoadStackM3_res2);
893                 *mem    = new_r_Proj(env->irg, bl, load_node, mode_M, pn_arm_LoadStackM3_M);
894                 arch_set_irn_register(curr_bp, env->arch_env->bp);
895                 arch_set_irn_register(curr_sp, env->arch_env->sp);
896                 arch_set_irn_register(curr_pc, &arm_gp_regs[REG_PC]);
897         }
898         be_abi_reg_map_set(reg_map, env->arch_env->sp, curr_sp);
899         be_abi_reg_map_set(reg_map, env->arch_env->bp, curr_bp);
900         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_LR], curr_lr);
901         be_abi_reg_map_set(reg_map, &arm_gp_regs[REG_PC], curr_pc);
902 }
903
904 static const be_abi_callbacks_t arm_abi_callbacks = {
905         arm_abi_init,
906         free,
907         arm_get_between_type,
908         arm_abi_prologue,
909         arm_abi_epilogue,
910 };
911
912
913 /**
914  * Get the ABI restrictions for procedure calls.
915  * @param self        The this pointer.
916  * @param method_type The type of the method (procedure) in question.
917  * @param abi         The abi object to be modified
918  */
919 void arm_get_call_abi(const void *self, ir_type *method_type, be_abi_call_t *abi) {
920         ir_type  *tp;
921         ir_mode  *mode;
922         int       i;
923         int       n = get_method_n_params(method_type);
924         be_abi_call_flags_t call_flags = be_abi_call_get_flags(abi);
925         (void) self;
926
927         /* set abi flags for calls */
928         call_flags.bits.left_to_right         = 0;
929         call_flags.bits.store_args_sequential = 0;
930         /* call_flags.bits.try_omit_fp     don't change this we can handle both */
931         call_flags.bits.fp_free               = 0;
932         call_flags.bits.call_has_imm          = 1;  /* IA32 calls can have immediate address */
933
934         /* set stack parameter passing style */
935         be_abi_call_set_flags(abi, call_flags, &arm_abi_callbacks);
936
937         for (i = 0; i < n; i++) {
938                 /* reg = get reg for param i;          */
939                 /* be_abi_call_param_reg(abi, i, reg); */
940                 if (i < 4) {
941                         be_abi_call_param_reg(abi, i, arm_get_RegParam_reg(i));
942                 } else {
943                         tp   = get_method_param_type(method_type, i);
944                         mode = get_type_mode(tp);
945                         be_abi_call_param_stack(abi, i, mode, 4, 0, 0);
946                 }
947         }
948
949         /* set return registers */
950         n = get_method_n_ress(method_type);
951
952         assert(n <= 2 && "more than two results not supported");
953
954         /* In case of 64bit returns, we will have two 32bit values */
955         if (n == 2) {
956                 tp   = get_method_res_type(method_type, 0);
957                 mode = get_type_mode(tp);
958
959                 assert(!mode_is_float(mode) && "two FP results not supported");
960
961                 tp   = get_method_res_type(method_type, 1);
962                 mode = get_type_mode(tp);
963
964                 assert(!mode_is_float(mode) && "mixed INT, FP results not supported");
965
966                 be_abi_call_res_reg(abi, 0, &arm_gp_regs[REG_R0]);
967                 be_abi_call_res_reg(abi, 1, &arm_gp_regs[REG_R1]);
968         } else if (n == 1) {
969                 const arch_register_t *reg;
970
971                 tp   = get_method_res_type(method_type, 0);
972                 assert(is_atomic_type(tp));
973                 mode = get_type_mode(tp);
974
975                 reg = mode_is_float(mode) ? &arm_fpa_regs[REG_F0] : &arm_gp_regs[REG_R0];
976                 be_abi_call_res_reg(abi, 0, reg);
977         }
978 }
979
980 int arm_to_appear_in_schedule(void *block_env, const ir_node *irn) {
981         (void) block_env;
982         if(!is_arm_irn(irn))
983                 return -1;
984
985         return 1;
986 }
987
988 /**
989  * Initializes the code generator interface.
990  */
991 static const arch_code_generator_if_t *arm_get_code_generator_if(void *self) {
992         (void) self;
993         return &arm_code_gen_if;
994 }
995
996 list_sched_selector_t arm_sched_selector;
997
998 /**
999  * Returns the reg_pressure scheduler with to_appear_in_schedule() over\loaded
1000  */
1001 static const list_sched_selector_t *arm_get_list_sched_selector(const void *self, list_sched_selector_t *selector) {
1002         (void) self;
1003         memcpy(&arm_sched_selector, selector, sizeof(arm_sched_selector));
1004         /* arm_sched_selector.exectime              = arm_sched_exectime; */
1005         arm_sched_selector.to_appear_in_schedule = arm_to_appear_in_schedule;
1006         return &arm_sched_selector;
1007
1008 }
1009
1010 static const ilp_sched_selector_t *arm_get_ilp_sched_selector(const void *self) {
1011         (void) self;
1012         return NULL;
1013 }
1014
1015 /**
1016  * Returns the necessary byte alignment for storing a register of given class.
1017  */
1018 static int arm_get_reg_class_alignment(const void *self, const arch_register_class_t *cls) {
1019         (void) self;
1020         (void) cls;
1021         /* ARM is a 32 bit CPU, no need for other alignment */
1022         return 4;
1023 }
1024
1025 static const be_execution_unit_t ***arm_get_allowed_execution_units(const void *self, const ir_node *irn) {
1026         (void) self;
1027         (void) irn;
1028         /* TODO */
1029         panic("Unimplemented arm_get_allowed_execution_units()");
1030 }
1031
1032 static const be_machine_t *arm_get_machine(const void *self) {
1033         (void) self;
1034         /* TODO */
1035         panic("Unimplemented arm_get_machine()");
1036 }
1037
1038 /**
1039  * Return irp irgs in the desired order.
1040  */
1041 static ir_graph **arm_get_irg_list(const void *self, ir_graph ***irg_list) {
1042         (void) self;
1043         (void) irg_list;
1044         return NULL;
1045 }
1046
1047 /**
1048  * Allows or disallows the creation of Psi nodes for the given Phi nodes.
1049  * @return 1 if allowed, 0 otherwise
1050  */
1051 static int arm_is_psi_allowed(ir_node *sel, ir_node *phi_list, int i, int j) {
1052         ir_node *cmp, *cmp_a, *phi;
1053         ir_mode *mode;
1054
1055
1056         /* currently Psi support is not implemented */
1057         return 0;
1058
1059 /* we don't want long long Psi */
1060 #define IS_BAD_PSI_MODE(mode) (!mode_is_float(mode) && get_mode_size_bits(mode) > 32)
1061
1062         if (get_irn_mode(sel) != mode_b)
1063                 return 0;
1064
1065         cmp   = get_Proj_pred(sel);
1066         cmp_a = get_Cmp_left(cmp);
1067         mode  = get_irn_mode(cmp_a);
1068
1069         if (IS_BAD_PSI_MODE(mode))
1070                 return 0;
1071
1072         /* check the Phi nodes */
1073         for (phi = phi_list; phi; phi = get_irn_link(phi)) {
1074                 ir_node *pred_i = get_irn_n(phi, i);
1075                 ir_node *pred_j = get_irn_n(phi, j);
1076                 ir_mode *mode_i = get_irn_mode(pred_i);
1077                 ir_mode *mode_j = get_irn_mode(pred_j);
1078
1079                 if (IS_BAD_PSI_MODE(mode_i) || IS_BAD_PSI_MODE(mode_j))
1080                         return 0;
1081         }
1082
1083 #undef IS_BAD_PSI_MODE
1084
1085         return 1;
1086 }
1087
1088 static asm_constraint_flags_t arm_parse_asm_constraint(const void *self, const char **c)
1089 {
1090         /* asm not supported */
1091         (void) self;
1092         (void) c;
1093         return ASM_CONSTRAINT_FLAG_INVALID;
1094 }
1095
1096 static int arm_is_valid_clobber(const void *self, const char *clobber)
1097 {
1098         (void) self;
1099         (void) clobber;
1100         return 0;
1101 }
1102
1103 /**
1104  * Returns the libFirm configuration parameter for this backend.
1105  */
1106 static const backend_params *arm_get_libfirm_params(void) {
1107         static const ir_settings_if_conv_t ifconv = {
1108                 4,                    /* maxdepth, doesn't matter for Psi-conversion */
1109                 arm_is_psi_allowed   /* allows or disallows Psi creation for given selector */
1110         };
1111         static ir_settings_arch_dep_t ad = {
1112                 1,    /* allow subs */
1113                 1,        /* Muls are fast enough on ARM but ... */
1114                 31,   /* ... one shift would be possible better */
1115                 NULL, /* no evaluator function */
1116                 0,    /* SMUL is needed, only in Arch M */
1117                 0,    /* UMUL is needed, only in Arch M */
1118                 32,   /* SMUL & UMUL available for 32 bit */
1119         };
1120         static backend_params p = {
1121                 1,     /* need dword lowering */
1122                 0,     /* don't support inline assembler yet */
1123                 NULL,  /* will be set later */
1124                 NULL,  /* but yet no creator function */
1125                 NULL,  /* context for create_intrinsic_fkt */
1126                 NULL,  /* ifconv_info will be set below */
1127                 NULL,  /* float arithmetic mode (TODO) */
1128                 0,     /* no trampoline support: size 0 */
1129                 0,     /* no trampoline support: align 0 */
1130                 NULL,  /* no trampoline support: no trampoline builder */
1131                 4      /* alignment of stack parameter */
1132         };
1133
1134         p.dep_param    = &ad;
1135         p.if_conv_info = &ifconv;
1136         return &p;
1137 }
1138
1139 /* fpu set architectures. */
1140 static const lc_opt_enum_int_items_t arm_fpu_items[] = {
1141         { "softfloat", ARM_FPU_ARCH_SOFTFLOAT },
1142         { "fpe",       ARM_FPU_ARCH_FPE },
1143         { "fpa",       ARM_FPU_ARCH_FPA },
1144         { "vfp1xd",    ARM_FPU_ARCH_VFP_V1xD },
1145         { "vfp1",      ARM_FPU_ARCH_VFP_V1 },
1146         { "vfp2",      ARM_FPU_ARCH_VFP_V2 },
1147         { NULL,        0 }
1148 };
1149
1150 static lc_opt_enum_int_var_t arch_fpu_var = {
1151         &arm_isa_template.fpu_arch, arm_fpu_items
1152 };
1153
1154 static const lc_opt_table_entry_t arm_options[] = {
1155         LC_OPT_ENT_ENUM_INT("fpunit",    "select the floating point unit", &arch_fpu_var),
1156         LC_OPT_ENT_BOOL("gen_reg_names", "use generic register names", &arm_isa_template.gen_reg_names),
1157         LC_OPT_LAST
1158 };
1159
1160 const arch_isa_if_t arm_isa_if = {
1161         arm_init,
1162         arm_done,
1163         NULL,  /* handle_intrinsics */
1164         arm_get_n_reg_class,
1165         arm_get_reg_class,
1166         arm_get_reg_class_for_mode,
1167         arm_get_call_abi,
1168         arm_get_code_generator_if,
1169         arm_get_list_sched_selector,
1170         arm_get_ilp_sched_selector,
1171         arm_get_reg_class_alignment,
1172         arm_get_libfirm_params,
1173         arm_get_allowed_execution_units,
1174         arm_get_machine,
1175         arm_get_irg_list,
1176         NULL,               /* mark remat */
1177         arm_parse_asm_constraint,
1178         arm_is_valid_clobber
1179 };
1180
1181 void be_init_arch_arm(void)
1182 {
1183         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
1184         lc_opt_entry_t *arm_grp = lc_opt_get_grp(be_grp, "arm");
1185
1186         lc_opt_add_table(arm_grp, arm_options);
1187
1188         be_register_isa_if("arm", &arm_isa_if);
1189
1190         arm_init_transform();
1191         arm_init_emitter();
1192 }
1193
1194 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_arch_arm);