ab641c67e25726bb6b19159240a00554aa6885c2
[libfirm] / ir / be / begnuas.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Dumps global variables and constants as gas assembler.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @date        04.11.2005
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include "begnuas.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <assert.h>
35
36 #include "obst.h"
37 #include "tv.h"
38 #include "irnode.h"
39 #include "irprog.h"
40 #include "entity_t.h"
41 #include "error.h"
42 #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 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                 default: panic("unsupported scetion type 0x%X", section);
89                 }
90                 be_emit_irprintf("\t.%s\n", name);
91                 be_emit_write_line();
92         } else if (flags & GAS_SECTION_FLAG_COMDAT) {
93                 switch (base) {
94                 case GAS_SECTION_TEXT:            name = "section __TEXT,__textcoal_nt,coalesced,pure_instructions"; break;
95                 case GAS_SECTION_BSS:
96                 case GAS_SECTION_DATA:            name = "section __DATA,__datacoal_nt,coalesced"; break;
97                 case GAS_SECTION_RODATA:          name = "section __TEXT,__const_coal,coalesced"; break;
98                 case GAS_SECTION_CSTRING:         name = "section __TEXT,__const_coal,coalesced"; break;
99                 default: panic("unsupported scetion type 0x%X", section);
100                 }
101         } else {
102                 panic("unsupported section type 0x%X\n", section);
103         }
104 }
105
106 static void emit_section_sparc(be_gas_section_t section, const ir_entity *entity)
107 {
108         be_gas_section_t base = section & GAS_SECTION_TYPE_MASK;
109         be_gas_section_t flags = section & ~GAS_SECTION_TYPE_MASK;
110         static const char *const basename[] = {
111                 "text", "data", "rodata", "bss", "ctors", "dtors"
112         };
113
114         if (current_section == section && !(section & GAS_SECTION_FLAG_COMDAT))
115                 return;
116         current_section = section;
117
118         be_emit_cstring("\t.section\t\".");
119
120         /* Part1: section-name */
121         if (flags & GAS_SECTION_FLAG_TLS)
122                 be_emit_char('t');
123         assert(base < (be_gas_section_t)ARRAY_SIZE(basename));
124         be_emit_string(basename[base]);
125
126         if (flags & GAS_SECTION_FLAG_COMDAT) {
127                 be_emit_char('.');
128                 be_gas_emit_entity(entity);
129         }
130         be_emit_char('"');
131
132         /* for the simple sections we're done here */
133         if (flags == 0)
134                 goto end;
135
136         be_emit_cstring(",#alloc");
137
138         switch (base) {
139         case GAS_SECTION_TEXT: be_emit_cstring(",#execinstr"); break;
140         case GAS_SECTION_DATA:
141         case GAS_SECTION_BSS:  be_emit_cstring(",#write"); break;
142         default:
143                 /* nothing */
144                 break;
145         }
146         if (flags & GAS_SECTION_FLAG_TLS) {
147                 be_emit_cstring(",#tls");
148         }
149
150 end:
151         be_emit_char('\n');
152         be_emit_write_line();
153 }
154
155 static void emit_section(be_gas_section_t section, const ir_entity *entity)
156 {
157         be_gas_section_t base = section & GAS_SECTION_TYPE_MASK;
158         be_gas_section_t flags = section & ~GAS_SECTION_TYPE_MASK;
159         static const char *const basename[] = {
160                 "text", "data", "rodata", "bss", "ctors", "dtors"
161         };
162         static const char *const type[] = {
163                 "progbits", "progbits", "progbits", "nobits", "init_array", "fini_array"
164         };
165
166         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
167                 emit_section_macho(section);
168                 return;
169         } else if(be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF_SPARC) {
170                 emit_section_sparc(section, entity);
171                 return;
172         }
173
174         if (current_section == section && !(section & GAS_SECTION_FLAG_COMDAT))
175                 return;
176         current_section = section;
177
178         /* shortforms */
179         if (flags == 0) {
180                 switch (base) {
181                 case GAS_SECTION_TEXT:
182                         be_emit_cstring("\t.text\n");
183                         be_emit_write_line();
184                         return;
185                 case GAS_SECTION_DATA:
186                         be_emit_cstring("\t.data\n");
187                         be_emit_write_line();
188                         return;
189                 case GAS_SECTION_RODATA:
190                         be_emit_cstring("\t.section\t.rodata\n");
191                         be_emit_write_line();
192                         return;
193                 case GAS_SECTION_BSS:
194                         be_emit_cstring("\t.bss\n");
195                         be_emit_write_line();
196                         return;
197                 default:
198                         break;
199                 }
200         }
201
202         assert(base < (be_gas_section_t) ARRAY_SIZE(basename));
203         be_emit_cstring("\t.section\t.");
204         /* section name */
205         if (flags & GAS_SECTION_FLAG_TLS)
206                 be_emit_char('t');
207         be_emit_string(basename[base]);
208         if (flags & GAS_SECTION_FLAG_COMDAT) {
209                 be_emit_char('.');
210                 be_gas_emit_entity(entity);
211         }
212
213         /* section flags */
214         be_emit_cstring(",\"");
215         if (be_gas_object_file_format != OBJECT_FILE_FORMAT_COFF)
216                 be_emit_char('a');
217         if (base == GAS_SECTION_TEXT)
218                 be_emit_char('x');
219         if (base != GAS_SECTION_RODATA && base != GAS_SECTION_TEXT)
220                 be_emit_char('w');
221         if (flags & GAS_SECTION_FLAG_TLS)
222                 be_emit_char('T');
223         if (flags & GAS_SECTION_FLAG_COMDAT)
224                 be_emit_char('G');
225         /* section type */
226         if (be_gas_object_file_format != OBJECT_FILE_FORMAT_COFF) {
227                 be_emit_cstring("\",");
228                 be_emit_char(be_gas_elf_type_char);
229                 be_emit_string(type[base]);
230         }
231
232         if (flags & GAS_SECTION_FLAG_COMDAT) {
233                 be_emit_char(',');
234                 be_gas_emit_entity(entity);
235                 be_emit_cstring(",comdat");
236         }
237         be_emit_char('\n');
238         be_emit_write_line();
239 }
240
241
242
243 void be_gas_emit_switch_section(be_gas_section_t section)
244 {
245         /* you have to produce a switch_section call with entity manually
246          * for comdat sections */
247         assert( !(section & GAS_SECTION_FLAG_COMDAT));
248
249         emit_section(section, NULL);
250 }
251
252 static ir_tarval *get_initializer_tarval(const ir_initializer_t *initializer)
253 {
254         if (initializer->kind == IR_INITIALIZER_TARVAL)
255                 return initializer->tarval.value;
256         if (initializer->kind == IR_INITIALIZER_CONST) {
257                 ir_node *node = initializer->consti.value;
258                 if (is_Const(node)) {
259                         return get_Const_tarval(node);
260                 }
261         }
262         return get_tarval_undefined();
263 }
264
265 static bool initializer_is_string_const(const ir_initializer_t *initializer)
266 {
267         size_t i, len;
268         bool found_printable = false;
269
270         if (initializer->kind != IR_INITIALIZER_COMPOUND)
271                 return false;
272
273         len = initializer->compound.n_initializers;
274         if (len < 1)
275                 return false;
276         for (i = 0; i < len; ++i) {
277                 int               c;
278                 ir_tarval        *tv;
279                 ir_mode          *mode;
280                 ir_initializer_t *sub_initializer
281                         = initializer->compound.initializers[i];
282
283                 tv = get_initializer_tarval(sub_initializer);
284                 if (!tarval_is_constant(tv))
285                         return false;
286
287                 mode = get_tarval_mode(tv);
288                 if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
289                         return false;
290
291                 c = get_tarval_long(tv);
292                 if (isgraph(c) || isspace(c))
293                         found_printable = true;
294                 else if (c != 0)
295                         return false;
296
297                 if (i == len - 1 && c != '\0')
298                         return false;
299         }
300
301         return found_printable;
302 }
303
304 static bool initializer_is_null(const ir_initializer_t *initializer)
305 {
306         switch (initializer->kind) {
307         case IR_INITIALIZER_NULL:
308                 return true;
309         case IR_INITIALIZER_TARVAL: {
310                 ir_tarval *tv = initializer->tarval.value;
311                 return tarval_is_null(tv);
312         }
313         case IR_INITIALIZER_CONST: {
314                 ir_node *value = initializer->consti.value;
315                 if (!is_Const(value))
316                         return false;
317                 return is_Const_null(value);
318         }
319         case IR_INITIALIZER_COMPOUND: {
320                 size_t i;
321                 for (i = 0; i < initializer->compound.n_initializers; ++i) {
322                         ir_initializer_t *subinitializer
323                                 = initializer->compound.initializers[i];
324                         if (!initializer_is_null(subinitializer))
325                                 return false;
326                 }
327                 return true;
328         }
329         }
330         panic("invalid initializer in initializer_is_null");
331 }
332
333 /**
334  * Determine if an entity is a string constant
335  * @param ent The entity
336  * @return 1 if it is a string constant, 0 otherwise
337  */
338 static int entity_is_string_const(const ir_entity *ent)
339 {
340         ir_type *type, *element_type;
341         ir_mode *mode;
342         int i, c, n;
343
344         type = get_entity_type(ent);
345
346         /* if it's an array */
347         if (!is_Array_type(type))
348                 return 0;
349
350         element_type = get_array_element_type(type);
351
352         /* and the array's element type is primitive */
353         if (!is_Primitive_type(element_type))
354                 return 0;
355
356         /* and the mode of the element type is an int of
357          * the same size as the byte mode */
358         mode = get_type_mode(element_type);
359         if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
360                 return 0;
361
362         if (ent->initializer != NULL) {
363                 return initializer_is_string_const(ent->initializer);
364         } else if (entity_has_compound_ent_values(ent)) {
365                 int found_printable = 0;
366                 /* if it contains only printable chars and a 0 at the end */
367                 n = get_compound_ent_n_values(ent);
368                 for (i = 0; i < n; ++i) {
369                         ir_node *irn = get_compound_ent_value(ent, i);
370                         if (! is_Const(irn))
371                                 return 0;
372
373                         c = (int) get_tarval_long(get_Const_tarval(irn));
374
375                         if (isgraph(c) || isspace(c))
376                                 found_printable = 1;
377                         else if (c != 0)
378                                 return 0;
379
380                         if (i == n - 1 && c != '\0')
381                                 return 0;
382                 }
383                 return found_printable;
384         }
385
386         return 0;
387 }
388
389 static bool entity_is_null(const ir_entity *entity)
390 {
391         if (entity->initializer != NULL) {
392                 return initializer_is_null(entity->initializer);
393         } else if (entity_has_compound_ent_values(entity)) {
394                 /* I'm too lazy to implement this case as compound graph paths will be
395                  * remove anyway in the future */
396                 return false;
397         }
398         /* uninitialized, NULL is fine */
399         return true;
400 }
401
402 static bool is_comdat(const ir_entity *entity)
403 {
404         ir_linkage linkage = get_entity_linkage(entity);
405         return (linkage & IR_LINKAGE_MERGE)
406                 && (linkage & IR_LINKAGE_GARBAGE_COLLECT);
407 }
408
409 static be_gas_section_t determine_basic_section(const ir_entity *entity)
410 {
411         ir_linkage linkage;
412
413         if (is_method_entity(entity))
414                 return GAS_SECTION_TEXT;
415
416         linkage = get_entity_linkage(entity);
417         if (linkage & IR_LINKAGE_CONSTANT) {
418                 /* mach-o is the only one with a cstring section */
419                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
420                                 && entity_is_string_const(entity))
421                         return GAS_SECTION_CSTRING;
422
423                 return GAS_SECTION_RODATA;
424         }
425         if (entity_is_null(entity))
426                 return GAS_SECTION_BSS;
427
428         return GAS_SECTION_DATA;
429 }
430
431 static be_gas_section_t determine_section(be_gas_decl_env_t *env,
432                                           const ir_entity *entity)
433 {
434         ir_type *owner = get_entity_owner(entity);
435
436         if (owner == get_segment_type(IR_SEGMENT_GLOBAL)) {
437                 be_gas_section_t section = determine_basic_section(entity);
438                 if (is_comdat(entity))
439                         section |= GAS_SECTION_FLAG_COMDAT;
440                 return section;
441         } else if (env != NULL && owner == env->main_env->pic_symbols_type) {
442                 return GAS_SECTION_PIC_SYMBOLS;
443         } else if (env != NULL && owner == env->main_env->pic_trampolines_type) {
444                 return GAS_SECTION_PIC_TRAMPOLINES;
445         } else if (owner == get_segment_type(IR_SEGMENT_CONSTRUCTORS)) {
446                 return GAS_SECTION_CONSTRUCTORS;
447         } else if (owner == get_segment_type(IR_SEGMENT_DESTRUCTORS)) {
448                 return GAS_SECTION_DESTRUCTORS;
449         } else if (owner == get_segment_type(IR_SEGMENT_THREAD_LOCAL)) {
450                 be_gas_section_t section = determine_basic_section(entity);
451                 if (is_comdat(entity))
452                         section |= GAS_SECTION_FLAG_COMDAT;
453
454                 return section | GAS_SECTION_FLAG_TLS;
455         }
456
457         /* the java frontend keeps some functions inside classes */
458         if (is_Class_type(owner)) {
459                 return determine_basic_section(entity);
460         }
461
462         panic("Couldn't determine section for %+F?!?", entity);
463 }
464
465 static void emit_weak(const ir_entity *entity)
466 {
467         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
468                 be_emit_cstring("\t.weak_reference ");
469         } else {
470                 be_emit_cstring("\t.weak ");
471         }
472         be_gas_emit_entity(entity);
473         be_emit_char('\n');
474         be_emit_write_line();
475 }
476
477 static void emit_visibility(const ir_entity *entity)
478 {
479         ir_linkage linkage = get_entity_linkage(entity);
480
481         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
482                 emit_weak(entity);
483                 /* Note: .weak seems to imply .globl so no need to output .globl */
484         } else if (get_entity_visibility(entity) == ir_visibility_default) {
485                 be_emit_cstring(".globl ");
486                 be_gas_emit_entity(entity);
487                 be_emit_char('\n');
488                 be_emit_write_line();
489         }
490
491         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
492                         && (linkage & IR_LINKAGE_HIDDEN_USER)) {
493                 be_emit_cstring("\t.no_dead_strip ");
494                 be_gas_emit_entity(entity);
495                 be_emit_char('\n');
496                 be_emit_write_line();
497         }
498 }
499
500 void be_gas_emit_function_prolog(const ir_entity *entity, unsigned po2alignment)
501 {
502         be_gas_section_t section = determine_section(NULL, entity);
503         emit_section(section, entity);
504
505         /* write the begin line (makes the life easier for scripts parsing the
506          * assembler) */
507         be_emit_write_line();
508         be_emit_cstring("# -- Begin  ");
509         be_gas_emit_entity(entity);
510         be_emit_char('\n');
511         be_emit_write_line();
512
513         if (po2alignment > 0) {
514                 const char *fill_byte = "";
515                 unsigned    maximum_skip = (1 << po2alignment) - 1;
516                 /* gcc fills space between function with 0x90... */
517                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
518                         fill_byte = "0x90";
519                 }
520                 be_emit_cstring("\t.p2align ");
521                 be_emit_irprintf("%u,%s,%u\n", po2alignment, fill_byte, maximum_skip);
522                 be_emit_write_line();
523         }
524         emit_visibility(entity);
525
526         switch (be_gas_object_file_format) {
527         case OBJECT_FILE_FORMAT_ELF:
528         case OBJECT_FILE_FORMAT_ELF_SPARC:
529                 be_emit_cstring("\t.type\t");
530                 be_gas_emit_entity(entity);
531                 be_emit_cstring(", ");
532                 be_emit_char(be_gas_elf_type_char);
533                 be_emit_cstring("function\n");
534                 be_emit_write_line();
535                 break;
536         case OBJECT_FILE_FORMAT_COFF:
537                 be_emit_cstring("\t.def\t");
538                 be_gas_emit_entity(entity);
539                 be_emit_cstring(";");
540                 if (get_entity_visibility(entity) == ir_visibility_local) {
541                         be_emit_cstring("\t.scl\t3;");
542                 } else {
543                         be_emit_cstring("\t.scl\t2;");
544                 }
545                 be_emit_cstring("\t.type\t32;\t.endef\n");
546                 be_emit_write_line();
547                 break;
548         case OBJECT_FILE_FORMAT_MACH_O:
549                 break;
550         }
551         be_gas_emit_entity(entity);
552         be_emit_cstring(":\n");
553         be_emit_write_line();
554 }
555
556 void be_gas_emit_function_epilog(const ir_entity *entity)
557 {
558         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF) {
559                 be_emit_cstring("\t.size\t");
560                 be_gas_emit_entity(entity);
561                 be_emit_cstring(", .-");
562                 be_gas_emit_entity(entity);
563                 be_emit_char('\n');
564                 be_emit_write_line();
565         }
566
567         be_emit_cstring("# -- End  ");
568         be_gas_emit_entity(entity);
569         be_emit_char('\n');
570         be_emit_write_line();
571 }
572
573 /**
574  * Output a tarval.
575  *
576  * @param tv     the tarval
577  * @param bytes  the width of the tarvals value in bytes
578  */
579 static void emit_arith_tarval(ir_tarval *tv, int bytes)
580 {
581         switch (bytes) {
582         case 1:
583                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
584                 return;
585
586         case 2:
587                 be_emit_irprintf("0x%02x%02x", get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
588                 return;
589
590         case 4:
591                 be_emit_irprintf("0x%02x%02x%02x%02x",
592                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
593                 return;
594
595         case 8:
596                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
597                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6), get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
598                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
599                 return;
600
601         case 12:
602                 /* Beware: Mixed endian output!  One little endian number emitted as
603                  * three longs.  Each long initializer is written in big endian. */
604                 be_emit_irprintf(
605                         "\t.long\t0x%02x%02x%02x%02x\n"
606                         "\t.long\t0x%02x%02x%02x%02x\n"
607                         "\t.long\t0x%02x%02x%02x%02x",
608                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
609                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
610                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
611                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
612                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
613                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
614                 );
615                 return;
616
617         case 16:
618                 /* Beware: Mixed endian output!  One little endian number emitted as
619                  * three longs.  Each long initializer is written in big endian. */
620                 be_emit_irprintf(
621                         "\t.long\t0x%02x%02x%02x%02x\n"
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",
625                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
626                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
627                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
628                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
629                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
630                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
631                         get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 14),
632                         get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12)
633                 );
634                 return;
635         }
636
637         panic("Can't dump a tarval with %d bytes", bytes);
638 }
639
640 /**
641  * Return the label prefix for labeled instructions.
642  */
643 const char *be_gas_insn_label_prefix(void)
644 {
645         return ".LE";
646 }
647
648 /**
649  * Return the tarval of an atomic initializer.
650  *
651  * @param init  a node representing the initializer (on the const code irg)
652  *
653  * @return the tarval
654  */
655 static ir_tarval *get_atomic_init_tv(ir_node *init)
656 {
657         for (;;) {
658                 ir_mode *mode = get_irn_mode(init);
659
660                 switch (get_irn_opcode(init)) {
661
662                 case iro_Cast:
663                         init = get_Cast_op(init);
664                         continue;
665
666                 case iro_Conv:
667                         init = get_Conv_op(init);
668                         continue;
669
670                 case iro_Const:
671                         return get_Const_tarval(init);
672
673                 case iro_SymConst:
674                         switch (get_SymConst_kind(init)) {
675                         case symconst_type_size:
676                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
677
678                         case symconst_type_align:
679                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
680
681                         case symconst_ofs_ent:
682                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
683
684                         case symconst_enum_const:
685                                 return get_enumeration_value(get_SymConst_enum(init));
686
687                         default:
688                                 return NULL;
689                         }
690
691                 default:
692                         return NULL;
693                 }
694         }
695 }
696
697 /**
698  * Dump an atomic value.
699  *
700  * @param env   the gas output environment
701  * @param init  a node representing the atomic value (on the const code irg)
702  */
703 static void do_emit_atomic_init(be_gas_decl_env_t *env, ir_node *init)
704 {
705         ir_mode *mode = get_irn_mode(init);
706         int bytes     = get_mode_size_bytes(mode);
707         ir_tarval *tv;
708         ir_entity *ent;
709
710         init = skip_Id(init);
711
712         switch (get_irn_opcode(init)) {
713         case iro_Cast:
714                 do_emit_atomic_init(env, get_Cast_op(init));
715                 return;
716
717         case iro_Conv:
718                 do_emit_atomic_init(env, get_Conv_op(init));
719                 return;
720
721         case iro_Const:
722                 tv = get_Const_tarval(init);
723
724                 /* it's a arithmetic value */
725                 emit_arith_tarval(tv, bytes);
726                 return;
727
728         case iro_SymConst:
729                 switch (get_SymConst_kind(init)) {
730                 case symconst_addr_ent:
731                         ent = get_SymConst_entity(init);
732                         be_gas_emit_entity(ent);
733                         break;
734
735                 case symconst_ofs_ent:
736                         ent = get_SymConst_entity(init);
737                         be_emit_irprintf("%d", get_entity_offset(ent));
738                         break;
739
740                 case symconst_type_size:
741                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
742                         break;
743
744                 case symconst_type_align:
745                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
746                         break;
747
748                 case symconst_enum_const:
749                         tv = get_enumeration_value(get_SymConst_enum(init));
750                         emit_arith_tarval(tv, bytes);
751                         break;
752
753                 default:
754                         assert(!"emit_atomic_init(): don't know how to init from this SymConst");
755                 }
756                 return;
757
758         case iro_Add:
759                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
760                         panic("Constant must be int or pointer for '+' to work");
761                 }
762                 do_emit_atomic_init(env, get_Add_left(init));
763                 be_emit_cstring(" + ");
764                 do_emit_atomic_init(env, get_Add_right(init));
765                 return;
766
767         case iro_Sub:
768                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
769                         panic("Constant must be int or pointer for '-' to work");
770                 }
771                 do_emit_atomic_init(env, get_Sub_left(init));
772                 be_emit_cstring(" - ");
773                 do_emit_atomic_init(env, get_Sub_right(init));
774                 return;
775
776         case iro_Mul:
777                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
778                         panic("Constant must be int or pointer for '*' to work");
779                 }
780                 do_emit_atomic_init(env, get_Mul_left(init));
781                 be_emit_cstring(" * ");
782                 do_emit_atomic_init(env, get_Mul_right(init));
783                 return;
784
785         case iro_Unknown:
786                 be_emit_cstring("0");
787                 return;
788
789         default:
790                 panic("emit_atomic_init(): unsupported IR-node %+F", init);
791         }
792 }
793
794 /**
795  * Dumps the type for given size (.byte, .long, ...)
796  *
797  * @param size  the size in bytes
798  */
799 static void emit_size_type(size_t size)
800 {
801         switch (size) {
802         case 1:
803                 be_emit_cstring("\t.byte\t");
804                 break;
805
806         case 2:
807                 be_emit_cstring("\t.short\t");
808                 break;
809
810         case 4:
811                 be_emit_cstring("\t.long\t");
812                 break;
813
814         case 8:
815                 be_emit_cstring("\t.quad\t");
816                 break;
817
818         case 10:
819         case 12:
820         case 16: /* Note: .octa does not work on mac */
821                 /* handled in arith */
822                 break;
823
824         default:
825                 panic("Try to dump a type with %u bytes", (unsigned)size);
826         }
827 }
828
829 /**
830  * Emit an atomic value.
831  *
832  * @param env   the gas output environment
833  * @param init  a node representing the atomic value (on the const code irg)
834  */
835 static void emit_atomic_init(be_gas_decl_env_t *env, ir_node *init)
836 {
837         ir_mode *mode = get_irn_mode(init);
838         int bytes     = get_mode_size_bytes(mode);
839
840         emit_size_type(bytes);
841         do_emit_atomic_init(env, init);
842         be_emit_char('\n');
843         be_emit_write_line();
844 }
845
846 /**
847  * Dump a string constant.
848  * No checks are made!!
849  *
850  * @param ent  The entity to dump.
851  */
852 static void emit_string_cst(const ir_entity *ent)
853 {
854         int      i, len;
855         int      output_len;
856         ir_type *type;
857         int      type_size;
858         int      remaining_space;
859
860         len        = get_compound_ent_n_values(ent);
861         output_len = len;
862         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
863                 be_emit_cstring("\t.ascii \"");
864         } else {
865                 be_emit_cstring("\t.string \"");
866                 output_len -= 1;
867         }
868
869         for (i = 0; i < output_len; ++i) {
870                 ir_node *irn;
871                 int c;
872
873                 irn = get_compound_ent_value(ent, i);
874                 c = (int) get_tarval_long(get_Const_tarval(irn));
875
876                 switch (c) {
877                 case '"' : be_emit_cstring("\\\""); break;
878                 case '\n': be_emit_cstring("\\n"); break;
879                 case '\r': be_emit_cstring("\\r"); break;
880                 case '\t': be_emit_cstring("\\t"); break;
881                 case '\\': be_emit_cstring("\\\\"); break;
882                 default  :
883                         if (isprint(c))
884                                 be_emit_char(c);
885                         else
886                                 be_emit_irprintf("\\%o", c);
887                         break;
888                 }
889         }
890         be_emit_cstring("\"\n");
891         be_emit_write_line();
892
893         type            = get_entity_type(ent);
894         type_size       = get_type_size_bytes(type);
895         remaining_space = type_size - len;
896         assert(remaining_space >= 0);
897         if (remaining_space > 0) {
898                 be_emit_irprintf("\t.space\t%d, 0\n", remaining_space);
899         }
900 }
901
902 static size_t emit_string_initializer(const ir_initializer_t *initializer)
903 {
904         size_t i, len;
905
906         len = initializer->compound.n_initializers;
907         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
908                 be_emit_cstring("\t.ascii \"");
909         } else {
910                 be_emit_cstring("\t.string \"");
911                 len -= 1;
912         }
913
914         for (i = 0; i < len; ++i) {
915                 const ir_initializer_t *sub_initializer
916                         = get_initializer_compound_value(initializer, i);
917
918                 ir_tarval *tv = get_initializer_tarval(sub_initializer);
919                 int        c  = get_tarval_long(tv);
920
921                 switch (c) {
922                 case '"' : be_emit_cstring("\\\""); break;
923                 case '\n': be_emit_cstring("\\n"); break;
924                 case '\r': be_emit_cstring("\\r"); break;
925                 case '\t': be_emit_cstring("\\t"); break;
926                 case '\\': be_emit_cstring("\\\\"); break;
927                 default  :
928                         if (isprint(c))
929                                 be_emit_char(c);
930                         else
931                                 be_emit_irprintf("\\%o", c);
932                         break;
933                 }
934         }
935         be_emit_cstring("\"\n");
936         be_emit_write_line();
937
938         return initializer->compound.n_initializers;
939 }
940
941 typedef enum normal_or_bitfield_kind {
942         NORMAL = 0,
943         TARVAL,
944         STRING,
945         BITFIELD
946 } normal_or_bitfield_kind;
947
948 typedef struct {
949         normal_or_bitfield_kind kind;
950         union {
951                 ir_node                *value;
952                 ir_tarval              *tarval;
953                 unsigned char           bf_val;
954                 const ir_initializer_t *string;
955         } v;
956 } normal_or_bitfield;
957
958 static int is_type_variable_size(ir_type *type)
959 {
960         (void) type;
961         /* TODO */
962         return 0;
963 }
964
965 static size_t get_initializer_size(const ir_initializer_t *initializer,
966                                    ir_type *type)
967 {
968         switch (get_initializer_kind(initializer)) {
969         case IR_INITIALIZER_TARVAL:
970                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
971                 return get_type_size_bytes(type);
972         case IR_INITIALIZER_CONST:
973         case IR_INITIALIZER_NULL:
974                 return get_type_size_bytes(type);
975         case IR_INITIALIZER_COMPOUND:
976                 if (!is_type_variable_size(type)) {
977                         return get_type_size_bytes(type);
978                 } else {
979                         unsigned n_entries
980                                 = get_initializer_compound_n_entries(initializer);
981                         unsigned i;
982                         unsigned initializer_size = get_type_size_bytes(type);
983                         for (i = 0; i < n_entries; ++i) {
984                                 ir_entity *entity = get_compound_member(type, i);
985                                 ir_type   *type   = get_entity_type(entity);
986
987                                 const ir_initializer_t *sub_initializer
988                                         = get_initializer_compound_value(initializer, i);
989
990                                 unsigned offset = get_entity_offset(entity);
991                                 unsigned size   = get_initializer_size(sub_initializer, type);
992
993                                 if (offset + size > initializer_size) {
994                                         initializer_size = offset + size;
995                                 }
996                         }
997                         return initializer_size;
998                 }
999         }
1000
1001         panic("found invalid initializer");
1002 }
1003
1004 #ifndef NDEBUG
1005 static normal_or_bitfield *glob_vals;
1006 static size_t              max_vals;
1007 #endif
1008
1009 static void emit_bitfield(normal_or_bitfield *vals, size_t offset_bits,
1010                           const ir_initializer_t *initializer, ir_type *type)
1011 {
1012         static const size_t BITS_PER_BYTE = 8;
1013         ir_mode   *mode      = get_type_mode(type);
1014         ir_tarval *tv        = NULL;
1015         int        value_len;
1016         size_t     bit_offset;
1017         size_t     end;
1018         bool       big_endian = be_get_backend_param()->byte_order_big_endian;
1019
1020         switch (get_initializer_kind(initializer)) {
1021         case IR_INITIALIZER_NULL:
1022                 return;
1023         case IR_INITIALIZER_TARVAL:
1024                 tv = get_initializer_tarval_value(initializer);
1025                 break;
1026         case IR_INITIALIZER_CONST: {
1027                 ir_node *node = get_initializer_const_value(initializer);
1028                 if (!is_Const(node)) {
1029                         panic("bitfield initializer not a Const node");
1030                 }
1031                 tv = get_Const_tarval(node);
1032                 break;
1033         }
1034         case IR_INITIALIZER_COMPOUND:
1035                 panic("bitfield initializer is compound");
1036         }
1037         if (tv == NULL) {
1038                 panic("Couldn't get numeric value for bitfield initializer");
1039         }
1040         tv = tarval_convert_to(tv, get_type_mode(type));
1041
1042         value_len  = get_type_size_bytes(get_primitive_base_type(type));
1043         bit_offset = 0;
1044         end        = get_mode_size_bits(mode);
1045         while (bit_offset < end) {
1046                 size_t        src_offset      = bit_offset / BITS_PER_BYTE;
1047                 size_t        src_offset_bits = bit_offset % BITS_PER_BYTE;
1048                 size_t        dst_offset      = (bit_offset+offset_bits) / BITS_PER_BYTE;
1049                 size_t        dst_offset_bits = (bit_offset+offset_bits) % BITS_PER_BYTE;
1050                 size_t        src_bits_len    = end-bit_offset;
1051                 size_t        dst_bits_len    = BITS_PER_BYTE-dst_offset_bits;
1052                 unsigned char curr_bits;
1053                 normal_or_bitfield *val;
1054                 if (src_bits_len > dst_bits_len)
1055                         src_bits_len = dst_bits_len;
1056
1057                 if (big_endian) {
1058                         val = &vals[value_len - dst_offset - 1];
1059                 } else {
1060                         val = &vals[dst_offset];
1061                 }
1062
1063                 assert((val-glob_vals) < (ptrdiff_t) max_vals);
1064                 assert(val->kind == BITFIELD ||
1065                                 (val->kind == NORMAL && val->v.value == NULL));
1066                 val->kind  = BITFIELD;
1067                 curr_bits  = get_tarval_sub_bits(tv, src_offset);
1068                 curr_bits  = curr_bits >> src_offset_bits;
1069                 if (src_offset_bits + src_bits_len > 8) {
1070                         unsigned next_bits = get_tarval_sub_bits(tv, src_offset+1);
1071                         curr_bits |= next_bits << (8 - src_offset_bits);
1072                 }
1073                 curr_bits &= (1 << src_bits_len) - 1;
1074                 val->v.bf_val |= curr_bits << dst_offset_bits;
1075
1076                 bit_offset += dst_bits_len;
1077         }
1078 }
1079
1080 static void emit_ir_initializer(normal_or_bitfield *vals,
1081                                 const ir_initializer_t *initializer,
1082                                 ir_type *type)
1083 {
1084         assert((size_t) (vals - glob_vals) < max_vals);
1085
1086         if (initializer_is_string_const(initializer)) {
1087                 assert(vals->kind != BITFIELD);
1088                 vals->kind     = STRING;
1089                 vals->v.string = initializer;
1090                 return;
1091         }
1092
1093         switch (get_initializer_kind(initializer)) {
1094         case IR_INITIALIZER_NULL:
1095                 return;
1096         case IR_INITIALIZER_TARVAL: {
1097                 size_t i;
1098
1099                 assert(vals->kind != BITFIELD);
1100                 vals->kind     = TARVAL;
1101                 vals->v.tarval = get_initializer_tarval_value(initializer);
1102                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
1103                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1104                         vals[i].kind    = NORMAL;
1105                         vals[i].v.value = NULL;
1106                 }
1107                 return;
1108         }
1109         case IR_INITIALIZER_CONST: {
1110                 size_t i;
1111
1112                 assert(vals->kind != BITFIELD);
1113                 vals->kind    = NORMAL;
1114                 vals->v.value = get_initializer_const_value(initializer);
1115                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1116                         vals[i].kind    = NORMAL;
1117                         vals[i].v.value = NULL;
1118                 }
1119                 return;
1120         }
1121         case IR_INITIALIZER_COMPOUND: {
1122                 size_t i = 0;
1123                 size_t n = get_initializer_compound_n_entries(initializer);
1124
1125                 if (is_Array_type(type)) {
1126                         ir_type *element_type = get_array_element_type(type);
1127                         size_t   skip         = get_type_size_bytes(element_type);
1128                         size_t   alignment    = get_type_alignment_bytes(element_type);
1129                         size_t   misalign     = skip % alignment;
1130                         if (misalign != 0) {
1131                                 skip += alignment - misalign;
1132                         }
1133
1134                         for (i = 0; i < n; ++i) {
1135                                 ir_initializer_t *sub_initializer
1136                                         = get_initializer_compound_value(initializer, i);
1137
1138                                 emit_ir_initializer(vals, sub_initializer, element_type);
1139
1140                                 vals += skip;
1141                         }
1142                 } else {
1143                         size_t n_members, i;
1144                         assert(is_compound_type(type));
1145                         n_members = get_compound_n_members(type);
1146                         for (i = 0; i < n_members; ++i) {
1147                                 ir_entity        *member    = get_compound_member(type, i);
1148                                 size_t            offset    = get_entity_offset(member);
1149                                 ir_type          *subtype   = get_entity_type(member);
1150                                 ir_mode          *mode      = get_type_mode(subtype);
1151                                 ir_initializer_t *sub_initializer;
1152
1153                                 assert(i < get_initializer_compound_n_entries(initializer));
1154                                 sub_initializer
1155                                         = get_initializer_compound_value(initializer, i);
1156
1157                                 if (mode != NULL) {
1158                                         size_t offset_bits
1159                                                 = get_entity_offset_bits_remainder(member);
1160                                         size_t value_len = get_mode_size_bits(mode);
1161
1162                                         if (offset_bits != 0 ||
1163                                                 (value_len != 8 && value_len != 16 && value_len != 32
1164                                                  && value_len != 64) ||
1165                                                 (is_Primitive_type(subtype) && get_primitive_base_type(subtype) != NULL)) {
1166                                                 emit_bitfield(&vals[offset], offset_bits,
1167                                                               sub_initializer, subtype);
1168                                                 continue;
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         case OBJECT_FILE_FORMAT_ELF_SPARC:
1410                 be_emit_cstring("\t.comm ");
1411                 be_gas_emit_entity(entity);
1412                 be_emit_irprintf(",%u,%u\n", size, alignment);
1413                 be_emit_write_line();
1414                 return;
1415         case OBJECT_FILE_FORMAT_COFF:
1416                 be_emit_cstring("\t.comm ");
1417                 be_gas_emit_entity(entity);
1418                 be_emit_irprintf(",%u # %u\n", size, alignment);
1419                 be_emit_write_line();
1420                 return;
1421         }
1422         panic("invalid object file format");
1423 }
1424
1425 static void emit_local_common(const ir_entity *entity)
1426 {
1427         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1428         unsigned alignment = get_effective_entity_alignment(entity);
1429
1430         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1431                 emit_weak(entity);
1432         }
1433
1434         switch (be_gas_object_file_format) {
1435         case OBJECT_FILE_FORMAT_MACH_O:
1436                 be_emit_cstring("\t.lcomm ");
1437                 be_gas_emit_entity(entity);
1438                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1439                 be_emit_write_line();
1440                 return;
1441         case OBJECT_FILE_FORMAT_ELF:
1442         case OBJECT_FILE_FORMAT_ELF_SPARC:
1443                 be_emit_cstring("\t.local ");
1444                 be_gas_emit_entity(entity);
1445                 be_emit_cstring("\n");
1446                 be_emit_write_line();
1447                 be_emit_cstring("\t.comm ");
1448                 be_gas_emit_entity(entity);
1449                 be_emit_irprintf(",%u,%u\n", size, alignment);
1450                 be_emit_write_line();
1451                 return;
1452         case OBJECT_FILE_FORMAT_COFF:
1453                 be_emit_cstring("\t.lcomm ");
1454                 be_gas_emit_entity(entity);
1455                 be_emit_irprintf(",%u # %u\n", size, alignment);
1456                 be_emit_write_line();
1457                 return;
1458         }
1459         panic("invalid object file format");
1460 }
1461
1462 static void emit_indirect_symbol(const ir_entity *entity, be_gas_section_t section)
1463 {
1464         /* we can only do PIC code on macho so far */
1465         assert(be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O);
1466
1467         be_gas_emit_entity(entity);
1468         be_emit_cstring(":\n");
1469         be_emit_write_line();
1470         be_emit_cstring("\t.indirect_symbol ");
1471         be_emit_ident(get_entity_ident(entity));
1472         be_emit_char('\n');
1473         be_emit_write_line();
1474         if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1475                 be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1476                 be_emit_write_line();
1477         } else {
1478                 assert(section == GAS_SECTION_PIC_SYMBOLS);
1479                 be_emit_cstring("\t.long 0\n");
1480                 be_emit_write_line();
1481         }
1482 }
1483
1484 char const *be_gas_get_private_prefix(void)
1485 {
1486         return be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O ? "L" : ".L";
1487 }
1488
1489 void be_gas_emit_entity(const ir_entity *entity)
1490 {
1491         if (entity->type == firm_code_type) {
1492                 ir_label_t label = get_entity_label(entity);
1493                 be_emit_irprintf("%s_%lu", be_gas_get_private_prefix(), label);
1494                 return;
1495         }
1496
1497         if (get_entity_visibility(entity) == ir_visibility_private) {
1498                 be_emit_string(be_gas_get_private_prefix());
1499         }
1500         be_emit_ident(get_entity_ld_ident(entity));
1501 }
1502
1503 void be_gas_emit_block_name(const ir_node *block)
1504 {
1505         if (has_Block_entity(block)) {
1506                 ir_entity *entity = get_Block_entity(block);
1507                 be_gas_emit_entity(entity);
1508         } else {
1509                 be_emit_irprintf("%s%ld", be_gas_get_private_prefix(), get_irn_node_nr(block));
1510         }
1511 }
1512
1513 /**
1514  * Dump a global entity.
1515  *
1516  * @param env  the gas output environment
1517  * @param ent  the entity to be dumped
1518  */
1519 static void emit_global(be_gas_decl_env_t *env, const ir_entity *entity)
1520 {
1521         ir_type          *type       = get_entity_type(entity);
1522         ident            *ld_ident   = get_entity_ld_ident(entity);
1523         unsigned          alignment  = get_effective_entity_alignment(entity);
1524         be_gas_section_t  section    = determine_section(env, entity);
1525         ir_visibility     visibility = get_entity_visibility(entity);
1526         ir_linkage        linkage    = get_entity_linkage(entity);
1527
1528         /* block labels are already emittet in the code */
1529         if (type == firm_code_type)
1530                 return;
1531
1532         /* we already emitted all methods. Except for the trampolines which
1533          * the assembler/linker generates */
1534         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1535                 /* functions with graph are already emitted with
1536                  * be_gas_emit_function_prolog */
1537                 if (get_entity_irg(entity) == NULL) {
1538                         emit_visibility(entity);
1539                 }
1540                 return;
1541         }
1542
1543         be_dbg_variable(entity);
1544
1545         if (section == GAS_SECTION_BSS) {
1546                 switch (visibility) {
1547                 case ir_visibility_local:
1548                 case ir_visibility_private:
1549                         emit_local_common(entity);
1550                         return;
1551                 case ir_visibility_default:
1552                         if (linkage & IR_LINKAGE_MERGE) {
1553                                 emit_common(entity);
1554                                 return;
1555                         }
1556                         break;
1557                 case ir_visibility_external:
1558                         if (linkage & IR_LINKAGE_MERGE)
1559                                 panic("merge link semantic not supported for extern entities");
1560                         break;
1561                 }
1562         }
1563
1564         emit_visibility(entity);
1565         if (visibility == ir_visibility_external) {
1566                 /* nothing to do for externally defined values */
1567                 return;
1568         }
1569
1570         if (!is_po2(alignment))
1571                 panic("alignment not a power of 2");
1572
1573         emit_section(section, entity);
1574
1575         if (section == GAS_SECTION_PIC_TRAMPOLINES
1576                         || section == GAS_SECTION_PIC_SYMBOLS) {
1577                 emit_indirect_symbol(entity, section);
1578                 return;
1579         }
1580
1581         /* alignment */
1582         if (alignment > 1) {
1583                 emit_align(alignment);
1584         }
1585         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF
1586                         && be_gas_emit_types
1587                         && visibility != ir_visibility_private) {
1588                 be_emit_cstring("\t.type\t");
1589                 be_gas_emit_entity(entity);
1590                 be_emit_cstring(", ");
1591                 be_emit_char(be_gas_elf_type_char);
1592                 be_emit_cstring("object\n\t.size\t");\
1593                 be_gas_emit_entity(entity);
1594                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1595         }
1596
1597         if (get_id_str(ld_ident)[0] != '\0') {
1598             be_gas_emit_entity(entity);
1599                 be_emit_cstring(":\n");
1600                 be_emit_write_line();
1601         }
1602
1603         if (entity_is_null(entity)) {
1604                 be_emit_irprintf("\t.space %u, 0\n", get_type_size_bytes(type));
1605                 be_emit_write_line();
1606         } else if (entity_has_compound_ent_values(entity)) {
1607                 emit_compound_graph_init(env, entity);
1608         } else {
1609                 assert(entity->initializer != NULL);
1610                 emit_initializer(env, entity);
1611         }
1612 }
1613
1614 /**
1615  * Dumps declarations of global variables and the initialization code.
1616  *
1617  * @param gt                a global like type, either the global or the TLS one
1618  * @param env               an environment
1619  */
1620 static void be_gas_emit_globals(ir_type *gt, be_gas_decl_env_t *env)
1621 {
1622         int i, n = get_compound_n_members(gt);
1623
1624         for (i = 0; i < n; i++) {
1625                 ir_entity *ent = get_compound_member(gt, i);
1626                 emit_global(env, ent);
1627         }
1628 }
1629
1630 /* Generate all entities. */
1631 void be_gas_emit_decls(const be_main_env_t *main_env)
1632 {
1633         be_gas_decl_env_t env;
1634         memset(&env, 0, sizeof(env));
1635
1636         /* dump global type */
1637         env.main_env = main_env;
1638         env.section  = (be_gas_section_t) -1;
1639
1640         be_gas_emit_globals(get_glob_type(), &env);
1641         be_gas_emit_globals(get_tls_type(), &env);
1642         be_gas_emit_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env);
1643         be_gas_emit_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env);
1644         be_gas_emit_globals(main_env->pic_symbols_type, &env);
1645         be_gas_emit_globals(main_env->pic_trampolines_type, &env);
1646
1647         /**
1648          * ".subsections_via_symbols marks object files which are OK to divide
1649          * their section contents into individual blocks".
1650          * From my understanding this means no label points in the middle of an
1651          * object which we want to address as a whole. Firm code should be fine
1652          * with this.
1653          */
1654         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
1655                 be_emit_cstring("\t.subsections_via_symbols\n");
1656                 be_emit_write_line();
1657         }
1658 }