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