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