sparc: Restore accidentally deleted assert.
[libfirm] / ir / be / sparc / sparc_emitter.c
1 /*
2  * Copyright (C) 1995-2010 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   emit assembler for a backend graph
23  * @author  Hannes Rapp, Matthias Braun
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include <limits.h>
29
30 #include "bitfiddle.h"
31 #include "xmalloc.h"
32 #include "tv.h"
33 #include "iredges.h"
34 #include "debug.h"
35 #include "irgwalk.h"
36 #include "irprintf.h"
37 #include "irop_t.h"
38 #include "irargs_t.h"
39 #include "irprog.h"
40 #include "irargs_t.h"
41 #include "error.h"
42 #include "raw_bitset.h"
43 #include "dbginfo.h"
44 #include "heights.h"
45
46 #include "besched.h"
47 #include "beblocksched.h"
48 #include "beirg.h"
49 #include "begnuas.h"
50 #include "be_dbgout.h"
51 #include "benode.h"
52 #include "bestack.h"
53
54 #include "sparc_emitter.h"
55 #include "gen_sparc_emitter.h"
56 #include "sparc_nodes_attr.h"
57 #include "sparc_new_nodes.h"
58 #include "gen_sparc_regalloc_if.h"
59
60 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
61
62 static ir_heights_t  *heights;
63 static const ir_node *delay_slot_filler; /**< this node has been choosen to fill
64                                               the next delay slot */
65
66 static void sparc_emit_node(const ir_node *node);
67
68 void sparc_emit_immediate(const ir_node *node)
69 {
70         const sparc_attr_t *attr   = get_sparc_attr_const(node);
71         ir_entity          *entity = attr->immediate_value_entity;
72
73         if (entity == NULL) {
74                 int32_t value = attr->immediate_value;
75                 assert(sparc_is_value_imm_encodeable(value));
76                 be_emit_irprintf("%d", value);
77         } else {
78                 if (get_entity_owner(entity) == get_tls_type()) {
79                         be_emit_cstring("%tle_lox10(");
80                 } else {
81                         be_emit_cstring("%lo(");
82                 }
83                 be_gas_emit_entity(entity);
84                 if (attr->immediate_value != 0) {
85                         be_emit_irprintf("%+d", attr->immediate_value);
86                 }
87                 be_emit_char(')');
88         }
89 }
90
91 void sparc_emit_high_immediate(const ir_node *node)
92 {
93         const sparc_attr_t *attr   = get_sparc_attr_const(node);
94         ir_entity          *entity = attr->immediate_value_entity;
95
96         if (entity == NULL) {
97                 uint32_t value = (uint32_t) attr->immediate_value;
98                 be_emit_irprintf("%%hi(0x%X)", value);
99         } else {
100                 if (get_entity_owner(entity) == get_tls_type()) {
101                         be_emit_cstring("%tle_hix22(");
102                 } else {
103                         be_emit_cstring("%hi(");
104                 }
105                 be_gas_emit_entity(entity);
106                 if (attr->immediate_value != 0) {
107                         be_emit_irprintf("%+d", attr->immediate_value);
108                 }
109                 be_emit_char(')');
110         }
111 }
112
113 void sparc_emit_source_register(const ir_node *node, int pos)
114 {
115         const arch_register_t *reg = arch_get_irn_register_in(node, pos);
116         be_emit_char('%');
117         be_emit_string(arch_register_get_name(reg));
118 }
119
120 void sparc_emit_dest_register(const ir_node *node, int pos)
121 {
122         const arch_register_t *reg = arch_get_irn_register_out(node, pos);
123         be_emit_char('%');
124         be_emit_string(arch_register_get_name(reg));
125 }
126
127 /**
128  * Emits either a imm or register depending on arity of node
129  * @param node
130  * @param register no (-1 if no register)
131  */
132 void sparc_emit_reg_or_imm(const ir_node *node, int pos)
133 {
134         if (arch_get_irn_flags(node) & ((arch_irn_flags_t)sparc_arch_irn_flag_immediate_form)) {
135                 // we have a imm input
136                 sparc_emit_immediate(node);
137         } else {
138                 // we have reg input
139                 sparc_emit_source_register(node, pos);
140         }
141 }
142
143 /**
144  * emit SP offset
145  */
146 void sparc_emit_offset(const ir_node *node, int offset_node_pos)
147 {
148         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
149
150         if (attr->is_reg_reg) {
151                 assert(!attr->is_frame_entity);
152                 assert(attr->base.immediate_value == 0);
153                 assert(attr->base.immediate_value_entity == NULL);
154                 be_emit_char('+');
155                 sparc_emit_source_register(node, offset_node_pos);
156         } else if (attr->is_frame_entity) {
157                 int32_t offset = attr->base.immediate_value;
158                 if (offset != 0) {
159                         assert(sparc_is_value_imm_encodeable(offset));
160                         be_emit_irprintf("%+ld", offset);
161                 }
162         } else if (attr->base.immediate_value != 0
163                         || attr->base.immediate_value_entity != NULL) {
164                 be_emit_char('+');
165                 sparc_emit_immediate(node);
166         }
167 }
168
169 void sparc_emit_source_reg_and_offset(const ir_node *node, int regpos,
170                                       int offpos)
171 {
172         const arch_register_t *reg = arch_get_irn_register_in(node, regpos);
173         const sparc_load_store_attr_t *attr;
174
175         if (reg == &sparc_registers[REG_SP]) {
176                 attr = get_sparc_load_store_attr_const(node);
177                 if (!attr->is_reg_reg
178                     && attr->base.immediate_value < SPARC_MIN_STACKSIZE) {
179
180                         ir_fprintf(stderr, "warning: emitting stack pointer relative load/store with offset < %d\n", SPARC_MIN_STACKSIZE);
181                 }
182         }
183
184         sparc_emit_source_register(node, regpos);
185         sparc_emit_offset(node, offpos);
186 }
187
188 void sparc_emit_float_load_store_mode(const ir_node *node)
189 {
190         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
191         ir_mode *mode = attr->load_store_mode;
192         int      bits = get_mode_size_bits(mode);
193
194         assert(mode_is_float(mode));
195
196         switch (bits) {
197         case 32:  return;
198         case 64:  be_emit_char('d'); return;
199         case 128: be_emit_char('q'); return;
200         }
201         panic("invalid float load/store mode %+F", mode);
202 }
203
204 /**
205  *  Emit load mode char
206  */
207 void sparc_emit_load_mode(const ir_node *node)
208 {
209         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
210         ir_mode *mode      = attr->load_store_mode;
211         int      bits      = get_mode_size_bits(mode);
212         bool     is_signed = mode_is_signed(mode);
213
214         if (bits == 16) {
215                 be_emit_string(is_signed ? "sh" : "uh");
216         } else if (bits == 8) {
217                 be_emit_string(is_signed ? "sb" : "ub");
218         } else if (bits == 64) {
219                 be_emit_char('d');
220         } else {
221                 assert(bits == 32);
222         }
223 }
224
225 /**
226  * Emit store mode char
227  */
228 void sparc_emit_store_mode(const ir_node *node)
229 {
230         const sparc_load_store_attr_t *attr = get_sparc_load_store_attr_const(node);
231         ir_mode *mode      = attr->load_store_mode;
232         int      bits      = get_mode_size_bits(mode);
233
234         if (bits == 16) {
235                 be_emit_string("h");
236         } else if (bits == 8) {
237                 be_emit_string("b");
238         } else if (bits == 64) {
239                 be_emit_char('d');
240         } else {
241                 assert(bits == 32);
242         }
243 }
244
245 static void emit_fp_suffix(const ir_mode *mode)
246 {
247         unsigned bits = get_mode_size_bits(mode);
248         assert(mode_is_float(mode));
249
250         if (bits == 32) {
251                 be_emit_char('s');
252         } else if (bits == 64) {
253                 be_emit_char('d');
254         } else if (bits == 128) {
255                 be_emit_char('q');
256         } else {
257                 panic("invalid FP mode");
258         }
259 }
260
261 void sparc_emit_fp_conv_source(const ir_node *node)
262 {
263         const sparc_fp_conv_attr_t *attr = get_sparc_fp_conv_attr_const(node);
264         emit_fp_suffix(attr->src_mode);
265 }
266
267 void sparc_emit_fp_conv_destination(const ir_node *node)
268 {
269         const sparc_fp_conv_attr_t *attr = get_sparc_fp_conv_attr_const(node);
270         emit_fp_suffix(attr->dest_mode);
271 }
272
273 /**
274  * emits the FP mode suffix char
275  */
276 void sparc_emit_fp_mode_suffix(const ir_node *node)
277 {
278         const sparc_fp_attr_t *attr = get_sparc_fp_attr_const(node);
279         emit_fp_suffix(attr->fp_mode);
280 }
281
282 static ir_node *get_jump_target(const ir_node *jump)
283 {
284         return (ir_node*)get_irn_link(jump);
285 }
286
287 /**
288  * Returns the target label for a control flow node.
289  */
290 static void sparc_emit_cfop_target(const ir_node *node)
291 {
292         ir_node *block = get_jump_target(node);
293         be_gas_emit_block_name(block);
294 }
295
296 static int get_sparc_Call_dest_addr_pos(const ir_node *node)
297 {
298         return get_irn_arity(node)-1;
299 }
300
301 static bool ba_is_fallthrough(const ir_node *node)
302 {
303         ir_node *block      = get_nodes_block(node);
304         ir_node *next_block = (ir_node*)get_irn_link(block);
305         return get_irn_link(node) == next_block;
306 }
307
308 static bool is_no_instruction(const ir_node *node)
309 {
310         /* copies are nops if src_reg == dest_reg */
311         if (be_is_Copy(node) || be_is_CopyKeep(node)) {
312                 const arch_register_t *src_reg  = arch_get_irn_register_in(node, 0);
313                 const arch_register_t *dest_reg = arch_get_irn_register_out(node, 0);
314
315                 if (src_reg == dest_reg)
316                         return true;
317         }
318         if (be_is_IncSP(node) && be_get_IncSP_offset(node) == 0)
319                 return true;
320         /* Ba is not emitted if it is a simple fallthrough */
321         if (is_sparc_Ba(node) && ba_is_fallthrough(node))
322                 return true;
323
324         return be_is_Keep(node) || be_is_Start(node) || is_Phi(node);
325 }
326
327 static bool has_delay_slot(const ir_node *node)
328 {
329         if (is_sparc_Ba(node)) {
330                 return !ba_is_fallthrough(node);
331         }
332
333         return arch_get_irn_flags(node) & sparc_arch_irn_flag_has_delay_slot;
334 }
335
336 /** returns true if the emitter for this sparc node can produce more than one
337  * actual sparc instruction.
338  * Usually it is a bad sign if we have to add instructions here. We should
339  * rather try to get them lowered down. So we can actually put them into
340  * delay slots and make them more accessible to the scheduler.
341  */
342 static bool emits_multiple_instructions(const ir_node *node)
343 {
344         if (has_delay_slot(node))
345                 return true;
346
347         if (is_sparc_Call(node)) {
348                 return arch_get_irn_flags(node) & sparc_arch_irn_flag_aggregate_return;
349         }
350
351         return is_sparc_SMulh(node) || is_sparc_UMulh(node)
352                 || is_sparc_SDiv(node) || is_sparc_UDiv(node)
353                 || be_is_MemPerm(node) || be_is_Perm(node);
354 }
355
356 /**
357  * search for an instruction that can fill the delay slot of @p node
358  */
359 static const ir_node *pick_delay_slot_for(const ir_node *node)
360 {
361         const ir_node *check      = node;
362         const ir_node *schedpoint = node;
363         unsigned       tries      = 0;
364         /* currently we don't track which registers are still alive, so we can't
365          * pick any other instructions other than the one directly preceding */
366         static const unsigned PICK_DELAY_SLOT_MAX_DISTANCE = 1;
367
368         assert(has_delay_slot(node));
369
370         if (is_sparc_Call(node)) {
371                 const sparc_attr_t *attr   = get_sparc_attr_const(node);
372                 ir_entity          *entity = attr->immediate_value_entity;
373                 if (entity != NULL) {
374                         check = NULL; /* pick any instruction, dependencies on Call
375                                          don't matter */
376                 } else {
377                         /* we only need to check the value for the call destination */
378                         check = get_irn_n(node, get_sparc_Call_dest_addr_pos(node));
379                 }
380
381                 /* the Call also destroys the value of %o7, but since this is currently
382                  * marked as ignore register in the backend, it should never be used by
383                  * the instruction in the delay slot. */
384         } else if (is_sparc_Return(node)) {
385                 /* we only have to check the jump destination value */
386                 int arity = get_irn_arity(node);
387                 int i;
388
389                 check = NULL;
390                 for (i = 0; i < arity; ++i) {
391                         ir_node               *in  = get_irn_n(node, i);
392                         const arch_register_t *reg = arch_get_irn_register(in);
393                         if (reg == &sparc_registers[REG_O7]) {
394                                 check = skip_Proj(in);
395                                 break;
396                         }
397                 }
398         } else {
399                 check = node;
400         }
401
402         while (sched_has_prev(schedpoint)) {
403                 schedpoint = sched_prev(schedpoint);
404
405                 if (has_delay_slot(schedpoint))
406                         break;
407
408                 /* skip things which don't really result in instructions */
409                 if (is_no_instruction(schedpoint))
410                         continue;
411
412                 if (tries++ >= PICK_DELAY_SLOT_MAX_DISTANCE)
413                         break;
414
415                 if (emits_multiple_instructions(schedpoint))
416                         continue;
417
418                 /* if check and schedpoint are not in the same block, give up. */
419                 if (check != NULL
420                                 && get_nodes_block(check) != get_nodes_block(schedpoint))
421                         break;
422
423                 /* allowed for delayslot: any instruction which is not necessary to
424                  * compute an input to the branch. */
425                 if (check != NULL
426                                 && heights_reachable_in_block(heights, check, schedpoint))
427                         continue;
428
429                 /* found something */
430                 return schedpoint;
431         }
432
433         return NULL;
434 }
435
436 /**
437  * Emits code for stack space management
438  */
439 static void emit_be_IncSP(const ir_node *irn)
440 {
441         int offset = be_get_IncSP_offset(irn);
442
443         if (offset == 0)
444                 return;
445
446         /* SPARC stack grows downwards */
447         if (offset < 0) {
448                 be_emit_cstring("\tsub ");
449                 offset = -offset;
450         } else {
451                 be_emit_cstring("\tadd ");
452         }
453
454         sparc_emit_source_register(irn, 0);
455         be_emit_irprintf(", %d", -offset);
456         be_emit_cstring(", ");
457         sparc_emit_dest_register(irn, 0);
458         be_emit_finish_line_gas(irn);
459 }
460
461 /**
462  * emits code for mulh
463  */
464 static void emit_sparc_Mulh(const ir_node *irn)
465 {
466         be_emit_cstring("\t");
467         if (is_sparc_UMulh(irn)) {
468                 be_emit_char('u');
469         } else {
470                 assert(is_sparc_SMulh(irn));
471                 be_emit_char('s');
472         }
473         be_emit_cstring("mul ");
474
475         sparc_emit_source_register(irn, 0);
476         be_emit_cstring(", ");
477         sparc_emit_reg_or_imm(irn, 1);
478         be_emit_cstring(", ");
479         sparc_emit_dest_register(irn, 0);
480         be_emit_finish_line_gas(irn);
481
482         // our result is in the y register now
483         // we just copy it to the assigned target reg
484         be_emit_cstring("\tmov %y, ");
485         sparc_emit_dest_register(irn, 0);
486         be_emit_finish_line_gas(irn);
487 }
488
489 static void fill_delay_slot(void)
490 {
491         if (delay_slot_filler != NULL) {
492                 sparc_emit_node(delay_slot_filler);
493                 delay_slot_filler = NULL;
494         } else {
495                 be_emit_cstring("\tnop\n");
496                 be_emit_write_line();
497         }
498 }
499
500 static void emit_sparc_Div(const ir_node *node, bool is_signed)
501 {
502         /* can we get the delay count of the wr instruction somewhere? */
503         unsigned wry_delay_count = 3;
504         unsigned i;
505
506         be_emit_cstring("\twr ");
507         sparc_emit_source_register(node, 0);
508         be_emit_cstring(", 0, %y");
509         be_emit_finish_line_gas(node);
510
511         for (i = 0; i < wry_delay_count; ++i) {
512                 fill_delay_slot();
513         }
514
515         be_emit_irprintf("\t%s ", is_signed ? "sdiv" : "udiv");
516         sparc_emit_source_register(node, 1);
517         be_emit_cstring(", ");
518         sparc_emit_reg_or_imm(node, 2);
519         be_emit_cstring(", ");
520         sparc_emit_dest_register(node, 0);
521         be_emit_finish_line_gas(node);
522 }
523
524 static void emit_sparc_SDiv(const ir_node *node)
525 {
526         emit_sparc_Div(node, true);
527 }
528
529 static void emit_sparc_UDiv(const ir_node *node)
530 {
531         emit_sparc_Div(node, false);
532 }
533
534 /**
535  * Emits code for Call node
536  */
537 static void emit_sparc_Call(const ir_node *node)
538 {
539         const sparc_attr_t *attr   = get_sparc_attr_const(node);
540         ir_entity          *entity = attr->immediate_value_entity;
541
542         be_emit_cstring("\tcall ");
543         if (entity != NULL) {
544             be_gas_emit_entity(entity);
545             if (attr->immediate_value != 0) {
546                         be_emit_irprintf("%+d", attr->immediate_value);
547                 }
548                 be_emit_cstring(", 0");
549         } else {
550                 int dest_addr = get_sparc_Call_dest_addr_pos(node);
551                 sparc_emit_source_register(node, dest_addr);
552         }
553         be_emit_finish_line_gas(node);
554
555         fill_delay_slot();
556
557         if (arch_get_irn_flags(node) & sparc_arch_irn_flag_aggregate_return) {
558                 be_emit_cstring("\tunimp 8\n");
559                 be_emit_write_line();
560         }
561 }
562
563 /**
564  * Emit code for Perm node
565  */
566 static void emit_be_Perm(const ir_node *irn)
567 {
568         be_emit_cstring("\txor ");
569         sparc_emit_source_register(irn, 1);
570         be_emit_cstring(", ");
571         sparc_emit_source_register(irn, 0);
572         be_emit_cstring(", ");
573         sparc_emit_source_register(irn, 0);
574         be_emit_finish_line_gas(NULL);
575
576         be_emit_cstring("\txor ");
577         sparc_emit_source_register(irn, 1);
578         be_emit_cstring(", ");
579         sparc_emit_source_register(irn, 0);
580         be_emit_cstring(", ");
581         sparc_emit_source_register(irn, 1);
582         be_emit_finish_line_gas(NULL);
583
584         be_emit_cstring("\txor ");
585         sparc_emit_source_register(irn, 1);
586         be_emit_cstring(", ");
587         sparc_emit_source_register(irn, 0);
588         be_emit_cstring(", ");
589         sparc_emit_source_register(irn, 0);
590         be_emit_finish_line_gas(irn);
591 }
592
593 /* The stack pointer must always be SPARC_STACK_ALIGNMENT bytes aligned, so get
594  * the next bigger integer that's evenly divisible by it. */
595 static unsigned get_aligned_sp_change(const unsigned num_regs)
596 {
597         const unsigned bytes = num_regs * SPARC_REGISTER_SIZE;
598         return round_up2(bytes, SPARC_STACK_ALIGNMENT);
599 }
600
601 /* Spill register l0 or both l0 and l1, depending on n_spilled and n_to_spill.*/
602 static void memperm_emit_spill_registers(const ir_node *node, int n_spilled,
603                                          int n_to_spill)
604 {
605         assert(n_spilled < n_to_spill);
606
607         if (n_spilled == 0) {
608                 /* We always reserve stack space for two registers because during copy
609                  * processing we don't know yet if we also need to handle a cycle which
610                  * needs two registers.  More complicated code in emit_MemPerm would
611                  * prevent wasting SPARC_REGISTER_SIZE bytes of stack space but
612                  * it is not worth the worse readability of emit_MemPerm. */
613
614                 /* Keep stack pointer aligned. */
615                 unsigned sp_change = get_aligned_sp_change(2);
616                 be_emit_irprintf("\tsub %%sp, %u, %%sp", sp_change);
617                 be_emit_finish_line_gas(node);
618
619                 /* Spill register l0. */
620                 be_emit_irprintf("\tst %%l0, [%%sp%+d]", SPARC_MIN_STACKSIZE);
621                 be_emit_finish_line_gas(node);
622         }
623
624         if (n_to_spill == 2) {
625                 /* Spill register l1. */
626                 be_emit_irprintf("\tst %%l1, [%%sp%+d]", SPARC_MIN_STACKSIZE + SPARC_REGISTER_SIZE);
627                 be_emit_finish_line_gas(node);
628         }
629 }
630
631 /* Restore register l0 or both l0 and l1, depending on n_spilled. */
632 static void memperm_emit_restore_registers(const ir_node *node, int n_spilled)
633 {
634         unsigned sp_change;
635
636         if (n_spilled == 2) {
637                 /* Restore register l1. */
638                 be_emit_irprintf("\tld [%%sp%+d], %%l1", SPARC_MIN_STACKSIZE + SPARC_REGISTER_SIZE);
639                 be_emit_finish_line_gas(node);
640         }
641
642         /* Restore register l0. */
643         be_emit_irprintf("\tld [%%sp%+d], %%l0", SPARC_MIN_STACKSIZE);
644         be_emit_finish_line_gas(node);
645
646         /* Restore stack pointer. */
647         sp_change = get_aligned_sp_change(2);
648         be_emit_irprintf("\tadd %%sp, %u, %%sp", sp_change);
649         be_emit_finish_line_gas(node);
650 }
651
652 /* Emit code to copy in_ent to out_ent.  Only uses l0. */
653 static void memperm_emit_copy(const ir_node *node, ir_entity *in_ent,
654                               ir_entity *out_ent)
655 {
656         ir_graph          *irg     = get_irn_irg(node);
657         be_stack_layout_t *layout  = be_get_irg_stack_layout(irg);
658         int                off_in  = be_get_stack_entity_offset(layout, in_ent, 0);
659         int                off_out = be_get_stack_entity_offset(layout, out_ent, 0);
660
661         /* Load from input entity. */
662         be_emit_irprintf("\tld [%%fp%+d], %%l0", off_in);
663         be_emit_finish_line_gas(node);
664
665         /* Store to output entity. */
666         be_emit_irprintf("\tst %%l0, [%%fp%+d]", off_out);
667         be_emit_finish_line_gas(node);
668 }
669
670 /* Emit code to swap ent1 and ent2.  Uses l0 and l1. */
671 static void memperm_emit_swap(const ir_node *node, ir_entity *ent1,
672                               ir_entity *ent2)
673 {
674         ir_graph          *irg     = get_irn_irg(node);
675         be_stack_layout_t *layout  = be_get_irg_stack_layout(irg);
676         int                off1    = be_get_stack_entity_offset(layout, ent1, 0);
677         int                off2    = be_get_stack_entity_offset(layout, ent2, 0);
678
679         /* Load from first input entity. */
680         be_emit_irprintf("\tld [%%fp%+d], %%l0", off1);
681         be_emit_finish_line_gas(node);
682
683         /* Load from second input entity. */
684         be_emit_irprintf("\tld [%%fp%+d], %%l1", off2);
685         be_emit_finish_line_gas(node);
686
687         /* Store first value to second output entity. */
688         be_emit_irprintf("\tst %%l0, [%%fp%+d]", off2);
689         be_emit_finish_line_gas(node);
690
691         /* Store second value to first output entity. */
692         be_emit_irprintf("\tst %%l1, [%%fp%+d]", off1);
693         be_emit_finish_line_gas(node);
694 }
695
696 /* Find the index of ent in ents or return -1 if not found. */
697 static int get_index(ir_entity **ents, int n, ir_entity *ent)
698 {
699         int i;
700
701         for (i = 0; i < n; ++i)
702                 if (ents[i] == ent)
703                         return i;
704
705         return -1;
706 }
707
708 /*
709  * Emit code for a MemPerm node.
710  *
711  * Analyze MemPerm for copy chains and cyclic swaps and resolve them using
712  * loads and stores.
713  * This function is conceptually very similar to permute_values in
714  * beprefalloc.c.
715  */
716 static void emit_be_MemPerm(const ir_node *node)
717 {
718         int         memperm_arity = be_get_MemPerm_entity_arity(node);
719         /* Upper limit for the number of participating entities is twice the
720          * arity, e.g., for a simple copying MemPerm node with one input/output. */
721         int         max_size      = 2 * memperm_arity;
722         ir_entity **entities      = ALLOCANZ(ir_entity *, max_size);
723         /* sourceof contains the input entity for each entity.  If an entity is
724          * never used as an output, its entry in sourceof is a fix point. */
725         int        *sourceof      = ALLOCANZ(int,         max_size);
726         /* n_users counts how many output entities use this entity as their input.*/
727         int        *n_users       = ALLOCANZ(int,         max_size);
728         /* n_spilled records the number of spilled registers, either 1 or 2. */
729         int         n_spilled     = 0;
730         int         i, n, oidx;
731
732         /* This implementation currently only works with frame pointers. */
733         ir_graph          *irg    = get_irn_irg(node);
734         be_stack_layout_t *layout = be_get_irg_stack_layout(irg);
735         assert(!layout->sp_relative && "MemPerms currently do not work without frame pointers");
736
737         for (i = 0; i < max_size; ++i) {
738                 sourceof[i] = i;
739         }
740
741         for (i = n = 0; i < memperm_arity; ++i) {
742                 ir_entity *out  = be_get_MemPerm_out_entity(node, i);
743                 ir_entity *in   = be_get_MemPerm_in_entity(node, i);
744                 int              oidx; /* Out index */
745                 int              iidx; /* In index */
746
747                 /* Insert into entities to be able to operate on unique indices. */
748                 if (get_index(entities, n, out) == -1)
749                         entities[n++] = out;
750                 if (get_index(entities, n, in) == -1)
751                         entities[n++] = in;
752
753                 oidx = get_index(entities, n, out);
754                 iidx = get_index(entities, n, in);
755
756                 sourceof[oidx] = iidx; /* Remember the source. */
757                 ++n_users[iidx]; /* Increment number of users of this entity. */
758         }
759
760         /* First do all the copies. */
761         for (oidx = 0; oidx < n; /* empty */) {
762                 int iidx = sourceof[oidx];
763
764                 /* Nothing to do for fix points.
765                  * Also, if entities[oidx] is used as an input by another copy, we
766                  * can't overwrite entities[oidx] yet.*/
767                 if (iidx == oidx || n_users[oidx] > 0) {
768                         ++oidx;
769                         continue;
770                 }
771
772                 /* We found the end of a 'chain', so do the copy. */
773                 if (n_spilled == 0) {
774                         memperm_emit_spill_registers(node, n_spilled, /*n_to_spill=*/1);
775                         n_spilled = 1;
776                 }
777                 memperm_emit_copy(node, entities[iidx], entities[oidx]);
778
779                 /* Mark as done. */
780                 sourceof[oidx] = oidx;
781
782                 assert(n_users[iidx] > 0);
783                 /* Decrementing the number of users might enable us to do another
784                  * copy. */
785                 --n_users[iidx];
786
787                 if (iidx < oidx && n_users[iidx] == 0) {
788                         oidx = iidx;
789                 } else {
790                         ++oidx;
791                 }
792         }
793
794         /* The rest are cycles. */
795         for (oidx = 0; oidx < n; /* empty */) {
796                 int iidx = sourceof[oidx];
797                 int tidx;
798
799                 /* Nothing to do for fix points. */
800                 if (iidx == oidx) {
801                         ++oidx;
802                         continue;
803                 }
804
805                 assert(n_users[iidx] == 1);
806
807                 /* Swap the two values to resolve the cycle. */
808                 if (n_spilled < 2) {
809                         memperm_emit_spill_registers(node, n_spilled, /*n_to_spill=*/2);
810                         n_spilled = 2;
811                 }
812                 memperm_emit_swap(node, entities[iidx], entities[oidx]);
813
814                 tidx = sourceof[iidx];
815                 /* Mark as done. */
816                 sourceof[iidx] = iidx;
817
818                 /* The source of oidx is now the old source of iidx, because we swapped
819                  * the two entities. */
820                 sourceof[oidx] = tidx;
821         }
822
823 #ifdef DEBUG_libfirm
824         /* Only fix points should remain. */
825         for (i = 0; i < max_size; ++i) {
826                 assert(sourceof[i] == i);
827         }
828 #endif
829
830         assert(n_spilled > 0 && "Useless MemPerm node");
831
832         memperm_emit_restore_registers(node, n_spilled);
833 }
834
835 static void emit_sparc_Return(const ir_node *node)
836 {
837         ir_graph  *irg    = get_irn_irg(node);
838         ir_entity *entity = get_irg_entity(irg);
839         ir_type   *type   = get_entity_type(entity);
840
841         const char *destreg = "%o7";
842
843         /* hack: we don't explicitely model register changes because of the
844          * restore node. So we have to do it manually here */
845         if (delay_slot_filler != NULL &&
846                         (is_sparc_Restore(delay_slot_filler)
847                          || is_sparc_RestoreZero(delay_slot_filler))) {
848                 destreg = "%i7";
849         }
850         be_emit_cstring("\tjmp ");
851         be_emit_string(destreg);
852         if (get_method_calling_convention(type) & cc_compound_ret) {
853                 be_emit_cstring("+12");
854         } else {
855                 be_emit_cstring("+8");
856         }
857         be_emit_finish_line_gas(node);
858         fill_delay_slot();
859 }
860
861 static void emit_sparc_FrameAddr(const ir_node *node)
862 {
863         const sparc_attr_t *attr   = get_sparc_attr_const(node);
864         int32_t             offset = attr->immediate_value;
865
866         if (offset < 0) {
867                 be_emit_cstring("\tadd ");
868                 sparc_emit_source_register(node, 0);
869                 be_emit_cstring(", ");
870                 assert(sparc_is_value_imm_encodeable(offset));
871                 be_emit_irprintf("%ld", offset);
872         } else {
873                 be_emit_cstring("\tsub ");
874                 sparc_emit_source_register(node, 0);
875                 be_emit_cstring(", ");
876                 assert(sparc_is_value_imm_encodeable(-offset));
877                 be_emit_irprintf("%ld", -offset);
878         }
879
880         be_emit_cstring(", ");
881         sparc_emit_dest_register(node, 0);
882         be_emit_finish_line_gas(node);
883 }
884
885 static const char *get_icc_unsigned(ir_relation relation)
886 {
887         switch (relation & (ir_relation_less_equal_greater)) {
888         case ir_relation_false:              return "bn";
889         case ir_relation_equal:              return "be";
890         case ir_relation_less:               return "blu";
891         case ir_relation_less_equal:         return "bleu";
892         case ir_relation_greater:            return "bgu";
893         case ir_relation_greater_equal:      return "bgeu";
894         case ir_relation_less_greater:       return "bne";
895         case ir_relation_less_equal_greater: return "ba";
896         default: panic("Cmp has unsupported relation");
897         }
898 }
899
900 static const char *get_icc_signed(ir_relation relation)
901 {
902         switch (relation & (ir_relation_less_equal_greater)) {
903         case ir_relation_false:              return "bn";
904         case ir_relation_equal:              return "be";
905         case ir_relation_less:               return "bl";
906         case ir_relation_less_equal:         return "ble";
907         case ir_relation_greater:            return "bg";
908         case ir_relation_greater_equal:      return "bge";
909         case ir_relation_less_greater:       return "bne";
910         case ir_relation_less_equal_greater: return "ba";
911         default: panic("Cmp has unsupported relation");
912         }
913 }
914
915 static const char *get_fcc(ir_relation relation)
916 {
917         switch (relation) {
918         case ir_relation_false:                   return "fbn";
919         case ir_relation_equal:                   return "fbe";
920         case ir_relation_less:                    return "fbl";
921         case ir_relation_less_equal:              return "fble";
922         case ir_relation_greater:                 return "fbg";
923         case ir_relation_greater_equal:           return "fbge";
924         case ir_relation_less_greater:            return "fblg";
925         case ir_relation_less_equal_greater:      return "fbo";
926         case ir_relation_unordered:               return "fbu";
927         case ir_relation_unordered_equal:         return "fbue";
928         case ir_relation_unordered_less:          return "fbul";
929         case ir_relation_unordered_less_equal:    return "fbule";
930         case ir_relation_unordered_greater:       return "fbug";
931         case ir_relation_unordered_greater_equal: return "fbuge";
932         case ir_relation_unordered_less_greater:  return "fbne";
933         case ir_relation_true:                    return "fba";
934         }
935         panic("invalid relation");
936 }
937
938 typedef const char* (*get_cc_func)(ir_relation relation);
939
940 static void emit_sparc_branch(const ir_node *node, get_cc_func get_cc)
941 {
942         const sparc_jmp_cond_attr_t *attr = get_sparc_jmp_cond_attr_const(node);
943         ir_relation      relation    = attr->relation;
944         const ir_node   *proj_true   = NULL;
945         const ir_node   *proj_false  = NULL;
946         const ir_edge_t *edge;
947         const ir_node   *block;
948         const ir_node   *next_block;
949
950         foreach_out_edge(node, edge) {
951                 ir_node *proj = get_edge_src_irn(edge);
952                 long nr = get_Proj_proj(proj);
953                 if (nr == pn_Cond_true) {
954                         proj_true = proj;
955                 } else {
956                         proj_false = proj;
957                 }
958         }
959
960         /* for now, the code works for scheduled and non-schedules blocks */
961         block = get_nodes_block(node);
962
963         /* we have a block schedule */
964         next_block = (ir_node*)get_irn_link(block);
965
966         if (get_irn_link(proj_true) == next_block) {
967                 /* exchange both proj's so the second one can be omitted */
968                 const ir_node *t = proj_true;
969
970                 proj_true  = proj_false;
971                 proj_false = t;
972                 relation   = get_negated_relation(relation);
973         }
974
975         /* emit the true proj */
976         be_emit_cstring("\t");
977         be_emit_string(get_cc(relation));
978         be_emit_char(' ');
979         sparc_emit_cfop_target(proj_true);
980         be_emit_finish_line_gas(proj_true);
981
982         fill_delay_slot();
983
984         if (get_irn_link(proj_false) == next_block) {
985                 be_emit_cstring("\t/* fallthrough to ");
986                 sparc_emit_cfop_target(proj_false);
987                 be_emit_cstring(" */");
988                 be_emit_finish_line_gas(proj_false);
989         } else {
990                 be_emit_cstring("\tba ");
991                 sparc_emit_cfop_target(proj_false);
992                 be_emit_finish_line_gas(proj_false);
993                 fill_delay_slot();
994         }
995 }
996
997 static void emit_sparc_Bicc(const ir_node *node)
998 {
999         const sparc_jmp_cond_attr_t *attr = get_sparc_jmp_cond_attr_const(node);
1000         bool             is_unsigned = attr->is_unsigned;
1001         emit_sparc_branch(node, is_unsigned ? get_icc_unsigned : get_icc_signed);
1002 }
1003
1004 static void emit_sparc_fbfcc(const ir_node *node)
1005 {
1006         /* if the flags producing node was immediately in front of us, emit
1007          * a nop */
1008         ir_node *flags = get_irn_n(node, n_sparc_fbfcc_flags);
1009         ir_node *prev  = sched_prev(node);
1010         if (is_Block(prev)) {
1011                 /* TODO: when the flags come from another block, then we have to do
1012                  * more complicated tests to see wether the flag producing node is
1013                  * potentially in front of us (could happen for fallthroughs) */
1014                 panic("TODO: fbfcc flags come from other block");
1015         }
1016         if (skip_Proj(flags) == prev) {
1017                 be_emit_cstring("\tnop\n");
1018         }
1019         emit_sparc_branch(node, get_fcc);
1020 }
1021
1022 static void emit_sparc_Ba(const ir_node *node)
1023 {
1024         if (ba_is_fallthrough(node)) {
1025                 be_emit_cstring("\t/* fallthrough to ");
1026                 sparc_emit_cfop_target(node);
1027                 be_emit_cstring(" */");
1028                 be_emit_finish_line_gas(node);
1029         } else {
1030                 be_emit_cstring("\tba ");
1031                 sparc_emit_cfop_target(node);
1032                 be_emit_finish_line_gas(node);
1033                 fill_delay_slot();
1034         }
1035 }
1036
1037 static void emit_sparc_SwitchJmp(const ir_node *node)
1038 {
1039         const sparc_switch_jmp_attr_t *attr = get_sparc_switch_jmp_attr_const(node);
1040
1041         be_emit_cstring("\tjmp ");
1042         sparc_emit_source_register(node, 0);
1043         be_emit_finish_line_gas(node);
1044         fill_delay_slot();
1045
1046         emit_jump_table(node, attr->default_proj_num, attr->jump_table,
1047                         get_jump_target);
1048 }
1049
1050 static void emit_fmov(const ir_node *node, const arch_register_t *src_reg,
1051                       const arch_register_t *dst_reg)
1052 {
1053         be_emit_cstring("\tfmovs %");
1054         be_emit_string(arch_register_get_name(src_reg));
1055         be_emit_cstring(", %");
1056         be_emit_string(arch_register_get_name(dst_reg));
1057         be_emit_finish_line_gas(node);
1058 }
1059
1060 static const arch_register_t *get_next_fp_reg(const arch_register_t *reg)
1061 {
1062         unsigned idx = reg->global_index;
1063         assert(reg == &sparc_registers[idx]);
1064         idx++;
1065         assert(idx - REG_F0 < N_sparc_fp_REGS);
1066         return &sparc_registers[idx];
1067 }
1068
1069 static void emit_be_Copy(const ir_node *node)
1070 {
1071         ir_mode               *mode    = get_irn_mode(node);
1072         const arch_register_t *src_reg = arch_get_irn_register_in(node, 0);
1073         const arch_register_t *dst_reg = arch_get_irn_register_out(node, 0);
1074
1075         if (src_reg == dst_reg)
1076                 return;
1077
1078         if (mode_is_float(mode)) {
1079                 unsigned bits = get_mode_size_bits(mode);
1080                 int      n    = bits > 32 ? bits > 64 ? 3 : 1 : 0;
1081                 int      i;
1082                 emit_fmov(node, src_reg, dst_reg);
1083                 for (i = 0; i < n; ++i) {
1084                         src_reg = get_next_fp_reg(src_reg);
1085                         dst_reg = get_next_fp_reg(dst_reg);
1086                         emit_fmov(node, src_reg, dst_reg);
1087                 }
1088         } else if (mode_is_data(mode)) {
1089                 be_emit_cstring("\tmov ");
1090                 sparc_emit_source_register(node, 0);
1091                 be_emit_cstring(", ");
1092                 sparc_emit_dest_register(node, 0);
1093                 be_emit_finish_line_gas(node);
1094         } else {
1095                 panic("emit_be_Copy: invalid mode");
1096         }
1097 }
1098
1099 static void emit_nothing(const ir_node *irn)
1100 {
1101         (void) irn;
1102 }
1103
1104 typedef void (*emit_func) (const ir_node *);
1105
1106 static inline void set_emitter(ir_op *op, emit_func sparc_emit_node)
1107 {
1108         op->ops.generic = (op_func)sparc_emit_node;
1109 }
1110
1111 /**
1112  * Enters the emitter functions for handled nodes into the generic
1113  * pointer of an opcode.
1114  */
1115 static void sparc_register_emitters(void)
1116 {
1117         /* first clear the generic function pointer for all ops */
1118         clear_irp_opcodes_generic_func();
1119         /* register all emitter functions defined in spec */
1120         sparc_register_spec_emitters();
1121
1122         /* custom emitter */
1123         set_emitter(op_be_Copy,         emit_be_Copy);
1124         set_emitter(op_be_CopyKeep,     emit_be_Copy);
1125         set_emitter(op_be_IncSP,        emit_be_IncSP);
1126         set_emitter(op_be_MemPerm,      emit_be_MemPerm);
1127         set_emitter(op_be_Perm,         emit_be_Perm);
1128         set_emitter(op_sparc_Ba,        emit_sparc_Ba);
1129         set_emitter(op_sparc_Bicc,      emit_sparc_Bicc);
1130         set_emitter(op_sparc_Call,      emit_sparc_Call);
1131         set_emitter(op_sparc_fbfcc,     emit_sparc_fbfcc);
1132         set_emitter(op_sparc_FrameAddr, emit_sparc_FrameAddr);
1133         set_emitter(op_sparc_SMulh,     emit_sparc_Mulh);
1134         set_emitter(op_sparc_UMulh,     emit_sparc_Mulh);
1135         set_emitter(op_sparc_Return,    emit_sparc_Return);
1136         set_emitter(op_sparc_SDiv,      emit_sparc_SDiv);
1137         set_emitter(op_sparc_SwitchJmp, emit_sparc_SwitchJmp);
1138         set_emitter(op_sparc_UDiv,      emit_sparc_UDiv);
1139
1140         /* no need to emit anything for the following nodes */
1141         set_emitter(op_be_Keep,     emit_nothing);
1142         set_emitter(op_sparc_Start, emit_nothing);
1143         set_emitter(op_Phi,         emit_nothing);
1144 }
1145
1146 /**
1147  * Emits code for a node.
1148  */
1149 static void sparc_emit_node(const ir_node *node)
1150 {
1151         ir_op *op = get_irn_op(node);
1152
1153         if (op->ops.generic) {
1154                 emit_func func = (emit_func) op->ops.generic;
1155                 be_dbg_set_dbg_info(get_irn_dbg_info(node));
1156                 (*func) (node);
1157         } else {
1158                 panic("No emit handler for node %+F (graph %+F)\n", node,
1159                       current_ir_graph);
1160         }
1161 }
1162
1163 static ir_node *find_next_delay_slot(ir_node *from)
1164 {
1165         ir_node *schedpoint = from;
1166         while (!has_delay_slot(schedpoint)) {
1167                 if (!sched_has_next(schedpoint))
1168                         return NULL;
1169                 schedpoint = sched_next(schedpoint);
1170         }
1171         return schedpoint;
1172 }
1173
1174 static bool block_needs_label(const ir_node *block, const ir_node *sched_prev)
1175 {
1176         int n_cfgpreds;
1177
1178         if (has_Block_entity(block))
1179                 return true;
1180
1181         n_cfgpreds = get_Block_n_cfgpreds(block);
1182         if (n_cfgpreds == 0) {
1183                 return false;
1184         } else if (n_cfgpreds > 1) {
1185                 return true;
1186         } else {
1187                 ir_node *cfgpred       = get_Block_cfgpred(block, 0);
1188                 ir_node *cfgpred_block = get_nodes_block(cfgpred);
1189                 if (is_Proj(cfgpred) && is_sparc_SwitchJmp(get_Proj_pred(cfgpred)))
1190                         return true;
1191                 return sched_prev != cfgpred_block || get_irn_link(cfgpred) != block;
1192         }
1193 }
1194
1195 /**
1196  * Walks over the nodes in a block connected by scheduling edges
1197  * and emits code for each node.
1198  */
1199 static void sparc_emit_block(ir_node *block, ir_node *prev)
1200 {
1201         ir_node *node;
1202         ir_node *next_delay_slot;
1203
1204         assert(is_Block(block));
1205
1206         if (block_needs_label(block, prev)) {
1207                 be_gas_emit_block_name(block);
1208                 be_emit_cstring(":\n");
1209                 be_emit_write_line();
1210         }
1211
1212         next_delay_slot = find_next_delay_slot(sched_first(block));
1213         if (next_delay_slot != NULL)
1214                 delay_slot_filler = pick_delay_slot_for(next_delay_slot);
1215
1216         sched_foreach(block, node) {
1217                 if (node == delay_slot_filler) {
1218                         continue;
1219                 }
1220
1221                 sparc_emit_node(node);
1222
1223                 if (node == next_delay_slot) {
1224                         assert(delay_slot_filler == NULL);
1225                         next_delay_slot = find_next_delay_slot(sched_next(node));
1226                         if (next_delay_slot != NULL)
1227                                 delay_slot_filler = pick_delay_slot_for(next_delay_slot);
1228                 }
1229         }
1230 }
1231
1232 /**
1233  * Emits code for function start.
1234  */
1235 static void sparc_emit_func_prolog(ir_graph *irg)
1236 {
1237         ir_entity *ent = get_irg_entity(irg);
1238         be_gas_emit_function_prolog(ent, 4);
1239         be_emit_write_line();
1240 }
1241
1242 /**
1243  * Emits code for function end
1244  */
1245 static void sparc_emit_func_epilog(ir_graph *irg)
1246 {
1247         ir_entity *ent = get_irg_entity(irg);
1248         const char *irg_name = get_entity_ld_name(ent);
1249         be_emit_write_line();
1250         be_emit_irprintf("\t.size  %s, .-%s\n", irg_name, irg_name);
1251         be_emit_cstring("# -- End ");
1252         be_emit_string(irg_name);
1253         be_emit_cstring("\n");
1254         be_emit_write_line();
1255 }
1256
1257 static void sparc_gen_labels(ir_node *block, void *env)
1258 {
1259         ir_node *pred;
1260         int n = get_Block_n_cfgpreds(block);
1261         (void) env;
1262
1263         for (n--; n >= 0; n--) {
1264                 pred = get_Block_cfgpred(block, n);
1265                 set_irn_link(pred, block); // link the pred of a block (which is a jmp)
1266         }
1267 }
1268
1269 void sparc_emit_routine(ir_graph *irg)
1270 {
1271         ir_entity  *entity = get_irg_entity(irg);
1272         ir_node   **block_schedule;
1273         size_t      i;
1274         size_t      n;
1275
1276         heights = heights_new(irg);
1277
1278         /* register all emitter functions */
1279         sparc_register_emitters();
1280         be_dbg_method_begin(entity);
1281
1282         /* create the block schedule. For now, we don't need it earlier. */
1283         block_schedule = be_create_block_schedule(irg);
1284
1285         sparc_emit_func_prolog(irg);
1286         irg_block_walk_graph(irg, sparc_gen_labels, NULL, NULL);
1287
1288         /* inject block scheduling links & emit code of each block */
1289         n = ARR_LEN(block_schedule);
1290         for (i = 0; i < n; ++i) {
1291                 ir_node *block      = block_schedule[i];
1292                 ir_node *next_block = i+1 < n ? block_schedule[i+1] : NULL;
1293                 set_irn_link(block, next_block);
1294         }
1295
1296         for (i = 0; i < n; ++i) {
1297                 ir_node *block = block_schedule[i];
1298                 ir_node *prev  = i>=1 ? block_schedule[i-1] : NULL;
1299                 if (block == get_irg_end_block(irg))
1300                         continue;
1301                 sparc_emit_block(block, prev);
1302         }
1303
1304         /* emit function epilog */
1305         sparc_emit_func_epilog(irg);
1306
1307         heights_free(heights);
1308 }
1309
1310 void sparc_init_emitter(void)
1311 {
1312         FIRM_DBG_REGISTER(dbg, "firm.be.sparc.emit");
1313 }