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