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