amd64: small changes w.r.t. stack alignment.
[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  * An environment containing all needed dumper data.
56  * Currently we create the file completely in memory first, then
57  * write it to the disk. This is an artifact from the old C-generating backend
58  * and even there NOT needed. So we might change it in the future.
59  */
60 typedef struct _be_gas_decl_env {
61         be_gas_section_t     section;
62         const be_main_env_t *main_env;
63 } be_gas_decl_env_t;
64
65 static void emit_section_macho(be_gas_section_t section)
66 {
67         be_gas_section_t  base  = section & GAS_SECTION_TYPE_MASK;
68         be_gas_section_t  flags = section & ~GAS_SECTION_TYPE_MASK;
69         const char       *name;
70
71         if (current_section == section)
72                 return;
73         current_section = section;
74
75         /* shortforms */
76         if (flags == 0) {
77                 switch (base) {
78                 case GAS_SECTION_TEXT:            name = "text";          break;
79                 case GAS_SECTION_DATA:            name = "data";          break;
80                 case GAS_SECTION_RODATA:          name = "const";         break;
81                 case GAS_SECTION_BSS:             name = "data";          break;
82                 case GAS_SECTION_CONSTRUCTORS:    name = "mod_init_func"; break;
83                 case GAS_SECTION_DESTRUCTORS:     name = "mod_term_func"; break;
84                 case GAS_SECTION_PIC_TRAMPOLINES: name = "section\t__IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5"; break;
85                 case GAS_SECTION_PIC_SYMBOLS:     name = "section\t__IMPORT,__pointers,non_lazy_symbol_pointers"; break;
86                 case GAS_SECTION_CSTRING:         name = "cstring";       break;
87                 default: panic("unsupported scetion type 0x%X", section);
88                 }
89                 be_emit_irprintf("\t.%s\n", name);
90                 be_emit_write_line();
91         } else if (flags & GAS_SECTION_FLAG_COMDAT) {
92                 switch (base) {
93                 case GAS_SECTION_TEXT:            name = "section __TEXT,__textcoal_nt,coalesced,pure_instructions"; break;
94                 case GAS_SECTION_BSS:
95                 case GAS_SECTION_DATA:            name = "section __DATA,__datacoal_nt,coalesced"; break;
96                 case GAS_SECTION_RODATA:          name = "section __TEXT,__const_coal,coalesced"; break;
97                 case GAS_SECTION_CSTRING:         name = "section __TEXT,__const_coal,coalesced"; break;
98                 default: panic("unsupported scetion type 0x%X", section);
99                 }
100         } else {
101                 panic("unsupported section type 0x%X\n", section);
102         }
103 }
104
105 static void emit_section_sparc(be_gas_section_t section, const ir_entity *entity)
106 {
107         be_gas_section_t base = section & GAS_SECTION_TYPE_MASK;
108         be_gas_section_t flags = section & ~GAS_SECTION_TYPE_MASK;
109         static const char *const basename[] = {
110                 "text", "data", "rodata", "bss", "ctors", "dtors"
111         };
112
113         if (current_section == section && !(section & GAS_SECTION_FLAG_COMDAT))
114                 return;
115         current_section = section;
116
117         be_emit_cstring("\t.section\t\".");
118
119         /* Part1: section-name */
120         if (flags & GAS_SECTION_FLAG_TLS)
121                 be_emit_char('t');
122         assert(base < sizeof(basename)/sizeof(basename[0]));
123         be_emit_string(basename[base]);
124
125         if (flags & GAS_SECTION_FLAG_COMDAT) {
126                 be_emit_char('.');
127                 be_gas_emit_entity(entity);
128         }
129         be_emit_char('"');
130
131         /* for the simple sections we're done here */
132         if (flags == 0)
133                 goto end;
134
135         be_emit_cstring(",#alloc");
136
137         switch (base) {
138         case GAS_SECTION_TEXT: be_emit_cstring(",#execinstr"); break;
139         case GAS_SECTION_DATA:
140         case GAS_SECTION_BSS:  be_emit_cstring(",#write"); break;
141         default:
142                 /* nothing */
143                 break;
144         }
145         if (flags & GAS_SECTION_FLAG_TLS) {
146                 be_emit_cstring(",#tls");
147         }
148
149 end:
150         be_emit_char('\n');
151         be_emit_write_line();
152 }
153
154 static void emit_section(be_gas_section_t section, const ir_entity *entity)
155 {
156         be_gas_section_t base = section & GAS_SECTION_TYPE_MASK;
157         be_gas_section_t flags = section & ~GAS_SECTION_TYPE_MASK;
158         static const char *const basename[] = {
159                 "text", "data", "rodata", "bss", "ctors", "dtors"
160         };
161         static const char *const type[] = {
162                 "progbits", "progbits", "progbits", "nobits", "init_array", "fini_array"
163         };
164
165         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
166                 emit_section_macho(section);
167                 return;
168         } else if(be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF_SPARC) {
169                 emit_section_sparc(section, entity);
170                 return;
171         }
172
173         if (current_section == section && !(section & GAS_SECTION_FLAG_COMDAT))
174                 return;
175         current_section = section;
176
177         /* shortforms */
178         if (flags == 0) {
179                 switch (base) {
180                 case GAS_SECTION_TEXT:
181                         be_emit_cstring("\t.text\n");
182                         be_emit_write_line();
183                         return;
184                 case GAS_SECTION_DATA:
185                         be_emit_cstring("\t.data\n");
186                         be_emit_write_line();
187                         return;
188                 case GAS_SECTION_RODATA:
189                         be_emit_cstring("\t.section\t.rodata\n");
190                         be_emit_write_line();
191                         return;
192                 case GAS_SECTION_BSS:
193                         be_emit_cstring("\t.bss\n");
194                         be_emit_write_line();
195                         return;
196                 default:
197                         break;
198                 }
199         }
200
201         assert(base < sizeof(basename)/sizeof(basename[0]));
202         be_emit_cstring("\t.section\t.");
203         /* section name */
204         if (flags & GAS_SECTION_FLAG_TLS)
205                 be_emit_char('t');
206         be_emit_string(basename[base]);
207         if (flags & GAS_SECTION_FLAG_COMDAT) {
208                 be_emit_char('.');
209                 be_gas_emit_entity(entity);
210         }
211
212         /* section flags */
213         be_emit_cstring(",\"");
214         if (be_gas_object_file_format != OBJECT_FILE_FORMAT_COFF)
215                 be_emit_char('a');
216         if (base == GAS_SECTION_TEXT)
217                 be_emit_char('x');
218         if (base != GAS_SECTION_RODATA && base != GAS_SECTION_TEXT)
219                 be_emit_char('w');
220         if (flags & GAS_SECTION_FLAG_TLS)
221                 be_emit_char('T');
222         if (flags & GAS_SECTION_FLAG_COMDAT)
223                 be_emit_char('G');
224         /* section type */
225         if (be_gas_object_file_format != OBJECT_FILE_FORMAT_COFF) {
226                 be_emit_cstring("\",");
227                 be_emit_char(be_gas_elf_type_char);
228                 be_emit_string(type[base]);
229         }
230
231         if (flags & GAS_SECTION_FLAG_COMDAT) {
232                 be_emit_char(',');
233                 be_gas_emit_entity(entity);
234                 be_emit_cstring(",comdat");
235         }
236         be_emit_char('\n');
237         be_emit_write_line();
238 }
239
240
241
242 void be_gas_emit_switch_section(be_gas_section_t section)
243 {
244         /* you have to produce a switch_section call with entity manually
245          * for comdat sections */
246         assert( !(section & GAS_SECTION_FLAG_COMDAT));
247
248         emit_section(section, NULL);
249 }
250
251 static tarval *get_initializer_tarval(const ir_initializer_t *initializer)
252 {
253         if (initializer->kind == IR_INITIALIZER_TARVAL)
254                 return initializer->tarval.value;
255         if (initializer->kind == IR_INITIALIZER_CONST) {
256                 ir_node *node = initializer->consti.value;
257                 if (is_Const(node)) {
258                         return get_Const_tarval(node);
259                 }
260         }
261         return get_tarval_undefined();
262 }
263
264 static int initializer_is_string_const(const ir_initializer_t *initializer)
265 {
266         size_t i, len;
267         int found_printable = 0;
268
269         if (initializer->kind != IR_INITIALIZER_COMPOUND)
270                 return 0;
271
272         len = initializer->compound.n_initializers;
273         if (len < 1)
274                 return 0;
275         for (i = 0; i < len; ++i) {
276                 int               c;
277                 tarval           *tv;
278                 ir_mode          *mode;
279                 ir_initializer_t *sub_initializer
280                         = initializer->compound.initializers[i];
281
282                 tv = get_initializer_tarval(sub_initializer);
283                 if (!tarval_is_constant(tv))
284                         return 0;
285
286                 mode = get_tarval_mode(tv);
287                 if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
288                         return 0;
289
290                 c = get_tarval_long(tv);
291                 if (isgraph(c) || isspace(c))
292                         found_printable = 1;
293                 else if (c != 0)
294                         return 0;
295
296                 if (i == len - 1 && c != '\0')
297                         return 0;
298         }
299
300         return found_printable;
301 }
302
303 static bool initializer_is_null(const ir_initializer_t *initializer)
304 {
305         switch (initializer->kind) {
306         case IR_INITIALIZER_NULL:
307                 return true;
308         case IR_INITIALIZER_TARVAL: {
309                 tarval *tv = initializer->tarval.value;
310                 return tarval_is_null(tv);
311         }
312         case IR_INITIALIZER_CONST: {
313                 ir_node *value = initializer->consti.value;
314                 if (!is_Const(value))
315                         return false;
316                 return is_Const_null(value);
317         }
318         case IR_INITIALIZER_COMPOUND: {
319                 size_t i;
320                 for (i = 0; i < initializer->compound.n_initializers; ++i) {
321                         ir_initializer_t *subinitializer
322                                 = initializer->compound.initializers[i];
323                         if (!initializer_is_null(subinitializer))
324                                 return false;
325                 }
326                 return true;
327         }
328         }
329         panic("invalid initializer in initializer_is_null");
330 }
331
332 /**
333  * Determine if an entity is a string constant
334  * @param ent The entity
335  * @return 1 if it is a string constant, 0 otherwise
336  */
337 static int entity_is_string_const(const ir_entity *ent)
338 {
339         ir_type *type, *element_type;
340         ir_mode *mode;
341         int i, c, n;
342
343         type = get_entity_type(ent);
344
345         /* if it's an array */
346         if (!is_Array_type(type))
347                 return 0;
348
349         element_type = get_array_element_type(type);
350
351         /* and the array's element type is primitive */
352         if (!is_Primitive_type(element_type))
353                 return 0;
354
355         /* and the mode of the element type is an int of
356          * the same size as the byte mode */
357         mode = get_type_mode(element_type);
358         if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
359                 return 0;
360
361         if (ent->initializer != NULL) {
362                 return initializer_is_string_const(ent->initializer);
363         } else if (entity_has_compound_ent_values(ent)) {
364                 int found_printable = 0;
365                 /* if it contains only printable chars and a 0 at the end */
366                 n = get_compound_ent_n_values(ent);
367                 for (i = 0; i < n; ++i) {
368                         ir_node *irn = get_compound_ent_value(ent, i);
369                         if (! is_Const(irn))
370                                 return 0;
371
372                         c = (int) get_tarval_long(get_Const_tarval(irn));
373
374                         if (isgraph(c) || isspace(c))
375                                 found_printable = 1;
376                         else if (c != 0)
377                                 return 0;
378
379                         if (i == n - 1 && c != '\0')
380                                 return 0;
381                 }
382                 return found_printable;
383         }
384
385         return 0;
386 }
387
388 static bool entity_is_null(const ir_entity *entity)
389 {
390         if (entity->initializer != NULL) {
391                 return initializer_is_null(entity->initializer);
392         } else if (entity_has_compound_ent_values(entity)) {
393                 /* I'm too lazy to implement this case as compound graph paths will be
394                  * remove anyway in the future */
395                 return false;
396         }
397         /* uninitialized, NULL is fine */
398         return true;
399 }
400
401 static bool is_comdat(const ir_entity *entity)
402 {
403         ir_linkage linkage = get_entity_linkage(entity);
404         return (linkage & IR_LINKAGE_MERGE)
405                 && (linkage & IR_LINKAGE_GARBAGE_COLLECT);
406 }
407
408 static be_gas_section_t determine_basic_section(const ir_entity *entity)
409 {
410         ir_linkage linkage;
411
412         if (is_method_entity(entity))
413                 return GAS_SECTION_TEXT;
414
415         linkage = get_entity_linkage(entity);
416         if (linkage & IR_LINKAGE_CONSTANT) {
417                 /* mach-o is the only one with a cstring section */
418                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
419                                 && entity_is_string_const(entity))
420                         return GAS_SECTION_CSTRING;
421
422                 return GAS_SECTION_RODATA;
423         }
424         if (entity_is_null(entity))
425                 return GAS_SECTION_BSS;
426
427         return GAS_SECTION_DATA;
428 }
429
430 static be_gas_section_t determine_section(be_gas_decl_env_t *env,
431                                           const ir_entity *entity)
432 {
433         ir_type *owner = get_entity_owner(entity);
434
435         if (owner == get_segment_type(IR_SEGMENT_GLOBAL)) {
436                 be_gas_section_t section = determine_basic_section(entity);
437                 if (is_comdat(entity))
438                         section |= GAS_SECTION_FLAG_COMDAT;
439                 return section;
440         } else if (env != NULL && owner == env->main_env->pic_symbols_type) {
441                 return GAS_SECTION_PIC_SYMBOLS;
442         } else if (env != NULL && owner == env->main_env->pic_trampolines_type) {
443                 return GAS_SECTION_PIC_TRAMPOLINES;
444         } else if (owner == get_segment_type(IR_SEGMENT_CONSTRUCTORS)) {
445                 return GAS_SECTION_CONSTRUCTORS;
446         } else if (owner == get_segment_type(IR_SEGMENT_DESTRUCTORS)) {
447                 return GAS_SECTION_DESTRUCTORS;
448         } else if (owner == get_segment_type(IR_SEGMENT_THREAD_LOCAL)) {
449                 be_gas_section_t section = determine_basic_section(entity);
450                 if (is_comdat(entity))
451                         section |= GAS_SECTION_FLAG_COMDAT;
452
453                 return section | GAS_SECTION_FLAG_TLS;
454         }
455
456         /* the java frontend keeps some functions inside classes */
457         if (is_Class_type(owner)) {
458                 return determine_basic_section(entity);
459         }
460
461         panic("Couldn't determine section for %+F?!?", entity);
462 }
463
464 static void emit_weak(const ir_entity *entity)
465 {
466         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
467                 be_emit_cstring("\t.weak_reference ");
468         } else {
469                 be_emit_cstring("\t.weak ");
470         }
471         be_gas_emit_entity(entity);
472         be_emit_char('\n');
473         be_emit_write_line();
474 }
475
476 static void emit_visibility(const ir_entity *entity)
477 {
478         ir_linkage linkage = get_entity_linkage(entity);
479
480         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
481                 emit_weak(entity);
482                 /* Note: .weak seems to imply .globl so no need to output .globl */
483         } else if (get_entity_visibility(entity) == ir_visibility_default) {
484                 be_emit_cstring(".globl ");
485                 be_gas_emit_entity(entity);
486                 be_emit_char('\n');
487                 be_emit_write_line();
488         }
489
490         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
491                         && (linkage & IR_LINKAGE_HIDDEN_USER)) {
492                 be_emit_cstring("\t.no_dead_strip ");
493                 be_gas_emit_entity(entity);
494                 be_emit_char('\n');
495                 be_emit_write_line();
496         }
497 }
498
499 void be_gas_emit_function_prolog(const ir_entity *entity, unsigned po2alignment)
500 {
501         be_gas_section_t section = determine_section(NULL, entity);
502         emit_section(section, entity);
503
504         /* write the begin line (makes the life easier for scripts parsing the
505          * assembler) */
506         be_emit_write_line();
507         be_emit_cstring("# -- Begin  ");
508         be_gas_emit_entity(entity);
509         be_emit_char('\n');
510         be_emit_write_line();
511
512         if (po2alignment > 0) {
513                 const char *fill_byte = "";
514                 unsigned    maximum_skip = (1 << po2alignment) - 1;
515                 /* gcc fills space between function with 0x90... */
516                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
517                         fill_byte = "0x90";
518                 }
519                 be_emit_cstring("\t.p2align ");
520                 be_emit_irprintf("%u,%s,%u\n", po2alignment, fill_byte, maximum_skip);
521                 be_emit_write_line();
522         }
523         emit_visibility(entity);
524
525         switch (be_gas_object_file_format) {
526         case OBJECT_FILE_FORMAT_ELF:
527         case OBJECT_FILE_FORMAT_ELF_SPARC:
528                 be_emit_cstring("\t.type\t");
529                 be_gas_emit_entity(entity);
530                 be_emit_cstring(", ");
531                 be_emit_char(be_gas_elf_type_char);
532                 be_emit_cstring("function\n");
533                 be_emit_write_line();
534                 break;
535         case OBJECT_FILE_FORMAT_COFF:
536                 be_emit_cstring("\t.def\t");
537                 be_gas_emit_entity(entity);
538                 be_emit_cstring(";");
539                 if (get_entity_visibility(entity) == ir_visibility_local) {
540                         be_emit_cstring("\t.scl\t3;");
541                 } else {
542                         be_emit_cstring("\t.scl\t2;");
543                 }
544                 be_emit_cstring("\t.type\t32;\t.endef\n");
545                 be_emit_write_line();
546                 break;
547         case OBJECT_FILE_FORMAT_MACH_O:
548                 break;
549         }
550         be_gas_emit_entity(entity);
551         be_emit_cstring(":\n");
552         be_emit_write_line();
553 }
554
555 void be_gas_emit_function_epilog(const ir_entity *entity)
556 {
557         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF) {
558                 be_emit_cstring("\t.size\t");
559                 be_gas_emit_entity(entity);
560                 be_emit_cstring(", .-");
561                 be_gas_emit_entity(entity);
562                 be_emit_char('\n');
563                 be_emit_write_line();
564         }
565
566         be_emit_cstring("# -- End  ");
567         be_gas_emit_entity(entity);
568         be_emit_char('\n');
569         be_emit_write_line();
570 }
571
572 /************************************************************************/
573
574 /**
575  * Output a tarval.
576  *
577  * @param tv     the tarval
578  * @param bytes  the width of the tarvals value in bytes
579  */
580 static void emit_arith_tarval(tarval *tv, int bytes)
581 {
582         switch (bytes) {
583         case 1:
584                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
585                 return;
586
587         case 2:
588                 be_emit_irprintf("0x%02x%02x", get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
589                 return;
590
591         case 4:
592                 be_emit_irprintf("0x%02x%02x%02x%02x",
593                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
594                 return;
595
596         case 8:
597                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
598                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6), get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
599                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
600                 return;
601
602         case 12:
603                 /* Beware: Mixed endian output!  One little endian number emitted as
604                  * three longs.  Each long initializer is written in big endian. */
605                 be_emit_irprintf(
606                         "\t.long\t0x%02x%02x%02x%02x\n"
607                         "\t.long\t0x%02x%02x%02x%02x\n"
608                         "\t.long\t0x%02x%02x%02x%02x",
609                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
610                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
611                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
612                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
613                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
614                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
615                 );
616                 return;
617
618         case 16:
619                 /* Beware: Mixed endian output!  One little endian number emitted as
620                  * three longs.  Each long initializer is written in big endian. */
621                 be_emit_irprintf(
622                         "\t.long\t0x%02x%02x%02x%02x\n"
623                         "\t.long\t0x%02x%02x%02x%02x\n"
624                         "\t.long\t0x%02x%02x%02x%02x\n"
625                         "\t.long\t0x%02x%02x%02x%02x",
626                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
627                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
628                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
629                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
630                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
631                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
632                         get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 14),
633                         get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12)
634                 );
635                 return;
636         }
637
638         panic("Can't dump a tarval with %d bytes", bytes);
639 }
640
641 /**
642  * Return the label prefix for labeled instructions.
643  */
644 const char *be_gas_insn_label_prefix(void)
645 {
646         return ".LE";
647 }
648
649 /**
650  * Return the tarval of an atomic initializer.
651  *
652  * @param init  a node representing the initializer (on the const code irg)
653  *
654  * @return the tarval
655  */
656 static tarval *get_atomic_init_tv(ir_node *init)
657 {
658         for (;;) {
659                 ir_mode *mode = get_irn_mode(init);
660
661                 switch (get_irn_opcode(init)) {
662
663                 case iro_Cast:
664                         init = get_Cast_op(init);
665                         continue;
666
667                 case iro_Conv:
668                         init = get_Conv_op(init);
669                         continue;
670
671                 case iro_Const:
672                         return get_Const_tarval(init);
673
674                 case iro_SymConst:
675                         switch (get_SymConst_kind(init)) {
676                         case symconst_type_size:
677                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
678
679                         case symconst_type_align:
680                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
681
682                         case symconst_ofs_ent:
683                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
684
685                         case symconst_enum_const:
686                                 return get_enumeration_value(get_SymConst_enum(init));
687
688                         default:
689                                 return NULL;
690                         }
691
692                 default:
693                         return NULL;
694                 }
695         }
696 }
697
698 /**
699  * Dump an atomic value.
700  *
701  * @param env   the gas output environment
702  * @param init  a node representing the atomic value (on the const code irg)
703  */
704 static void do_emit_atomic_init(be_gas_decl_env_t *env, ir_node *init)
705 {
706         ir_mode *mode = get_irn_mode(init);
707         int bytes     = get_mode_size_bytes(mode);
708         tarval *tv;
709         ir_entity *ent;
710
711         init = skip_Id(init);
712
713         switch (get_irn_opcode(init)) {
714         case iro_Cast:
715                 do_emit_atomic_init(env, get_Cast_op(init));
716                 return;
717
718         case iro_Conv:
719                 do_emit_atomic_init(env, get_Conv_op(init));
720                 return;
721
722         case iro_Const:
723                 tv = get_Const_tarval(init);
724
725                 /* it's a arithmetic value */
726                 emit_arith_tarval(tv, bytes);
727                 return;
728
729         case iro_SymConst:
730                 switch (get_SymConst_kind(init)) {
731                 case symconst_addr_ent:
732                         ent = get_SymConst_entity(init);
733                         be_gas_emit_entity(ent);
734                         break;
735
736                 case symconst_ofs_ent:
737                         ent = get_SymConst_entity(init);
738                         be_emit_irprintf("%d", get_entity_offset(ent));
739                         break;
740
741                 case symconst_type_size:
742                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
743                         break;
744
745                 case symconst_type_align:
746                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
747                         break;
748
749                 case symconst_enum_const:
750                         tv = get_enumeration_value(get_SymConst_enum(init));
751                         emit_arith_tarval(tv, bytes);
752                         break;
753
754                 default:
755                         assert(!"emit_atomic_init(): don't know how to init from this SymConst");
756                 }
757                 return;
758
759         case iro_Add:
760                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
761                         panic("Constant must be int or pointer for '+' to work");
762                 }
763                 do_emit_atomic_init(env, get_Add_left(init));
764                 be_emit_cstring(" + ");
765                 do_emit_atomic_init(env, get_Add_right(init));
766                 return;
767
768         case iro_Sub:
769                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
770                         panic("Constant must be int or pointer for '-' to work");
771                 }
772                 do_emit_atomic_init(env, get_Sub_left(init));
773                 be_emit_cstring(" - ");
774                 do_emit_atomic_init(env, get_Sub_right(init));
775                 return;
776
777         case iro_Mul:
778                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
779                         panic("Constant must be int or pointer for '*' to work");
780                 }
781                 do_emit_atomic_init(env, get_Mul_left(init));
782                 be_emit_cstring(" * ");
783                 do_emit_atomic_init(env, get_Mul_right(init));
784                 return;
785
786         case iro_Unknown:
787                 be_emit_cstring("0");
788                 return;
789
790         default:
791                 panic("emit_atomic_init(): unsupported IR-node %+F", init);
792         }
793 }
794
795 /**
796  * Dumps the type for given size (.byte, .long, ...)
797  *
798  * @param size  the size in bytes
799  */
800 static void emit_size_type(size_t size)
801 {
802         switch (size) {
803         case 1:
804                 be_emit_cstring("\t.byte\t");
805                 break;
806
807         case 2:
808                 be_emit_cstring("\t.short\t");
809                 break;
810
811         case 4:
812                 be_emit_cstring("\t.long\t");
813                 break;
814
815         case 8:
816                 be_emit_cstring("\t.quad\t");
817                 break;
818
819         case 10:
820         case 12:
821         case 16: /* Note: .octa does not work on mac */
822                 /* handled in arith */
823                 break;
824
825         default:
826                 panic("Try to dump a type with %u bytes", (unsigned)size);
827         }
828 }
829
830 /**
831  * Emit an atomic value.
832  *
833  * @param env   the gas output environment
834  * @param init  a node representing the atomic value (on the const code irg)
835  */
836 static void emit_atomic_init(be_gas_decl_env_t *env, ir_node *init)
837 {
838         ir_mode *mode = get_irn_mode(init);
839         int bytes     = get_mode_size_bytes(mode);
840
841         emit_size_type(bytes);
842         do_emit_atomic_init(env, init);
843         be_emit_char('\n');
844         be_emit_write_line();
845 }
846
847 /************************************************************************/
848 /* Routines to dump global variables                                    */
849 /************************************************************************/
850
851 /**
852  * Dump a string constant.
853  * No checks are made!!
854  *
855  * @param ent  The entity to dump.
856  */
857 static void emit_string_cst(const ir_entity *ent)
858 {
859         int      i, len;
860         int      output_len;
861         ir_type *type;
862         int      type_size;
863         int      remaining_space;
864
865         len        = get_compound_ent_n_values(ent);
866         output_len = len;
867         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
868                 be_emit_cstring("\t.ascii \"");
869         } else {
870                 be_emit_cstring("\t.string \"");
871                 output_len -= 1;
872         }
873
874         for (i = 0; i < output_len; ++i) {
875                 ir_node *irn;
876                 int c;
877
878                 irn = get_compound_ent_value(ent, i);
879                 c = (int) get_tarval_long(get_Const_tarval(irn));
880
881                 switch (c) {
882                 case '"' : be_emit_cstring("\\\""); break;
883                 case '\n': be_emit_cstring("\\n"); break;
884                 case '\r': be_emit_cstring("\\r"); break;
885                 case '\t': be_emit_cstring("\\t"); break;
886                 case '\\': be_emit_cstring("\\\\"); break;
887                 default  :
888                         if (isprint(c))
889                                 be_emit_char(c);
890                         else
891                                 be_emit_irprintf("\\%o", c);
892                         break;
893                 }
894         }
895         be_emit_cstring("\"\n");
896         be_emit_write_line();
897
898         type            = get_entity_type(ent);
899         type_size       = get_type_size_bytes(type);
900         remaining_space = type_size - len;
901         assert(remaining_space >= 0);
902         if (remaining_space > 0) {
903                 be_emit_irprintf("\t.space\t%d\n", remaining_space);
904         }
905 }
906
907 static void emit_string_initializer(const ir_initializer_t *initializer)
908 {
909         size_t i, len;
910
911         len = initializer->compound.n_initializers;
912         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
913                 be_emit_cstring("\t.ascii \"");
914         } else {
915                 be_emit_cstring("\t.string \"");
916                 len -= 1;
917         }
918
919         for (i = 0; i < len; ++i) {
920                 const ir_initializer_t *sub_initializer
921                         = get_initializer_compound_value(initializer, i);
922
923                 tarval *tv = get_initializer_tarval(sub_initializer);
924                 int     c  = get_tarval_long(tv);
925
926                 switch (c) {
927                 case '"' : be_emit_cstring("\\\""); break;
928                 case '\n': be_emit_cstring("\\n"); break;
929                 case '\r': be_emit_cstring("\\r"); break;
930                 case '\t': be_emit_cstring("\\t"); break;
931                 case '\\': be_emit_cstring("\\\\"); break;
932                 default  :
933                         if (isprint(c))
934                                 be_emit_char(c);
935                         else
936                                 be_emit_irprintf("\\%o", c);
937                         break;
938                 }
939         }
940         be_emit_cstring("\"\n");
941         be_emit_write_line();
942 }
943
944 enum normal_or_bitfield_kind {
945         NORMAL = 0,
946         TARVAL,
947         BITFIELD
948 };
949
950 typedef struct {
951         enum normal_or_bitfield_kind kind;
952         union {
953                 ir_node       *value;
954                 tarval        *tarval;
955                 unsigned char  bf_val;
956         } v;
957 } normal_or_bitfield;
958
959 static int is_type_variable_size(ir_type *type)
960 {
961         (void) type;
962         /* TODO */
963         return 0;
964 }
965
966 static size_t get_initializer_size(const ir_initializer_t *initializer,
967                                    ir_type *type)
968 {
969         switch (get_initializer_kind(initializer)) {
970         case IR_INITIALIZER_TARVAL:
971                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
972                 return get_type_size_bytes(type);
973         case IR_INITIALIZER_CONST:
974         case IR_INITIALIZER_NULL:
975                 return get_type_size_bytes(type);
976         case IR_INITIALIZER_COMPOUND:
977                 if (!is_type_variable_size(type)) {
978                         return get_type_size_bytes(type);
979                 } else {
980                         unsigned n_entries
981                                 = get_initializer_compound_n_entries(initializer);
982                         unsigned i;
983                         unsigned initializer_size = get_type_size_bytes(type);
984                         for (i = 0; i < n_entries; ++i) {
985                                 ir_entity *entity = get_compound_member(type, i);
986                                 ir_type   *type   = get_entity_type(entity);
987
988                                 const ir_initializer_t *sub_initializer
989                                         = get_initializer_compound_value(initializer, i);
990
991                                 unsigned offset = get_entity_offset(entity);
992                                 unsigned size   = get_initializer_size(sub_initializer, type);
993
994                                 if (offset + size > initializer_size) {
995                                         initializer_size = offset + size;
996                                 }
997                         }
998                         return initializer_size;
999                 }
1000         }
1001
1002         panic("found invalid initializer");
1003 }
1004
1005 #ifndef NDEBUG
1006 static normal_or_bitfield *glob_vals;
1007 static size_t              max_vals;
1008 #endif
1009
1010 static void emit_bitfield(normal_or_bitfield *vals, size_t offset_bits,
1011                           const ir_initializer_t *initializer, ir_type *type)
1012 {
1013         unsigned char  last_bits = 0;
1014         ir_mode       *mode      = get_type_mode(type);
1015         tarval        *tv        = NULL;
1016         unsigned char  curr_bits;
1017         int            value_len;
1018         int            j;
1019
1020         switch (get_initializer_kind(initializer)) {
1021         case IR_INITIALIZER_NULL:
1022                 return;
1023         case IR_INITIALIZER_TARVAL:
1024                 tv = get_initializer_tarval_value(initializer);
1025                 break;
1026         case IR_INITIALIZER_CONST: {
1027                 ir_node *node = get_initializer_const_value(initializer);
1028                 if (!is_Const(node)) {
1029                         panic("bitfield initializer not a Const node");
1030                 }
1031                 tv = get_Const_tarval(node);
1032                 break;
1033         }
1034         case IR_INITIALIZER_COMPOUND:
1035                 panic("bitfield initializer is compound");
1036         }
1037         if (tv == NULL) {
1038                 panic("Couldn't get numeric value for bitfield initializer");
1039         }
1040         tv = tarval_convert_to(tv, get_type_mode(type));
1041
1042         /* normalize offset */
1043         vals        += offset_bits >> 3;
1044         offset_bits &= 7;
1045         value_len    = get_mode_size_bits(mode);
1046
1047         /* combine bits with existing bits */
1048         for (j = 0; value_len + (int) offset_bits > 0; ++j) {
1049                 assert((size_t) (vals - glob_vals) + j < max_vals);
1050                 assert(vals[j].kind == BITFIELD ||
1051                                 (vals[j].kind == NORMAL && vals[j].v.value == NULL));
1052                 vals[j].kind = BITFIELD;
1053                 curr_bits    = get_tarval_sub_bits(tv, j);
1054                 vals[j].v.bf_val
1055                         |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1056                 value_len -= 8;
1057                 last_bits = curr_bits;
1058         }
1059 }
1060
1061 static void emit_ir_initializer(normal_or_bitfield *vals,
1062                                 const ir_initializer_t *initializer,
1063                                 ir_type *type)
1064 {
1065         assert((size_t) (vals - glob_vals) < max_vals);
1066
1067         switch (get_initializer_kind(initializer)) {
1068         case IR_INITIALIZER_NULL:
1069                 return;
1070         case IR_INITIALIZER_TARVAL: {
1071                 size_t i;
1072
1073                 assert(vals->kind != BITFIELD);
1074                 vals->kind     = TARVAL;
1075                 vals->v.tarval = get_initializer_tarval_value(initializer);
1076                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
1077                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1078                         vals[i].kind    = NORMAL;
1079                         vals[i].v.value = NULL;
1080                 }
1081                 return;
1082         }
1083         case IR_INITIALIZER_CONST: {
1084                 size_t i;
1085
1086                 assert(vals->kind != BITFIELD);
1087                 vals->kind    = NORMAL;
1088                 vals->v.value = get_initializer_const_value(initializer);
1089                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1090                         vals[i].kind    = NORMAL;
1091                         vals[i].v.value = NULL;
1092                 }
1093                 return;
1094         }
1095         case IR_INITIALIZER_COMPOUND: {
1096                 size_t i = 0;
1097                 size_t n = get_initializer_compound_n_entries(initializer);
1098
1099                 if (is_Array_type(type)) {
1100                         ir_type *element_type = get_array_element_type(type);
1101                         size_t   skip         = get_type_size_bytes(element_type);
1102                         size_t   alignment    = get_type_alignment_bytes(element_type);
1103                         size_t   misalign     = skip % alignment;
1104                         if (misalign != 0) {
1105                                 skip += alignment - misalign;
1106                         }
1107
1108                         for (i = 0; i < n; ++i) {
1109                                 ir_initializer_t *sub_initializer
1110                                         = get_initializer_compound_value(initializer, i);
1111
1112                                 emit_ir_initializer(vals, sub_initializer, element_type);
1113
1114                                 vals += skip;
1115                         }
1116                 } else {
1117                         size_t n_members, i;
1118                         assert(is_compound_type(type));
1119                         n_members = get_compound_n_members(type);
1120                         for (i = 0; i < n_members; ++i) {
1121                                 ir_entity        *member    = get_compound_member(type, i);
1122                                 size_t            offset    = get_entity_offset(member);
1123                                 ir_type          *subtype   = get_entity_type(member);
1124                                 ir_mode          *mode      = get_type_mode(subtype);
1125                                 ir_initializer_t *sub_initializer;
1126
1127                                 assert(i < get_initializer_compound_n_entries(initializer));
1128                                 sub_initializer
1129                                         = get_initializer_compound_value(initializer, i);
1130
1131                                 if (mode != NULL) {
1132                                         size_t offset_bits
1133                                                 = get_entity_offset_bits_remainder(member);
1134                                         size_t value_len   = get_mode_size_bits(mode);
1135
1136                                         if (offset_bits != 0 ||
1137                                                 (value_len != 8 && value_len != 16 && value_len != 32
1138                                                  && value_len != 64)) {
1139                                                 emit_bitfield(&vals[offset], offset_bits,
1140                                                               sub_initializer, subtype);
1141                                                 continue;
1142                                         }
1143                                 }
1144
1145                                 emit_ir_initializer(&vals[offset], sub_initializer, subtype);
1146                         }
1147                 }
1148
1149                 return;
1150         }
1151         }
1152         panic("invalid ir_initializer kind found");
1153 }
1154
1155 static void emit_initializer(be_gas_decl_env_t *env, const ir_entity *entity)
1156 {
1157         const ir_initializer_t *initializer = entity->initializer;
1158         ir_type                *type;
1159         normal_or_bitfield     *vals;
1160         size_t                  size;
1161         size_t                  k;
1162
1163         if (initializer_is_string_const(initializer)) {
1164                 emit_string_initializer(initializer);
1165                 return;
1166         }
1167
1168         type = get_entity_type(entity);
1169         size = get_initializer_size(initializer, type);
1170
1171         if (size == 0)
1172                 return;
1173
1174         /*
1175          * In the worst case, every initializer allocates one byte.
1176          * Moreover, initializer might be big, do not allocate on stack.
1177          */
1178         vals = XMALLOCNZ(normal_or_bitfield, size);
1179
1180 #ifndef NDEBUG
1181         glob_vals = vals;
1182         max_vals  = size;
1183 #endif
1184
1185         emit_ir_initializer(vals, initializer, type);
1186
1187         /* now write values sorted */
1188         for (k = 0; k < size; ) {
1189                 int space     = 0;
1190                 int elem_size = 1;
1191                 if (vals[k].kind == NORMAL) {
1192                         if (vals[k].v.value != NULL) {
1193                                 emit_atomic_init(env, vals[k].v.value);
1194                                 elem_size = get_mode_size_bytes(get_irn_mode(vals[k].v.value));
1195                         } else {
1196                                 elem_size = 0;
1197                         }
1198                 } else if (vals[k].kind == TARVAL) {
1199                         tarval *tv   = vals[k].v.tarval;
1200                         size_t  size = get_mode_size_bytes(get_tarval_mode(tv));
1201
1202                         assert(tv != NULL);
1203
1204                         elem_size = size;
1205                         emit_size_type(size);
1206                         emit_arith_tarval(tv, size);
1207                         be_emit_char('\n');
1208                         be_emit_write_line();
1209                 } else {
1210                         assert(vals[k].kind == BITFIELD);
1211                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1212                         be_emit_write_line();
1213                 }
1214
1215                 k += elem_size;
1216                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1217                         ++space;
1218                         ++k;
1219                 }
1220
1221                 /* a gap */
1222                 if (space > 0) {
1223                         be_emit_irprintf("\t.space\t%d\n", space);
1224                         be_emit_write_line();
1225                 }
1226         }
1227         xfree(vals);
1228 }
1229
1230 static void emit_compound_graph_init(be_gas_decl_env_t *env,
1231                                      const ir_entity *ent)
1232 {
1233         normal_or_bitfield *vals;
1234         int i, j, n;
1235         unsigned k, last_ofs;
1236
1237         if (entity_is_string_const(ent)) {
1238                 emit_string_cst(ent);
1239                 return;
1240         }
1241
1242         n = get_compound_ent_n_values(ent);
1243
1244         /* Find the initializer size. Sorrily gcc support a nasty feature:
1245            The last field of a compound may be a flexible array. This allows
1246            initializers bigger than the type size. */
1247         last_ofs = get_type_size_bytes(get_entity_type(ent));
1248         for (i = 0; i < n; ++i) {
1249                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1250                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1251                 ir_node  *value         = get_compound_ent_value(ent, i);
1252                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1253
1254                 offset += (value_len + bits_remainder + 7) >> 3;
1255
1256                 if (offset > last_ofs) {
1257                         last_ofs = offset;
1258                 }
1259         }
1260
1261         /*
1262          * In the worst case, every initializer allocates one byte.
1263          * Moreover, initializer might be big, do not allocate on stack.
1264          */
1265         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1266
1267         /* collect the values and store them at the offsets */
1268         for (i = 0; i < n; ++i) {
1269                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1270                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1271                 ir_node  *value      = get_compound_ent_value(ent, i);
1272                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1273
1274                 assert(offset_bits >= 0);
1275
1276                 if (offset_bits != 0 ||
1277                                 (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1278                         tarval *tv = get_atomic_init_tv(value);
1279                         unsigned char curr_bits, last_bits = 0;
1280                         if (tv == NULL) {
1281                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1282                                                 get_entity_ld_name(ent));
1283                         }
1284                         /* normalize offset */
1285                         offset += offset_bits >> 3;
1286                         offset_bits &= 7;
1287
1288                         for (j = 0; value_len + offset_bits > 0; ++j) {
1289                                 assert(offset + j < last_ofs);
1290                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1291                                 vals[offset + j].kind = BITFIELD;
1292                                 curr_bits = get_tarval_sub_bits(tv, j);
1293                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1294                                 value_len -= 8;
1295                                 last_bits = curr_bits;
1296                         }
1297                 } else {
1298                         int i;
1299
1300                         assert(offset < last_ofs);
1301                         assert(vals[offset].kind == NORMAL);
1302                         for (i = 1; i < value_len / 8; ++i) {
1303                                 assert(vals[offset + i].v.value == NULL);
1304                         }
1305                         vals[offset].v.value = value;
1306                 }
1307         }
1308
1309         /* now write them sorted */
1310         for (k = 0; k < last_ofs; ) {
1311                 int space = 0, skip = 0;
1312                 if (vals[k].kind == NORMAL) {
1313                         if (vals[k].v.value != NULL) {
1314                                 emit_atomic_init(env, vals[k].v.value);
1315                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1316                         } else {
1317                                 space = 1;
1318                         }
1319                 } else {
1320                         assert(vals[k].kind == BITFIELD);
1321                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1322                 }
1323
1324                 ++k;
1325                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1326                         ++space;
1327                         ++k;
1328                 }
1329                 space -= skip;
1330                 assert(space >= 0);
1331
1332                 /* a gap */
1333                 if (space > 0) {
1334                         be_emit_irprintf("\t.space\t%d\n", space);
1335                         be_emit_write_line();
1336                 }
1337         }
1338         xfree(vals);
1339 }
1340
1341 static void emit_align(unsigned p2alignment)
1342 {
1343         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1344         be_emit_write_line();
1345 }
1346
1347 static unsigned get_effective_entity_alignment(const ir_entity *entity)
1348 {
1349         unsigned alignment = get_entity_alignment(entity);
1350         if (alignment == 0) {
1351                 ir_type *type = get_entity_type(entity);
1352                 alignment     = get_type_alignment_bytes(type);
1353         }
1354         return alignment;
1355 }
1356
1357 static void emit_common(const ir_entity *entity)
1358 {
1359         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1360         unsigned alignment = get_effective_entity_alignment(entity);
1361
1362         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1363                 emit_weak(entity);
1364         }
1365
1366         switch (be_gas_object_file_format) {
1367         case OBJECT_FILE_FORMAT_MACH_O:
1368                 be_emit_cstring("\t.comm ");
1369                 be_gas_emit_entity(entity);
1370                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1371                 be_emit_write_line();
1372                 return;
1373         case OBJECT_FILE_FORMAT_ELF:
1374         case OBJECT_FILE_FORMAT_ELF_SPARC:
1375                 be_emit_cstring("\t.comm ");
1376                 be_gas_emit_entity(entity);
1377                 be_emit_irprintf(",%u,%u\n", size, alignment);
1378                 be_emit_write_line();
1379                 return;
1380         case OBJECT_FILE_FORMAT_COFF:
1381                 be_emit_cstring("\t.comm ");
1382                 be_gas_emit_entity(entity);
1383                 be_emit_irprintf(",%u # %u\n", size, alignment);
1384                 be_emit_write_line();
1385                 return;
1386         }
1387         panic("invalid object file format");
1388 }
1389
1390 static void emit_local_common(const ir_entity *entity)
1391 {
1392         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1393         unsigned alignment = get_effective_entity_alignment(entity);
1394
1395         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1396                 emit_weak(entity);
1397         }
1398
1399         switch (be_gas_object_file_format) {
1400         case OBJECT_FILE_FORMAT_MACH_O:
1401                 be_emit_cstring("\t.lcomm ");
1402                 be_gas_emit_entity(entity);
1403                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1404                 be_emit_write_line();
1405                 return;
1406         case OBJECT_FILE_FORMAT_ELF:
1407         case OBJECT_FILE_FORMAT_ELF_SPARC:
1408                 be_emit_cstring("\t.local ");
1409                 be_gas_emit_entity(entity);
1410                 be_emit_cstring("\n");
1411                 be_emit_write_line();
1412                 be_emit_cstring("\t.comm ");
1413                 be_gas_emit_entity(entity);
1414                 be_emit_irprintf(",%u,%u\n", size, alignment);
1415                 be_emit_write_line();
1416                 return;
1417         case OBJECT_FILE_FORMAT_COFF:
1418                 be_emit_cstring("\t.lcomm ");
1419                 be_gas_emit_entity(entity);
1420                 be_emit_irprintf(",%u # %u\n", size, alignment);
1421                 be_emit_write_line();
1422                 return;
1423         }
1424         panic("invalid object file format");
1425 }
1426
1427 static void emit_indirect_symbol(const ir_entity *entity, be_gas_section_t section)
1428 {
1429         /* we can only do PIC code on macho so far */
1430         assert(be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O);
1431
1432         be_gas_emit_entity(entity);
1433         be_emit_cstring(":\n");
1434         be_emit_write_line();
1435         be_emit_cstring("\t.indirect_symbol ");
1436         be_emit_ident(get_entity_ident(entity));
1437         be_emit_char('\n');
1438         be_emit_write_line();
1439         if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1440                 be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1441                 be_emit_write_line();
1442         } else {
1443                 assert(section == GAS_SECTION_PIC_SYMBOLS);
1444                 be_emit_cstring("\t.long 0\n");
1445                 be_emit_write_line();
1446         }
1447 }
1448
1449 char const *be_gas_get_private_prefix(void)
1450 {
1451         return be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O ? "L" : ".L";
1452 }
1453
1454 void be_gas_emit_entity(const ir_entity *entity)
1455 {
1456         if (entity->type == firm_code_type) {
1457                 ir_label_t label = get_entity_label(entity);
1458                 be_emit_irprintf("%s_%lu", be_gas_get_private_prefix(), label);
1459                 return;
1460         }
1461
1462         if (get_entity_visibility(entity) == ir_visibility_private) {
1463                 be_emit_string(be_gas_get_private_prefix());
1464         }
1465         be_emit_ident(get_entity_ld_ident(entity));
1466 }
1467
1468 void be_gas_emit_block_name(const ir_node *block)
1469 {
1470         if (has_Block_entity(block)) {
1471                 ir_entity *entity = get_Block_entity(block);
1472                 be_gas_emit_entity(entity);
1473         } else {
1474                 be_emit_irprintf("%s%ld", be_gas_get_private_prefix(), get_irn_node_nr(block));
1475         }
1476 }
1477
1478 /**
1479  * Dump a global entity.
1480  *
1481  * @param env  the gas output environment
1482  * @param ent  the entity to be dumped
1483  */
1484 static void emit_global(be_gas_decl_env_t *env, const ir_entity *entity)
1485 {
1486         ir_type          *type       = get_entity_type(entity);
1487         ident            *ld_ident   = get_entity_ld_ident(entity);
1488         unsigned          alignment  = get_effective_entity_alignment(entity);
1489         be_gas_section_t  section    = determine_section(env, entity);
1490         ir_visibility     visibility = get_entity_visibility(entity);
1491         ir_linkage        linkage    = get_entity_linkage(entity);
1492
1493         /* block labels are already emittet in the code */
1494         if (type == firm_code_type)
1495                 return;
1496
1497         /* we already emitted all methods. Except for the trampolines which
1498          * the assembler/linker generates */
1499         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1500                 /* functions with graph are already emitted with
1501                  * be_gas_emit_function_prolog */
1502                 if (get_entity_irg(entity) == NULL) {
1503                         emit_visibility(entity);
1504                 }
1505                 return;
1506         }
1507
1508         be_dbg_variable(entity);
1509
1510         if (section == GAS_SECTION_BSS) {
1511                 ir_visibility visibility = get_entity_visibility(entity);
1512
1513                 switch (visibility) {
1514                 case ir_visibility_local:
1515                 case ir_visibility_private:
1516                         emit_local_common(entity);
1517                         return;
1518                 case ir_visibility_default:
1519                         if (linkage & IR_LINKAGE_MERGE) {
1520                                 emit_common(entity);
1521                                 return;
1522                         }
1523                         break;
1524                 case ir_visibility_external:
1525                         if (linkage & IR_LINKAGE_MERGE)
1526                                 panic("merge link semantic not supported for extern entities");
1527                         break;
1528                 }
1529         }
1530
1531         emit_visibility(entity);
1532         if (visibility == ir_visibility_external) {
1533                 /* nothing to do for externally defined values */
1534                 return;
1535         }
1536
1537         if (!is_po2(alignment))
1538                 panic("alignment not a power of 2");
1539
1540         emit_section(section, entity);
1541
1542         if (section == GAS_SECTION_PIC_TRAMPOLINES
1543                         || section == GAS_SECTION_PIC_SYMBOLS) {
1544                 emit_indirect_symbol(entity, section);
1545                 return;
1546         }
1547
1548         /* alignment */
1549         if (alignment > 1) {
1550                 emit_align(alignment);
1551         }
1552         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF
1553                         && be_gas_emit_types) {
1554                 be_emit_cstring("\t.type\t");
1555                 be_gas_emit_entity(entity);
1556                 be_emit_cstring(", ");
1557                 be_emit_char(be_gas_elf_type_char);
1558                 be_emit_cstring("object\n\t.size\t");\
1559                 be_gas_emit_entity(entity);
1560                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1561         }
1562
1563         if (get_id_str(ld_ident)[0] != '\0') {
1564             be_gas_emit_entity(entity);
1565                 be_emit_cstring(":\n");
1566                 be_emit_write_line();
1567         }
1568
1569         if (entity_is_null(entity)) {
1570                 be_emit_irprintf("\t.space %u\n", get_type_size_bytes(type));
1571                 be_emit_write_line();
1572         } else if (entity_has_compound_ent_values(entity)) {
1573                 emit_compound_graph_init(env, entity);
1574         } else {
1575                 assert(entity->initializer != NULL);
1576                 emit_initializer(env, entity);
1577         }
1578 }
1579
1580 /**
1581  * Dumps declarations of global variables and the initialization code.
1582  *
1583  * @param gt                a global like type, either the global or the TLS one
1584  * @param env               an environment
1585  */
1586 static void be_gas_emit_globals(ir_type *gt, be_gas_decl_env_t *env)
1587 {
1588         int i, n = get_compound_n_members(gt);
1589
1590         for (i = 0; i < n; i++) {
1591                 ir_entity *ent = get_compound_member(gt, i);
1592                 emit_global(env, ent);
1593         }
1594 }
1595
1596 /************************************************************************/
1597
1598 /* Generate all entities. */
1599 void be_gas_emit_decls(const be_main_env_t *main_env)
1600 {
1601         be_gas_decl_env_t env;
1602         memset(&env, 0, sizeof(env));
1603
1604         /* dump global type */
1605         env.main_env = main_env;
1606         env.section  = (be_gas_section_t) -1;
1607
1608         be_gas_emit_globals(get_glob_type(), &env);
1609         be_gas_emit_globals(get_tls_type(), &env);
1610         be_gas_emit_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env);
1611         be_gas_emit_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env);
1612         be_gas_emit_globals(main_env->pic_symbols_type, &env);
1613         be_gas_emit_globals(main_env->pic_trampolines_type, &env);
1614
1615         /**
1616          * ".subsections_via_symbols marks object files which are OK to divide
1617          * their section contents into individual blocks".
1618          * From my understanding this means no label points in the middle of an
1619          * object which we want to address as a whole. Firm code should be fine
1620          * with this.
1621          */
1622         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
1623                 be_emit_cstring("\t.subsections_via_symbols\n");
1624                 be_emit_write_line();
1625         }
1626 }