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