Emit the symbol of PIC trampolines.
[libfirm] / ir / be / begnuas.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       Dumps global variables and constants as gas assembler.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @date        04.11.2005
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include "begnuas.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <assert.h>
35
36 #include "obst.h"
37 #include "tv.h"
38 #include "irnode.h"
39 #include "irprog.h"
40 #include "entity_t.h"
41 #include "error.h"
42
43 #include "be_t.h"
44 #include "beemitter.h"
45 #include "be_dbgout.h"
46
47 /** by default, we generate assembler code for the Linux gas */
48 object_file_format_t  be_gas_object_file_format = OBJECT_FILE_FORMAT_ELF;
49 bool                  be_gas_emit_types         = true;
50 char                  be_gas_elf_type_char      = '@';
51
52 static be_gas_section_t current_section = (be_gas_section_t) -1;
53
54 /**
55  * Return the pseudo-instruction to be issued for a section switch
56  * depending on the current flavour.
57  *
58  * @param section  the section to switch to
59  *
60  * @return  the pseudo-instruction
61  */
62 static const char *get_section_name(be_gas_section_t section)
63 {
64         static const char *text[OBJECT_FILE_FORMAT_LAST+1][GAS_SECTION_LAST+1] = {
65                 { /* OBJECT_FILE_FORMAT_ELF */
66                         ".section\t.text",
67                         ".section\t.data",
68                         ".section\t.rodata",
69                         ".section\t.bss",
70                         ".section\t.tbss,\"awT\",@nobits",
71                         ".section\t.ctors,\"aw\",@progbits",
72                         ".section\t.dtors,\"aw\",@progbits",
73                         NULL, /* no cstring section */
74                         NULL,
75                         NULL
76                 },
77                 { /* OBJECT_FILE_FORMAT_COFF */
78                         ".section\t.text",
79                         ".section\t.data",
80                         ".section .rdata,\"dr\"",
81                         ".section\t.bss",
82                         ".section\t.tbss,\"awT\",@nobits",
83                         ".section\t.ctors,\"w\"",
84                         ".section\t.dtors,\"w\"",
85                         NULL,
86                         NULL,
87                         NULL
88                 },
89                 { /* OBJECT_FILE_FORMAT_MACH_O */
90                         ".text",
91                         ".data",
92                         ".const",
93                         ".data",
94                         NULL,             /* TLS is not supported on Mach-O */
95                         ".mod_init_func",
96                         NULL,             /* are there destructors on mach-o? */
97                         ".cstring",
98                         ".section\t__IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5",
99                         ".section\t__IMPORT,__pointers,non_lazy_symbol_pointers"
100                 }
101         };
102
103         assert((int) be_gas_object_file_format >= 0
104                         && be_gas_object_file_format <= OBJECT_FILE_FORMAT_LAST);
105         assert((int) section >= 0 && section <= GAS_SECTION_LAST);
106         return text[be_gas_object_file_format][section];
107 }
108
109 void be_gas_emit_switch_section(be_gas_section_t section)
110 {
111         if (current_section == section)
112                 return;
113
114         be_emit_char('\t');
115         be_emit_string(get_section_name(section));
116         be_emit_char('\n');
117         be_emit_write_line();
118         current_section = section;
119 }
120
121 static void emit_entity_visibility(const ir_entity *entity)
122 {
123         ir_visibility visibility = get_entity_visibility(entity);
124         ir_linkage    linkage    = get_entity_linkage(entity);
125
126         if (visibility != ir_visibility_local) {
127                 be_emit_cstring(".globl ");
128                 be_emit_ident(get_entity_ld_ident(entity));
129                 be_emit_char('\n');
130                 be_emit_write_line();
131         }
132         if (linkage & IR_LINKAGE_WEAK) {
133                 if (! (linkage & IR_LINKAGE_MERGE)) {
134                         panic("Weak symbols only supported in combination with IR_LINKAGE_MERGE on this architecture");
135                 }
136                 be_emit_cstring(".weak ");
137                 be_emit_ident(get_entity_ld_ident(entity));
138                 be_emit_char('\n');
139                 be_emit_write_line();
140         }
141 }
142
143 void be_gas_emit_function_prolog(ir_entity *entity, unsigned po2alignment)
144 {
145         const char *name = get_entity_ld_name(entity);
146
147         be_gas_emit_switch_section(GAS_SECTION_TEXT);
148
149         /* write the begin line (makes the life easier for scripts parsing the
150          * assembler) */
151         be_emit_write_line();
152         be_emit_cstring("# -- Begin  ");
153         be_emit_string(name);
154         be_emit_char('\n');
155         be_emit_write_line();
156
157         if (po2alignment > 0) {
158                 const char *fill_byte = "";
159                 unsigned    maximum_skip = (1 << po2alignment) - 1;
160                 /* gcc fills space between function with 0x90... */
161                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
162                         fill_byte = "0x90";
163                 }
164                 be_emit_cstring("\t.p2align ");
165                 be_emit_irprintf("%u,%s,%u\n", po2alignment, fill_byte, maximum_skip);
166                 be_emit_write_line();
167         }
168         emit_entity_visibility(entity);
169
170         switch (be_gas_object_file_format) {
171         case OBJECT_FILE_FORMAT_ELF:
172                 be_emit_cstring("\t.type\t");
173                 be_emit_string(name);
174                 be_emit_cstring(", ");
175                 be_emit_char(be_gas_elf_type_char);
176                 be_emit_cstring("function\n");
177                 be_emit_write_line();
178                 break;
179         case OBJECT_FILE_FORMAT_COFF:
180                 be_emit_cstring("\t.def\t");
181                 be_emit_string(name);
182                 be_emit_cstring(";");
183                 if (get_entity_visibility(entity) == ir_visibility_local) {
184                         be_emit_cstring("\t.scl\t3;");
185                 } else {
186                         be_emit_cstring("\t.scl\t2;");
187                 }
188                 be_emit_cstring("\t.type\t32;\t.endef\n");
189                 be_emit_write_line();
190                 break;
191         case OBJECT_FILE_FORMAT_MACH_O:
192                 break;
193         }
194         be_emit_string(name);
195         be_emit_cstring(":\n");
196         be_emit_write_line();
197 }
198
199 void be_gas_emit_function_epilog(ir_entity *entity)
200 {
201         const char *name = get_entity_ld_name(entity);
202
203         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF) {
204                 be_emit_cstring("\t.size\t");
205                 be_emit_string(name);
206                 be_emit_cstring(", .-");
207                 be_emit_string(name);
208                 be_emit_char('\n');
209                 be_emit_write_line();
210         }
211
212         be_emit_cstring("# -- End  ");
213         be_emit_string(name);
214         be_emit_char('\n');
215         be_emit_write_line();
216 }
217
218 /**
219  * An environment containing all needed dumper data.
220  * Currently we create the file completely in memory first, then
221  * write it to the disk. This is an artifact from the old C-generating backend
222  * and even there NOT needed. So we might change it in the future.
223  */
224 typedef struct _be_gas_decl_env {
225         be_gas_section_t     section;
226         const be_main_env_t *main_env;
227 } be_gas_decl_env_t;
228
229 /************************************************************************/
230
231 /**
232  * Output a tarval.
233  *
234  * @param tv     the tarval
235  * @param bytes  the width of the tarvals value in bytes
236  */
237 static void dump_arith_tarval(tarval *tv, int bytes)
238 {
239         switch (bytes) {
240         case 1:
241                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
242                 return;
243
244         case 2:
245                 be_emit_irprintf("0x%02x%02x", get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
246                 return;
247
248         case 4:
249                 be_emit_irprintf("0x%02x%02x%02x%02x",
250                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
251                 return;
252
253         case 8:
254                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
255                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6), get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
256                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
257                 return;
258
259         case 12:
260                 /* Beware: Mixed endian output!  One little endian number emitted as
261                  * three longs.  Each long initializer is written in big endian. */
262                 be_emit_irprintf(
263                         "\t.long\t0x%02x%02x%02x%02x\n"
264                         "\t.long\t0x%02x%02x%02x%02x\n"
265                         "\t.long\t0x%02x%02x%02x%02x",
266                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
267                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
268                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
269                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
270                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
271                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
272                 );
273                 return;
274
275         case 16:
276                 be_emit_irprintf(
277                         "\t.long\t0x%02x%02x%02x%02x0x%02x%02x%02x%02x0x%02x%02x%02x%02x0x%02x%02x%02x%02x",
278                         get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 16),
279                         get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12),
280                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
281                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
282                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
283                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
284                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
285                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0)
286                 );
287                 return;
288         }
289
290         panic("Can't dump a tarval with %d bytes", bytes);
291 }
292
293 /**
294  * Return the label prefix for labeled blocks.
295  */
296 const char *be_gas_block_label_prefix(void)
297 {
298         return ".LG";
299 }
300
301 /**
302  * Return the label prefix for labeled instructions.
303  */
304 const char *be_gas_insn_label_prefix(void)
305 {
306         return ".LE";
307 }
308
309 void be_gas_emit_entity(ir_entity *entity)
310 {
311         if (entity->type == firm_code_type) {
312                 ir_label_t label = get_entity_label(entity);
313                 be_emit_string(be_gas_block_label_prefix());
314                 be_emit_irprintf("%lu", label);
315         } else {
316                 be_emit_ident(get_entity_ld_ident(entity));
317         }
318 }
319
320 /**
321  * Return the tarval of an atomic initializer.
322  *
323  * @param init  a node representing the initializer (on the const code irg)
324  *
325  * @return the tarval
326  */
327 static tarval *get_atomic_init_tv(ir_node *init)
328 {
329         for (;;) {
330                 ir_mode *mode = get_irn_mode(init);
331
332                 switch (get_irn_opcode(init)) {
333
334                 case iro_Cast:
335                         init = get_Cast_op(init);
336                         continue;
337
338                 case iro_Conv:
339                         init = get_Conv_op(init);
340                         continue;
341
342                 case iro_Const:
343                         return get_Const_tarval(init);
344
345                 case iro_SymConst:
346                         switch (get_SymConst_kind(init)) {
347                         case symconst_type_size:
348                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
349
350                         case symconst_type_align:
351                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
352
353                         case symconst_ofs_ent:
354                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
355
356                         case symconst_enum_const:
357                                 return get_enumeration_value(get_SymConst_enum(init));
358
359                         default:
360                                 return NULL;
361                         }
362
363                 default:
364                         return NULL;
365                 }
366         }
367 }
368
369 /**
370  * Dump an atomic value.
371  *
372  * @param env   the gas output environment
373  * @param init  a node representing the atomic value (on the const code irg)
374  */
375 static void do_dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
376 {
377         ir_mode *mode = get_irn_mode(init);
378         int bytes     = get_mode_size_bytes(mode);
379         tarval *tv;
380         ir_entity *ent;
381
382         init = skip_Id(init);
383
384         switch (get_irn_opcode(init)) {
385         case iro_Cast:
386                 do_dump_atomic_init(env, get_Cast_op(init));
387                 return;
388
389         case iro_Conv:
390                 do_dump_atomic_init(env, get_Conv_op(init));
391                 return;
392
393         case iro_Const:
394                 tv = get_Const_tarval(init);
395
396                 /* it's a arithmetic value */
397                 dump_arith_tarval(tv, bytes);
398                 return;
399
400         case iro_SymConst:
401                 switch (get_SymConst_kind(init)) {
402                 case symconst_addr_name:
403                         be_emit_ident(get_SymConst_name(init));
404                         break;
405
406                 case symconst_addr_ent:
407                         ent = get_SymConst_entity(init);
408                         be_gas_emit_entity(ent);
409                         break;
410
411                 case symconst_ofs_ent:
412                         ent = get_SymConst_entity(init);
413                         be_emit_irprintf("%d", get_entity_offset(ent));
414                         break;
415
416                 case symconst_type_size:
417                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
418                         break;
419
420                 case symconst_type_align:
421                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
422                         break;
423
424                 case symconst_enum_const:
425                         tv = get_enumeration_value(get_SymConst_enum(init));
426                         dump_arith_tarval(tv, bytes);
427                         break;
428
429                 default:
430                         assert(!"dump_atomic_init(): don't know how to init from this SymConst");
431                 }
432                 return;
433
434         case iro_Add:
435                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
436                         panic("Constant must be int or pointer for '+' to work");
437                 }
438                 do_dump_atomic_init(env, get_Add_left(init));
439                 be_emit_cstring(" + ");
440                 do_dump_atomic_init(env, get_Add_right(init));
441                 return;
442
443         case iro_Sub:
444                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
445                         panic("Constant must be int or pointer for '-' to work");
446                 }
447                 do_dump_atomic_init(env, get_Sub_left(init));
448                 be_emit_cstring(" - ");
449                 do_dump_atomic_init(env, get_Sub_right(init));
450                 return;
451
452         case iro_Mul:
453                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
454                         panic("Constant must be int or pointer for '*' to work");
455                 }
456                 do_dump_atomic_init(env, get_Mul_left(init));
457                 be_emit_cstring(" * ");
458                 do_dump_atomic_init(env, get_Mul_right(init));
459                 return;
460
461         case iro_Unknown:
462                 be_emit_cstring("0");
463                 return;
464
465         default:
466                 panic("dump_atomic_init(): unsupported IR-node %+F", init);
467         }
468 }
469
470 /**
471  * Dumps the type for given size (.byte, .long, ...)
472  *
473  * @param size  the size in bytes
474  */
475 static void dump_size_type(size_t size) {
476         switch (size) {
477         case 1:
478                 be_emit_cstring("\t.byte\t");
479                 break;
480
481         case 2:
482                 be_emit_cstring("\t.short\t");
483                 break;
484
485         case 4:
486                 be_emit_cstring("\t.long\t");
487                 break;
488
489         case 8:
490                 be_emit_cstring("\t.quad\t");
491                 break;
492
493         case 10:
494         case 12:
495                 /* handled in arith */
496                 break;
497
498         case 16:
499                 be_emit_cstring("\t.octa\t");
500                 break;
501
502         default:
503                 panic("Try to dump a type with %u bytes", (unsigned)size);
504         }
505 }
506
507 /**
508  * Emit an atomic value.
509  *
510  * @param env   the gas output environment
511  * @param init  a node representing the atomic value (on the const code irg)
512  */
513 static void dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
514 {
515         ir_mode *mode = get_irn_mode(init);
516         int bytes     = get_mode_size_bytes(mode);
517
518         dump_size_type(bytes);
519         do_dump_atomic_init(env, init);
520         be_emit_char('\n');
521         be_emit_write_line();
522 }
523
524 /************************************************************************/
525 /* Routines to dump global variables                                    */
526 /************************************************************************/
527
528 static int initializer_is_string_const(const ir_initializer_t *initializer)
529 {
530         size_t i, len;
531         int found_printable = 0;
532
533         if (initializer->kind != IR_INITIALIZER_COMPOUND)
534                 return 0;
535
536         len = initializer->compound.n_initializers;
537         if (len < 1)
538                 return 0;
539         for (i = 0; i < len; ++i) {
540                 int               c;
541                 tarval           *tv;
542                 ir_mode          *mode;
543                 ir_initializer_t *sub_initializer
544                         = initializer->compound.initializers[i];
545
546                 if (sub_initializer->kind != IR_INITIALIZER_TARVAL)
547                         return 0;
548
549                 tv   = sub_initializer->tarval.value;
550                 mode = get_tarval_mode(tv);
551
552                 if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
553                         return 0;
554
555                 c = get_tarval_long(tv);
556                 if (isgraph(c) || isspace(c))
557                         found_printable = 1;
558                 else if (c != 0)
559                         return 0;
560
561                 if (i == len - 1 && c != '\0')
562                         return 0;
563         }
564
565         return found_printable;
566 }
567
568 /**
569  * Determine if an entity is a string constant
570  * @param ent The entity
571  * @return 1 if it is a string constant, 0 otherwise
572  */
573 static int ent_is_string_const(const ir_entity *ent)
574 {
575         ir_type *type, *element_type;
576         ir_mode *mode;
577         int i, c, n;
578
579         type = get_entity_type(ent);
580
581         /* if it's an array */
582         if (!is_Array_type(type))
583                 return 0;
584
585         element_type = get_array_element_type(type);
586
587         /* and the array's element type is primitive */
588         if (!is_Primitive_type(element_type))
589                 return 0;
590
591         /* and the mode of the element type is an int of
592          * the same size as the byte mode */
593         mode = get_type_mode(element_type);
594         if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
595                 return 0;
596
597         if (ent->initializer != NULL) {
598                 return initializer_is_string_const(ent->initializer);
599         } else if (entity_has_compound_ent_values(ent)) {
600                 int found_printable = 0;
601                 /* if it contains only printable chars and a 0 at the end */
602                 n = get_compound_ent_n_values(ent);
603                 for (i = 0; i < n; ++i) {
604                         ir_node *irn = get_compound_ent_value(ent, i);
605                         if (! is_Const(irn))
606                                 return 0;
607
608                         c = (int) get_tarval_long(get_Const_tarval(irn));
609
610                         if (isgraph(c) || isspace(c))
611                                 found_printable = 1;
612                         else if (c != 0)
613                                 return 0;
614
615                         if (i == n - 1 && c != '\0')
616                                 return 0;
617                 }
618                 return found_printable;
619         }
620
621         return 0;
622 }
623
624 /**
625  * Dump a string constant.
626  * No checks are made!!
627  *
628  * @param ent  The entity to dump.
629  */
630 static void dump_string_cst(const ir_entity *ent)
631 {
632         int      i, len;
633         int      output_len;
634         ir_type *type;
635         int      type_size;
636         int      remaining_space;
637
638         len        = get_compound_ent_n_values(ent);
639         output_len = len;
640         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
641                 be_emit_cstring("\t.ascii \"");
642         } else {
643                 be_emit_cstring("\t.string \"");
644                 output_len -= 1;
645         }
646
647         for (i = 0; i < output_len; ++i) {
648                 ir_node *irn;
649                 int c;
650
651                 irn = get_compound_ent_value(ent, i);
652                 c = (int) get_tarval_long(get_Const_tarval(irn));
653
654                 switch (c) {
655                 case '"' : be_emit_cstring("\\\""); break;
656                 case '\n': be_emit_cstring("\\n"); break;
657                 case '\r': be_emit_cstring("\\r"); break;
658                 case '\t': be_emit_cstring("\\t"); break;
659                 case '\\': be_emit_cstring("\\\\"); break;
660                 default  :
661                         if (isprint(c))
662                                 be_emit_char(c);
663                         else
664                                 be_emit_irprintf("\\%o", c);
665                         break;
666                 }
667         }
668         be_emit_cstring("\"\n");
669         be_emit_write_line();
670
671         type            = get_entity_type(ent);
672         type_size       = get_type_size_bytes(type);
673         remaining_space = type_size - len;
674         assert(remaining_space >= 0);
675         if (remaining_space > 0) {
676                 be_emit_irprintf("\t.space\t%d\n", remaining_space);
677         }
678 }
679
680 static void dump_string_initializer(const ir_initializer_t *initializer)
681 {
682         size_t i, len;
683
684         len = initializer->compound.n_initializers;
685         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
686                 be_emit_cstring("\t.ascii \"");
687         } else {
688                 be_emit_cstring("\t.string \"");
689                 len -= 1;
690         }
691
692         for (i = 0; i < len; ++i) {
693                 const ir_initializer_t *sub_initializer
694                         = get_initializer_compound_value(initializer, i);
695
696                 tarval *tv = get_initializer_tarval_value(sub_initializer);
697                 int     c  = get_tarval_long(tv);
698
699                 switch (c) {
700                 case '"' : be_emit_cstring("\\\""); break;
701                 case '\n': be_emit_cstring("\\n"); break;
702                 case '\r': be_emit_cstring("\\r"); break;
703                 case '\t': be_emit_cstring("\\t"); break;
704                 case '\\': be_emit_cstring("\\\\"); break;
705                 default  :
706                         if (isprint(c))
707                                 be_emit_char(c);
708                         else
709                                 be_emit_irprintf("\\%o", c);
710                         break;
711                 }
712         }
713         be_emit_cstring("\"\n");
714         be_emit_write_line();
715 }
716
717 enum normal_or_bitfield_kind {
718         NORMAL = 0,
719         TARVAL,
720         BITFIELD
721 };
722
723 typedef struct {
724         enum normal_or_bitfield_kind kind;
725         union {
726                 ir_node       *value;
727                 tarval        *tarval;
728                 unsigned char  bf_val;
729         } v;
730 } normal_or_bitfield;
731
732 static int is_type_variable_size(ir_type *type)
733 {
734         (void) type;
735         /* TODO */
736         return 0;
737 }
738
739 static size_t get_initializer_size(const ir_initializer_t *initializer,
740                                    ir_type *type)
741 {
742         switch (get_initializer_kind(initializer)) {
743         case IR_INITIALIZER_TARVAL:
744                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
745                 return get_type_size_bytes(type);
746         case IR_INITIALIZER_CONST:
747         case IR_INITIALIZER_NULL:
748                 return get_type_size_bytes(type);
749         case IR_INITIALIZER_COMPOUND:
750                 if (!is_type_variable_size(type)) {
751                         return get_type_size_bytes(type);
752                 } else {
753                         unsigned n_entries
754                                 = get_initializer_compound_n_entries(initializer);
755                         unsigned i;
756                         unsigned initializer_size = get_type_size_bytes(type);
757                         for (i = 0; i < n_entries; ++i) {
758                                 ir_entity *entity = get_compound_member(type, i);
759                                 ir_type   *type   = get_entity_type(entity);
760
761                                 const ir_initializer_t *sub_initializer
762                                         = get_initializer_compound_value(initializer, i);
763
764                                 unsigned offset = get_entity_offset(entity);
765                                 unsigned size   = get_initializer_size(sub_initializer, type);
766
767                                 if (offset + size > initializer_size) {
768                                         initializer_size = offset + size;
769                                 }
770                         }
771                         return initializer_size;
772                 }
773         }
774
775         panic("found invalid initializer");
776 }
777
778 #ifndef NDEBUG
779 static normal_or_bitfield *glob_vals;
780 static size_t              max_vals;
781 #endif
782
783 static void dump_bitfield(normal_or_bitfield *vals, size_t offset_bits,
784                           const ir_initializer_t *initializer, ir_type *type)
785 {
786         unsigned char  last_bits = 0;
787         ir_mode       *mode      = get_type_mode(type);
788         tarval        *tv        = NULL;
789         unsigned char  curr_bits;
790         int            value_len;
791         int            j;
792
793         switch (get_initializer_kind(initializer)) {
794         case IR_INITIALIZER_NULL:
795                 return;
796         case IR_INITIALIZER_TARVAL:
797                 tv = get_initializer_tarval_value(initializer);
798                 break;
799         case IR_INITIALIZER_CONST: {
800                 ir_node *node = get_initializer_const_value(initializer);
801                 if (!is_Const(node)) {
802                         panic("bitfield initializer not a Const node");
803                 }
804                 tv = get_Const_tarval(node);
805                 break;
806         }
807         case IR_INITIALIZER_COMPOUND:
808                 panic("bitfield initializer is compound");
809         }
810         if (tv == NULL) {
811                 panic("Couldn't get numeric value for bitfield initializer");
812         }
813         tv = tarval_convert_to(tv, get_type_mode(type));
814
815         /* normalize offset */
816         vals        += offset_bits >> 3;
817         offset_bits &= 7;
818         value_len    = get_mode_size_bits(mode);
819
820         /* combine bits with existing bits */
821         for (j = 0; value_len + (int) offset_bits > 0; ++j) {
822                 assert((size_t) (vals - glob_vals) + j < max_vals);
823                 assert(vals[j].kind == BITFIELD ||
824                                 (vals[j].kind == NORMAL && vals[j].v.value == NULL));
825                 vals[j].kind = BITFIELD;
826                 curr_bits    = get_tarval_sub_bits(tv, j);
827                 vals[j].v.bf_val
828                         |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
829                 value_len -= 8;
830                 last_bits = curr_bits;
831         }
832 }
833
834 static void dump_ir_initializer(normal_or_bitfield *vals,
835                                 const ir_initializer_t *initializer,
836                                 ir_type *type)
837 {
838         assert((size_t) (vals - glob_vals) < max_vals);
839
840         switch (get_initializer_kind(initializer)) {
841         case IR_INITIALIZER_NULL:
842                 return;
843         case IR_INITIALIZER_TARVAL: {
844                 size_t i;
845
846                 assert(vals->kind != BITFIELD);
847                 vals->kind     = TARVAL;
848                 vals->v.tarval = get_initializer_tarval_value(initializer);
849                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
850                 for (i = 1; i < get_type_size_bytes(type); ++i) {
851                         vals[i].kind    = NORMAL;
852                         vals[i].v.value = NULL;
853                 }
854                 return;
855         }
856         case IR_INITIALIZER_CONST: {
857                 size_t i;
858
859                 assert(vals->kind != BITFIELD);
860                 vals->kind    = NORMAL;
861                 vals->v.value = get_initializer_const_value(initializer);
862                 for (i = 1; i < get_type_size_bytes(type); ++i) {
863                         vals[i].kind    = NORMAL;
864                         vals[i].v.value = NULL;
865                 }
866                 return;
867         }
868         case IR_INITIALIZER_COMPOUND: {
869                 size_t i = 0;
870                 size_t n = get_initializer_compound_n_entries(initializer);
871
872                 if (is_Array_type(type)) {
873                         ir_type *element_type = get_array_element_type(type);
874                         size_t   skip         = get_type_size_bytes(element_type);
875                         size_t   alignment    = get_type_alignment_bytes(element_type);
876                         size_t   misalign     = skip % alignment;
877                         if (misalign != 0) {
878                                 skip += alignment - misalign;
879                         }
880
881                         for (i = 0; i < n; ++i) {
882                                 ir_initializer_t *sub_initializer
883                                         = get_initializer_compound_value(initializer, i);
884
885                                 dump_ir_initializer(vals, sub_initializer, element_type);
886
887                                 vals += skip;
888                         }
889                 } else {
890                         size_t n_members, i;
891                         assert(is_compound_type(type));
892                         n_members = get_compound_n_members(type);
893                         for (i = 0; i < n_members; ++i) {
894                                 ir_entity        *member    = get_compound_member(type, i);
895                                 size_t            offset    = get_entity_offset(member);
896                                 ir_type          *subtype   = get_entity_type(member);
897                                 ir_mode          *mode      = get_type_mode(subtype);
898                                 ir_initializer_t *sub_initializer;
899
900                                 assert(i < get_initializer_compound_n_entries(initializer));
901                                 sub_initializer
902                                         = get_initializer_compound_value(initializer, i);
903
904                                 if (mode != NULL) {
905                                         size_t offset_bits
906                                                 = get_entity_offset_bits_remainder(member);
907                                         size_t value_len   = get_mode_size_bits(mode);
908
909                                         if (offset_bits != 0 ||
910                                                 (value_len != 8 && value_len != 16 && value_len != 32
911                                                  && value_len != 64)) {
912                                                 dump_bitfield(&vals[offset], offset_bits,
913                                                               sub_initializer, subtype);
914                                                 continue;
915                                         }
916                                 }
917
918                                 dump_ir_initializer(&vals[offset], sub_initializer, subtype);
919                         }
920                 }
921
922                 return;
923         }
924         }
925         panic("invalid ir_initializer kind found");
926 }
927
928 static void dump_initializer(be_gas_decl_env_t *env, const ir_entity *entity)
929 {
930         const ir_initializer_t *initializer = entity->initializer;
931         ir_type                *type;
932         normal_or_bitfield     *vals;
933         size_t                  size;
934         size_t                  k;
935
936         if (initializer_is_string_const(initializer)) {
937                 dump_string_initializer(initializer);
938                 return;
939         }
940
941         type = get_entity_type(entity);
942         size = get_initializer_size(initializer, type);
943
944         if (size == 0)
945                 return;
946
947         /*
948          * In the worst case, every initializer allocates one byte.
949          * Moreover, initializer might be big, do not allocate on stack.
950          */
951         vals = XMALLOCNZ(normal_or_bitfield, size);
952
953 #ifndef NDEBUG
954         glob_vals = vals;
955         max_vals  = size;
956 #endif
957
958         dump_ir_initializer(vals, initializer, type);
959
960         /* now write values sorted */
961         for (k = 0; k < size; ) {
962                 int space     = 0;
963                 int elem_size = 1;
964                 if (vals[k].kind == NORMAL) {
965                         if (vals[k].v.value != NULL) {
966                                 dump_atomic_init(env, vals[k].v.value);
967                                 elem_size = get_mode_size_bytes(get_irn_mode(vals[k].v.value));
968                         } else {
969                                 elem_size = 0;
970                         }
971                 } else if (vals[k].kind == TARVAL) {
972                         tarval *tv   = vals[k].v.tarval;
973                         size_t  size = get_mode_size_bytes(get_tarval_mode(tv));
974
975                         assert(tv != NULL);
976
977                         elem_size = size;
978                         dump_size_type(size);
979                         dump_arith_tarval(tv, size);
980                         be_emit_char('\n');
981                         be_emit_write_line();
982                 } else {
983                         assert(vals[k].kind == BITFIELD);
984                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
985                         be_emit_write_line();
986                 }
987
988                 k += elem_size;
989                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
990                         ++space;
991                         ++k;
992                 }
993
994                 /* a gap */
995                 if (space > 0) {
996                         be_emit_irprintf("\t.space\t%d\n", space);
997                         be_emit_write_line();
998                 }
999         }
1000         xfree(vals);
1001 }
1002
1003 static void dump_compound_graph_init(be_gas_decl_env_t *env,
1004                                      const ir_entity *ent)
1005 {
1006         normal_or_bitfield *vals;
1007         int i, j, n;
1008         unsigned k, last_ofs;
1009
1010         if (ent_is_string_const(ent)) {
1011                 dump_string_cst(ent);
1012                 return;
1013         }
1014
1015         n = get_compound_ent_n_values(ent);
1016
1017         /* Find the initializer size. Sorrily gcc support a nasty feature:
1018            The last field of a compound may be a flexible array. This allows
1019            initializers bigger than the type size. */
1020         last_ofs = get_type_size_bytes(get_entity_type(ent));
1021         for (i = 0; i < n; ++i) {
1022                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1023                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1024                 ir_node  *value         = get_compound_ent_value(ent, i);
1025                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1026
1027                 offset += (value_len + bits_remainder + 7) >> 3;
1028
1029                 if (offset > last_ofs) {
1030                         last_ofs = offset;
1031                 }
1032         }
1033
1034         /*
1035          * In the worst case, every initializer allocates one byte.
1036          * Moreover, initializer might be big, do not allocate on stack.
1037          */
1038         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1039
1040         /* collect the values and store them at the offsets */
1041         for (i = 0; i < n; ++i) {
1042                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1043                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1044                 ir_node  *value      = get_compound_ent_value(ent, i);
1045                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1046
1047                 assert(offset_bits >= 0);
1048
1049                 if (offset_bits != 0 ||
1050                                 (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1051                         tarval *tv = get_atomic_init_tv(value);
1052                         unsigned char curr_bits, last_bits = 0;
1053                         if (tv == NULL) {
1054                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1055                                                 get_entity_ld_name(ent));
1056                         }
1057                         /* normalize offset */
1058                         offset += offset_bits >> 3;
1059                         offset_bits &= 7;
1060
1061                         for (j = 0; value_len + offset_bits > 0; ++j) {
1062                                 assert(offset + j < last_ofs);
1063                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1064                                 vals[offset + j].kind = BITFIELD;
1065                                 curr_bits = get_tarval_sub_bits(tv, j);
1066                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1067                                 value_len -= 8;
1068                                 last_bits = curr_bits;
1069                         }
1070                 } else {
1071                         int i;
1072
1073                         assert(offset < last_ofs);
1074                         assert(vals[offset].kind == NORMAL);
1075                         for (i = 1; i < value_len / 8; ++i) {
1076                                 assert(vals[offset + i].v.value == NULL);
1077                         }
1078                         vals[offset].v.value = value;
1079                 }
1080         }
1081
1082         /* now write them sorted */
1083         for (k = 0; k < last_ofs; ) {
1084                 int space = 0, skip = 0;
1085                 if (vals[k].kind == NORMAL) {
1086                         if (vals[k].v.value != NULL) {
1087                                 dump_atomic_init(env, vals[k].v.value);
1088                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1089                         } else {
1090                                 space = 1;
1091                         }
1092                 } else {
1093                         assert(vals[k].kind == BITFIELD);
1094                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1095                 }
1096
1097                 ++k;
1098                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1099                         ++space;
1100                         ++k;
1101                 }
1102                 space -= skip;
1103                 assert(space >= 0);
1104
1105                 /* a gap */
1106                 if (space > 0) {
1107                         be_emit_irprintf("\t.space\t%d\n", space);
1108                         be_emit_write_line();
1109                 }
1110         }
1111         xfree(vals);
1112 }
1113
1114 static void emit_align(unsigned p2alignment)
1115 {
1116         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1117         be_emit_write_line();
1118 }
1119
1120 static unsigned get_effective_entity_alignment(const ir_entity *entity)
1121 {
1122         unsigned alignment = get_entity_alignment(entity);
1123         if (alignment == 0) {
1124                 ir_type *type = get_entity_type(entity);
1125                 alignment     = get_type_alignment_bytes(type);
1126         }
1127         return alignment;
1128 }
1129
1130 static be_gas_section_t determine_section(be_gas_decl_env_t *env,
1131                                           const ir_entity *entity)
1132 {
1133         ir_type *owner = get_entity_owner(entity);
1134
1135         if (owner == get_segment_type(IR_SEGMENT_GLOBAL)) {
1136                 ir_linkage linkage = get_entity_linkage(entity);
1137                 if (linkage & IR_LINKAGE_CONSTANT) {
1138                         /* mach-o is the only one with a cstring section */
1139                         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
1140                                         && ent_is_string_const(entity))
1141                                 return GAS_SECTION_CSTRING;
1142
1143                         return GAS_SECTION_RODATA;
1144                 }
1145                 if (!entity_has_definition(entity))
1146                         return GAS_SECTION_BSS;
1147
1148                 return GAS_SECTION_DATA;
1149
1150         } else if (owner == env->main_env->pic_symbols_type) {
1151                 return GAS_SECTION_PIC_SYMBOLS;
1152         } else if (owner == env->main_env->pic_trampolines_type) {
1153                 return GAS_SECTION_PIC_TRAMPOLINES;
1154         } else if (owner == get_segment_type(IR_SEGMENT_CONSTRUCTORS)) {
1155                 return GAS_SECTION_CONSTRUCTORS;
1156         } else if (owner == get_segment_type(IR_SEGMENT_DESTRUCTORS)) {
1157                 return GAS_SECTION_DESTRUCTORS;
1158         } else if (owner == get_segment_type(IR_SEGMENT_THREAD_LOCAL)) {
1159                 return GAS_SECTION_TLS;
1160         }
1161
1162         panic("Couldn't determine section for %+F?!?", entity);
1163 }
1164
1165 static void emit_common(const ir_entity *ent)
1166 {
1167         const char *name      = get_entity_ld_name(ent);
1168         unsigned    size      = get_type_size_bytes(get_entity_type(ent));
1169         unsigned    alignment = get_effective_entity_alignment(ent);
1170
1171         switch (be_gas_object_file_format) {
1172         case OBJECT_FILE_FORMAT_MACH_O:
1173                 be_emit_irprintf("\t.comm %s,%u,%u\n", name, size,
1174                                  log2_floor(alignment));
1175                 be_emit_write_line();
1176                 return;
1177         case OBJECT_FILE_FORMAT_ELF:
1178                 be_emit_irprintf("\t.comm %s,%u,%u\n", name, size, alignment);
1179                 be_emit_write_line();
1180                 return;
1181         case OBJECT_FILE_FORMAT_COFF:
1182                 be_emit_irprintf("\t.comm %s,%u # %u\n", name, size, alignment);
1183                 be_emit_write_line();
1184                 return;
1185         }
1186         panic("invalid object file format");
1187 }
1188
1189 static void dump_indirect_symbol(const ir_entity *entity, be_gas_section_t section)
1190 {
1191         /* we can only do PIC code on macho so far */
1192         assert(be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O);
1193
1194         be_emit_ident(get_entity_ld_ident(entity));
1195         be_emit_cstring(":\n");
1196         be_emit_write_line();
1197         be_emit_cstring("\t.indirect_symbol ");
1198         be_emit_ident(get_entity_ident(entity));
1199         be_emit_char('\n');
1200         be_emit_write_line();
1201         if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1202                 be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1203                 be_emit_write_line();
1204         } else {
1205                 assert(section == GAS_SECTION_PIC_SYMBOLS);
1206                 be_emit_cstring("\t.long 0\n");
1207                 be_emit_write_line();
1208         }
1209 }
1210
1211 /**
1212  * Dump a global entity.
1213  *
1214  * @param env  the gas output environment
1215  * @param ent  the entity to be dumped
1216  */
1217 static void dump_global(be_gas_decl_env_t *env, const ir_entity *ent)
1218 {
1219         ir_type          *type           = get_entity_type(ent);
1220         ident            *ld_ident       = get_entity_ld_ident(ent);
1221         unsigned          alignment      = get_effective_entity_alignment(ent);
1222         be_gas_section_t  section        = determine_section(env, ent);
1223
1224         /* we already emitted all methods. Except for the trampolines which
1225          * the assembler/linker generates */
1226         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1227                 return;
1228         }
1229         /* block labels are already emittet in the code */
1230         if (type == firm_code_type)
1231                 return;
1232
1233         be_dbg_variable(ent);
1234
1235         /* nothing to do for externally defined values */
1236         if (get_entity_visibility(ent) == ir_visibility_external)
1237                 return;
1238
1239         if (!is_po2(alignment))
1240                 panic("alignment not a power of 2");
1241
1242         if (section == GAS_SECTION_BSS &&
1243                         (get_entity_linkage(ent) & IR_LINKAGE_MERGE)) {
1244                 if (get_entity_visibility(ent) != ir_visibility_default) {
1245                         panic("merge link semantic not supported for local/extern entities");
1246                 }
1247                 emit_common(ent);
1248                 return;
1249         }
1250
1251         be_gas_emit_switch_section(section);
1252
1253         if (section == GAS_SECTION_PIC_TRAMPOLINES
1254                         || section == GAS_SECTION_PIC_SYMBOLS) {
1255                 dump_indirect_symbol(ent, section);
1256                 return;
1257         }
1258
1259         /* alignment */
1260         if (alignment > 1) {
1261                 emit_align(alignment);
1262         }
1263         emit_entity_visibility(ent);
1264         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF
1265                         && be_gas_emit_types) {
1266                 be_emit_cstring("\t.type\t");
1267                 be_emit_ident(ld_ident);
1268                 be_emit_cstring(", ");
1269                 be_emit_char(be_gas_elf_type_char);
1270                 be_emit_cstring("object\n\t.size\t");
1271                 be_emit_ident(ld_ident);
1272                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1273         }
1274         be_emit_ident(ld_ident);
1275         be_emit_cstring(":\n");
1276         be_emit_write_line();
1277
1278         if (ent->initializer != NULL) {
1279                 dump_initializer(env, ent);
1280         } else if(entity_has_compound_ent_values(ent)) {
1281                 dump_compound_graph_init(env, ent);
1282         } else {
1283                 /* uninitialized */
1284                 be_emit_irprintf("\t.space %u\n", get_type_size_bytes(type));
1285                 be_emit_write_line();
1286         }
1287 }
1288
1289 /**
1290  * Dumps declarations of global variables and the initialization code.
1291  *
1292  * @param gt                a global like type, either the global or the TLS one
1293  * @param env               an environment
1294  */
1295 static void be_gas_dump_globals(ir_type *gt, be_gas_decl_env_t *env)
1296 {
1297         int i, n = get_compound_n_members(gt);
1298
1299         for (i = 0; i < n; i++) {
1300                 ir_entity *ent = get_compound_member(gt, i);
1301                 dump_global(env, ent);
1302         }
1303 }
1304
1305 /************************************************************************/
1306
1307 /* Generate all entities. */
1308 void be_gas_emit_decls(const be_main_env_t *main_env)
1309 {
1310         be_gas_decl_env_t env;
1311         memset(&env, 0, sizeof(env));
1312
1313         /* dump global type */
1314         env.main_env = main_env;
1315         env.section  = (be_gas_section_t) -1;
1316
1317         be_gas_dump_globals(get_glob_type(), &env);
1318         be_gas_dump_globals(get_tls_type(), &env);
1319         be_gas_dump_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env);
1320         be_gas_dump_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env);
1321         be_gas_dump_globals(main_env->pic_symbols_type, &env);
1322         be_gas_dump_globals(main_env->pic_trampolines_type, &env);
1323
1324         /**
1325          * ".subsections_via_symbols marks object files which are OK to divide
1326          * their section contents into individual blocks".
1327          * From my understanding this means no label points in the middle of an
1328          * object which we want to address as a whole. Firm code should be fine
1329          * with this.
1330          */
1331         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
1332                 be_emit_cstring("\t.subsections_via_symbols\n");
1333                 be_emit_write_line();
1334         }
1335 }