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