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