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