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