simplify begnuas.c by not sorting entities into sections
[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 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30
31 #include "begnuas.h"
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <assert.h>
37
38 #include "obst.h"
39 #include "tv.h"
40 #include "irnode.h"
41 #include "irprog.h"
42 #include "pdeq.h"
43 #include "entity_t.h"
44 #include "error.h"
45
46 #include "be_t.h"
47 #include "beemitter.h"
48 #include "be_dbgout.h"
49
50 /** by default, we generate assembler code for the Linux gas */
51 be_gas_flavour_t be_gas_flavour = GAS_FLAVOUR_ELF;
52
53 static be_gas_section_t current_section = (be_gas_section_t) -1;
54 static int              force_section   = 0;
55
56 /**
57  * Return the pseudo-instruction to be issued for a section switch
58  * depending on the current flavour.
59  *
60  * @param section  the section to switch to
61  *
62  * @return  the pseudo-instruction
63  */
64 static const char *get_section_name(be_gas_section_t section) {
65         static const char *text[GAS_FLAVOUR_LAST+1][GAS_SECTION_LAST+1] = {
66                 { /* GAS_FLAVOUR_ELF */
67                         ".section\t.text",
68                         ".section\t.data",
69                         ".section\t.rodata",
70                         ".section\t.bss",
71                         ".section\t.tbss,\"awT\",@nobits",
72                         ".section\t.ctors,\"aw\",@progbits"
73                 },
74                 { /* GAS_FLAVOUR_MINGW */
75                         ".section\t.text",
76                         ".section\t.data",
77                         ".section .rdata,\"dr\"",
78                         ".section\t.bss",
79                         ".section\t.tbss,\"awT\",@nobits",
80                         ".section\t.ctors,\"aw\",@progbits"
81                 },
82                 { /* GAS_FLAVOUR_YASM */
83                         ".section\t.text",
84                         ".section\t.data",
85                         ".section\t.rodata",
86                         ".section\t.bss",
87                         ".section\t.tbss,\"awT\",@nobits",
88                         ".section\t.ctors,\"aw\",@progbits"
89                 },
90                 { /* GAS_FLAVOUR_MACH_O */
91                         ".text",
92                         ".data",
93                         ".const",
94                         ".data",
95                         NULL, /* TLS is not supported on Mach-O */
96                         NULL  /* constructors aren't marked with sections in Mach-O */
97                 }
98         };
99
100         assert((int) be_gas_flavour >= 0 && be_gas_flavour <= GAS_FLAVOUR_LAST);
101         assert((int) section >= 0 && section <= GAS_SECTION_LAST);
102         return text[be_gas_flavour][section];
103 }
104
105 void be_gas_emit_switch_section(be_gas_section_t section) {
106         if(current_section == section || force_section)
107                 return;
108
109         be_emit_char('\t');
110         be_emit_string(get_section_name(section));
111         be_emit_char('\n');
112         be_emit_write_line();
113         current_section = section;
114 }
115
116 void be_gas_emit_function_prolog(ir_entity *entity, unsigned alignment)
117 {
118         const char *name = get_entity_ld_name(entity);
119
120         be_gas_emit_switch_section(GAS_SECTION_TEXT);
121
122         /* write the begin line (used by scripts processing the assembler... */
123         be_emit_write_line();
124         be_emit_cstring("# -- Begin  ");
125         be_emit_string(name);
126         be_emit_char('\n');
127         be_emit_write_line();
128
129         const char *fill_byte = "";
130         /* gcc fills space between function with 0x90, no idea if this is needed */
131         if(be_gas_flavour == GAS_FLAVOUR_MACH_O) {
132                 fill_byte = "0x90";
133         }
134
135         unsigned maximum_skip = (1 << alignment) - 1;
136         be_emit_cstring("\t.p2align ");
137         be_emit_irprintf("%u,%s,%u\n", alignment, fill_byte, maximum_skip);
138         be_emit_write_line();
139
140         if (get_entity_visibility(entity) == visibility_external_visible) {
141                 be_emit_cstring(".globl ");
142                 be_emit_string(name);
143                 be_emit_char('\n');
144                 be_emit_write_line();
145         }
146
147         switch (be_gas_flavour) {
148         case GAS_FLAVOUR_ELF:
149                 be_emit_cstring("\t.type\t");
150                 be_emit_string(name);
151                 be_emit_cstring(", @function\n");
152                 be_emit_write_line();
153                 break;
154         case GAS_FLAVOUR_MINGW:
155                 be_emit_cstring("\t.def\t");
156                 be_emit_string(name);
157                 be_emit_cstring(";\t.scl\t2;\t.type\t32;\t.endef\n");
158                 be_emit_write_line();
159                 break;
160         case GAS_FLAVOUR_MACH_O:
161         case GAS_FLAVOUR_YASM:
162                 break;
163         }
164         be_emit_string(name);
165         be_emit_cstring(":\n");
166         be_emit_write_line();
167 }
168
169 void be_gas_emit_function_epilog(ir_entity *entity)
170 {
171         const char *name = get_entity_ld_name(entity);
172
173         if (be_gas_flavour == GAS_FLAVOUR_ELF) {
174                 be_emit_cstring("\t.size\t");
175                 be_emit_string(name);
176                 be_emit_cstring(", .-");
177                 be_emit_string(name);
178                 be_emit_char('\n');
179                 be_emit_write_line();
180         }
181
182         be_emit_cstring("# -- End  ");
183         be_emit_string(name);
184         be_emit_char('\n');
185         be_emit_write_line();
186 }
187
188 /**
189  * An environment containing all needed dumper data.
190  * Currently we create the file completely in memory first, then
191  * write it to the disk. This is an artifact from the old C-generating backend
192  * and even there NOT needed. So we might change it in the future.
193  */
194 typedef struct _be_gas_decl_env {
195         const be_main_env_t *main_env; /**< The main backend environment, used for it's debug handle. */
196         waitq     *worklist;           /**< A worklist we use to place not yet handled entities on. */
197 } be_gas_decl_env_t;
198
199 /************************************************************************/
200
201 /**
202  * Output a tarval.
203  *
204  * @param tv     the tarval
205  * @param bytes  the width of the tarvals value in bytes
206  */
207 static void dump_arith_tarval(tarval *tv, int bytes)
208 {
209         switch (bytes) {
210         case 1:
211                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
212                 break;
213
214         case 2:
215                 be_emit_irprintf("0x%02x%02x", get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
216                 break;
217
218         case 4:
219                 be_emit_irprintf("0x%02x%02x%02x%02x",
220                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
221                 break;
222
223         case 8:
224                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
225                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6), get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
226                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
227                 break;
228
229         case 10:
230         case 12:
231                 break;
232
233         case 16:
234                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x"
235                                                "%02x%02x%02x%02x%02x%02x%02x%02x",
236                         get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 16),
237                         get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12),
238                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
239                         get_tarval_sub_bits(tv, 9), get_tarval_sub_bits(tv, 8),
240                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6),
241                         get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
242                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2),
243                         get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
244                 break;
245
246
247         default:
248                 fprintf(stderr, "Try to dump an tarval with %d bytes\n", bytes);
249                 assert(0);
250         }
251 }
252
253 /**
254  * Return the label prefix for labeled blocks.
255  */
256 const char *be_gas_label_prefix(void) {
257         return ".LG";
258 }
259
260 /**
261  * Dump a label.
262  */
263 static void dump_label(ir_label_t label) {
264         be_emit_irprintf("%s%ld", be_gas_label_prefix(), label);
265 }
266
267 /**
268  * Return the tarval of an atomic initializer.
269  *
270  * @param init  a node representing the initializer (on the const code irg)
271  *
272  * @return the tarval
273  */
274 static tarval *get_atomic_init_tv(ir_node *init)
275 {
276         for (;;) {
277                 ir_mode *mode = get_irn_mode(init);
278
279                 switch (get_irn_opcode(init)) {
280
281                 case iro_Cast:
282                         init = get_Cast_op(init);
283                         continue;
284
285                 case iro_Conv:
286                         init = get_Conv_op(init);
287                         continue;
288
289                 case iro_Const:
290                         return get_Const_tarval(init);
291
292                 case iro_SymConst:
293                         switch (get_SymConst_kind(init)) {
294                         case symconst_type_size:
295                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
296
297                         case symconst_type_align:
298                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
299
300                         case symconst_ofs_ent:
301                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
302
303                         case symconst_enum_const:
304                                 return get_enumeration_value(get_SymConst_enum(init));
305
306                         case symconst_label:
307                                 return NULL;
308
309                         default:
310                                 return NULL;
311                         }
312
313                 default:
314                         return NULL;
315                 }
316         }
317 }
318
319 /**
320  * Dump an atomic value.
321  *
322  * @param env   the gas output environment
323  * @param init  a node representing the atomic value (on the const code irg)
324  */
325 static void do_dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
326 {
327         ir_mode *mode = get_irn_mode(init);
328         int bytes     = get_mode_size_bytes(mode);
329         tarval *tv;
330         ir_label_t label;
331         ir_entity *ent;
332
333         init = skip_Id(init);
334
335         switch (get_irn_opcode(init)) {
336         case iro_Cast:
337                 do_dump_atomic_init(env, get_Cast_op(init));
338                 return;
339
340         case iro_Conv:
341                 do_dump_atomic_init(env, get_Conv_op(init));
342                 return;
343
344         case iro_Const:
345                 tv = get_Const_tarval(init);
346
347                 /* it's a arithmetic value */
348                 dump_arith_tarval(tv, bytes);
349                 return;
350
351         case iro_SymConst:
352                 switch (get_SymConst_kind(init)) {
353                 case symconst_addr_name:
354                         be_emit_ident(get_SymConst_name(init));
355                         break;
356
357                 case symconst_addr_ent:
358                         ent = get_SymConst_entity(init);
359                         if(!is_entity_backend_marked(ent)) {
360                                 waitq_put(env->worklist, ent);
361                                 set_entity_backend_marked(ent, 1);
362                         }
363                         be_emit_ident(get_entity_ld_ident(ent));
364                         break;
365
366                 case symconst_ofs_ent:
367                         ent = get_SymConst_entity(init);
368 #if 0       /* not needed, is it? */
369                         if(!is_entity_backend_marked(ent)) {
370                                 waitq_put(env->worklist, ent);
371                                 set_entity_backend_marked(ent, 1);
372                         }
373 #endif
374                         be_emit_irprintf("%d", get_entity_offset(ent));
375                         break;
376
377                 case symconst_type_size:
378                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
379                         break;
380
381                 case symconst_type_align:
382                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
383                         break;
384
385                 case symconst_enum_const:
386                         tv = get_enumeration_value(get_SymConst_enum(init));
387                         dump_arith_tarval(tv, bytes);
388                         break;
389
390                 case symconst_label:
391                         label = get_SymConst_label(init);
392                         dump_label(label);
393                         break;
394
395                 default:
396                         assert(!"dump_atomic_init(): don't know how to init from this SymConst");
397                 }
398                 return;
399
400                 case iro_Add:
401                         do_dump_atomic_init(env, get_Add_left(init));
402                         be_emit_cstring(" + ");
403                         do_dump_atomic_init(env, get_Add_right(init));
404                         return;
405
406                 case iro_Sub:
407                         do_dump_atomic_init(env, get_Sub_left(init));
408                         be_emit_cstring(" - ");
409                         do_dump_atomic_init(env, get_Sub_right(init));
410                         return;
411
412                 case iro_Mul:
413                         do_dump_atomic_init(env, get_Mul_left(init));
414                         be_emit_cstring(" * ");
415                         do_dump_atomic_init(env, get_Mul_right(init));
416                         return;
417
418                 default:
419                         assert(0 && "dump_atomic_init(): unknown IR-node");
420         }
421 }
422
423 /**
424  * Dumps the type for given size (.byte, .long, ...)
425  *
426  * @param size  the size in bytes
427  */
428 static void dump_size_type(size_t size) {
429         switch (size) {
430         case 1:
431                 be_emit_cstring("\t.byte\t");
432                 break;
433
434         case 2:
435                 be_emit_cstring("\t.word\t");
436                 break;
437
438         case 4:
439                 be_emit_cstring("\t.long\t");
440                 break;
441
442         case 8:
443                 be_emit_cstring("\t.quad\t");
444                 break;
445
446         case 10:
447         case 12:
448                 /* handled in arith */
449                 break;
450
451         case 16:
452                 be_emit_cstring("\t.octa\t");
453                 break;
454
455         default:
456                 panic("Try to dump a type with %u bytes\n", (unsigned) size);
457         }
458 }
459
460 /**
461  * Emit an atomic value.
462  *
463  * @param env   the gas output environment
464  * @param init  a node representing the atomic value (on the const code irg)
465  */
466 static void dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
467 {
468         ir_mode *mode = get_irn_mode(init);
469         int bytes     = get_mode_size_bytes(mode);
470
471         dump_size_type(bytes);
472         do_dump_atomic_init(env, init);
473         be_emit_char('\n');
474         be_emit_write_line();
475 }
476
477 /************************************************************************/
478 /* Routines to dump global variables                                    */
479 /************************************************************************/
480
481 static int initializer_is_string_const(const ir_initializer_t *initializer)
482 {
483         size_t i, len;
484
485         if(initializer->kind != IR_INITIALIZER_COMPOUND)
486                 return 0;
487
488         len = initializer->compound.n_initializers;
489         if (len < 1)
490                 return 0;
491         for(i = 0; i < len; ++i) {
492                 int               c;
493                 tarval           *tv;
494                 ir_mode          *mode;
495                 ir_initializer_t *sub_initializer
496                         = initializer->compound.initializers[i];
497
498                 if(sub_initializer->kind != IR_INITIALIZER_TARVAL)
499                         return 0;
500
501                 tv   = sub_initializer->tarval.value;
502                 mode = get_tarval_mode(tv);
503
504                 if (!mode_is_int(mode)
505                                 || get_mode_size_bits(mode) != get_mode_size_bits(mode_Bs))
506                         return 0;
507
508                 c = get_tarval_long(tv);
509                 if (i < len - 1) {
510                         if (!isgraph(c) && !isspace(c))
511                                 return 0;
512                 } else {
513                         if (c != 0)
514                                 return 0;
515                 }
516         }
517
518         return 1;
519 }
520
521 /**
522  * Determine if an entity is a string constant
523  * @param ent The entity
524  * @return 1 if it is a string constant, 0 otherwise
525  */
526 static int ent_is_string_const(ir_entity *ent)
527 {
528         ir_type *type, *element_type;
529         ir_mode *mode;
530         int i, c, n;
531
532         type = get_entity_type(ent);
533
534         /* if it's an array */
535         if (!is_Array_type(type))
536                 return 0;
537
538         element_type = get_array_element_type(type);
539
540         /* and the array's element type is primitive */
541         if (!is_Primitive_type(element_type))
542                 return 0;
543
544         /* and the mode of the element type is an int of
545          * the same size as the byte mode */
546         mode = get_type_mode(element_type);
547         if (!mode_is_int(mode)
548                 || get_mode_size_bits(mode) != get_mode_size_bits(mode_Bs))
549                 return 0;
550
551         if(ent->has_initializer) {
552                 /* TODO */
553                 return 0;
554         } else {
555                 /* if it contains only printable chars and a 0 at the end */
556                 n = get_compound_ent_n_values(ent);
557                 for (i = 0; i < n; ++i) {
558                         ir_node *irn = get_compound_ent_value(ent, i);
559                         if (! is_Const(irn))
560                                 return 0;
561
562                         c = (int) get_tarval_long(get_Const_tarval(irn));
563
564                         if((i < n - 1 && !(isgraph(c) || isspace(c)))
565                                         || (i == n - 1 && c != '\0'))
566                                 return 0;
567                 }
568         }
569
570         /* then we can emit it as a string constant */
571         return 1;
572 }
573
574 /**
575  * Dump a string constant.
576  * No checks are made!!
577  *
578  * @param ent  The entity to dump.
579  */
580 static void dump_string_cst(ir_entity *ent)
581 {
582         int      i, len;
583         ir_type *type;
584         int      type_size;
585         int      remaining_space;
586
587         be_gas_section_t last_section = current_section;
588         len = get_compound_ent_n_values(ent);
589         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
590                 if (get_entity_variability(ent) == variability_constant) {
591                         be_gas_emit_switch_section(GAS_SECTION_CSTRING);
592                 }
593                 be_emit_cstring("\t.ascii \"");
594         } else {
595                 be_emit_cstring("\t.string \"");
596                 len -= 1;
597         }
598
599         for (i = 0; i < len; ++i) {
600                 ir_node *irn;
601                 int c;
602
603                 irn = get_compound_ent_value(ent, i);
604                 c = (int) get_tarval_long(get_Const_tarval(irn));
605
606                 switch (c) {
607                 case '"' : be_emit_cstring("\\\""); break;
608                 case '\n': be_emit_cstring("\\n"); break;
609                 case '\r': be_emit_cstring("\\r"); break;
610                 case '\t': be_emit_cstring("\\t"); break;
611                 case '\\': be_emit_cstring("\\\\"); break;
612                 default  :
613                         if (isprint(c))
614                                 be_emit_char(c);
615                         else
616                                 be_emit_irprintf("\\%o", c);
617                         break;
618                 }
619         }
620         be_emit_cstring("\"\n");
621         be_emit_write_line();
622
623         type            = get_entity_type(ent);
624         type_size       = get_type_size_bytes(type);
625         remaining_space = type_size - len;
626         assert(remaining_space >= 0);
627         if(remaining_space > 0) {
628                 be_emit_irprintf("\t.skip\t%d\n", remaining_space);
629         }
630         if(be_gas_flavour == GAS_FLAVOUR_MACH_O) {
631                 be_gas_emit_switch_section(last_section);
632         }
633 }
634
635 static void dump_string_initializer(const ir_initializer_t *initializer)
636 {
637         size_t i, len;
638
639         len = initializer->compound.n_initializers;
640         if(be_gas_flavour == GAS_FLAVOUR_MACH_O) {
641                 be_emit_cstring("\t.string \"");
642                 len -= 1;
643         } else {
644                 be_emit_cstring("\t.ascii \"");
645         }
646
647         for(i = 0; i < len; ++i) {
648                 const ir_initializer_t *sub_initializer
649                         = get_initializer_compound_value(initializer, i);
650
651                 tarval *tv = get_initializer_tarval_value(sub_initializer);
652                 int     c  = get_tarval_long(tv);
653
654                 switch (c) {
655                 case '"' : be_emit_cstring("\\\""); break;
656                 case '\n': be_emit_cstring("\\n"); break;
657                 case '\r': be_emit_cstring("\\r"); break;
658                 case '\t': be_emit_cstring("\\t"); break;
659                 case '\\': be_emit_cstring("\\\\"); break;
660                 default  :
661                         if (isprint(c))
662                                 be_emit_char(c);
663                         else
664                                 be_emit_irprintf("\\%o", c);
665                         break;
666                 }
667         }
668         be_emit_cstring("\"\n");
669         be_emit_write_line();
670 }
671
672 enum normal_or_bitfield_kind {
673         NORMAL = 0,
674         TARVAL,
675         BITFIELD
676 };
677
678 typedef struct {
679         enum normal_or_bitfield_kind kind;
680         union {
681                 ir_node       *value;
682                 tarval        *tarval;
683                 unsigned char  bf_val;
684         } v;
685 } normal_or_bitfield;
686
687 static int is_type_variable_size(ir_type *type)
688 {
689         (void) type;
690         /* TODO */
691         return 0;
692 }
693
694 static size_t get_initializer_size(const ir_initializer_t *initializer,
695                                    ir_type *type)
696 {
697         switch(get_initializer_kind(initializer)) {
698         case IR_INITIALIZER_TARVAL: {
699                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
700                 return get_type_size_bytes(type);
701         }
702         case IR_INITIALIZER_CONST:
703         case IR_INITIALIZER_NULL:
704                 return get_type_size_bytes(type);
705         case IR_INITIALIZER_COMPOUND: {
706                 if(!is_type_variable_size(type)) {
707                         return get_type_size_bytes(type);
708                 } else {
709                         unsigned n_entries
710                                 = get_initializer_compound_n_entries(initializer);
711                         unsigned i;
712                         unsigned initializer_size = get_type_size_bytes(type);
713                         for(i = 0; i < n_entries; ++i) {
714                                 ir_entity *entity = get_compound_member(type, i);
715                                 ir_type   *type   = get_entity_type(entity);
716
717                                 const ir_initializer_t *sub_initializer
718                                         = get_initializer_compound_value(initializer, i);
719
720                                 unsigned offset = get_entity_offset(entity);
721                                 unsigned size   = get_initializer_size(sub_initializer, type);
722
723                                 if(offset + size > initializer_size) {
724                                         initializer_size = offset + size;
725                                 }
726                         }
727                         return initializer_size;
728                 }
729         }
730         }
731
732         panic("found invalid initializer");
733 }
734
735 #ifndef NDEBUG
736 static normal_or_bitfield *glob_vals;
737 static size_t              max_vals;
738 #endif
739
740 static void dump_bitfield(normal_or_bitfield *vals, size_t offset_bits,
741                           const ir_initializer_t *initializer, ir_type *type)
742 {
743         unsigned char  last_bits = 0;
744         ir_mode       *mode      = get_type_mode(type);
745         tarval        *tv        = NULL;
746         unsigned char  curr_bits;
747         int            value_len;
748         int            j;
749
750         switch(get_initializer_kind(initializer)) {
751         case IR_INITIALIZER_NULL:
752                 return;
753         case IR_INITIALIZER_TARVAL:
754                 tv = get_initializer_tarval_value(initializer);
755                 break;
756         case IR_INITIALIZER_CONST: {
757                 ir_node *node = get_initializer_const_value(initializer);
758                 if(!is_Const(node)) {
759                         panic("bitfield initializer not a Const node");
760                 }
761                 tv = get_Const_tarval(node);
762                 break;
763         }
764         case IR_INITIALIZER_COMPOUND:
765                 panic("bitfield initializer is compound");
766         }
767         if (tv == NULL) {
768                 panic("Couldn't get numeric value for bitfield initializer\n");
769         }
770
771         /* normalize offset */
772         vals        += offset_bits >> 3;
773         offset_bits &= 7;
774         value_len    = get_mode_size_bits(mode);
775
776         /* combine bits with existing bits */
777         for (j = 0; value_len + (int) offset_bits > 0; ++j) {
778                 assert((size_t) (vals - glob_vals) + j < max_vals);
779                 assert(vals[j].kind == BITFIELD ||
780                                 (vals[j].kind == NORMAL && vals[j].v.value == NULL));
781                 vals[j].kind = BITFIELD;
782                 curr_bits    = get_tarval_sub_bits(tv, j);
783                 vals[j].v.bf_val
784                         |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
785                 value_len -= 8;
786                 last_bits = curr_bits;
787         }
788 }
789
790 static void dump_ir_initializer(normal_or_bitfield *vals,
791                                 const ir_initializer_t *initializer,
792                                 ir_type *type)
793 {
794         assert((size_t) (vals - glob_vals) < max_vals);
795
796         switch(get_initializer_kind(initializer)) {
797         case IR_INITIALIZER_NULL:
798                 return;
799         case IR_INITIALIZER_TARVAL: {
800                 size_t i;
801
802                 assert(vals->kind != BITFIELD);
803                 vals->kind     = TARVAL;
804                 vals->v.tarval = get_initializer_tarval_value(initializer);
805                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
806                 for(i = 1; i < get_type_size_bytes(type); ++i) {
807                         vals[i].kind    = NORMAL;
808                         vals[i].v.value = NULL;
809                 }
810                 return;
811         }
812         case IR_INITIALIZER_CONST: {
813                 size_t i;
814
815                 assert(vals->kind != BITFIELD);
816                 vals->kind    = NORMAL;
817                 vals->v.value = get_initializer_const_value(initializer);
818                 for(i = 1; i < get_type_size_bytes(type); ++i) {
819                         vals[i].kind    = NORMAL;
820                         vals[i].v.value = NULL;
821                 }
822                 return;
823         }
824         case IR_INITIALIZER_COMPOUND: {
825                 size_t i = 0;
826                 size_t n = get_initializer_compound_n_entries(initializer);
827
828                 if(is_Array_type(type)) {
829                         ir_type *element_type = get_array_element_type(type);
830                         size_t   skip         = get_type_size_bytes(element_type);
831                         size_t   alignment    = get_type_alignment_bytes(element_type);
832                         size_t   misalign     = skip % alignment;
833                         if(misalign != 0) {
834                                 skip += alignment - misalign;
835                         }
836
837                         for(i = 0; i < n; ++i) {
838                                 ir_initializer_t *sub_initializer
839                                         = get_initializer_compound_value(initializer, i);
840
841                                 dump_ir_initializer(vals, sub_initializer, element_type);
842
843                                 vals += skip;
844                         }
845                 } else {
846                         size_t n_members, i;
847                         assert(is_compound_type(type));
848                         n_members = get_compound_n_members(type);
849                         for(i = 0; i < n_members; ++i) {
850                                 ir_entity        *member    = get_compound_member(type, i);
851                                 size_t            offset    = get_entity_offset(member);
852                                 ir_type          *subtype   = get_entity_type(member);
853                                 ir_mode          *mode      = get_type_mode(subtype);
854                                 ir_initializer_t *sub_initializer;
855
856                                 assert(i < get_initializer_compound_n_entries(initializer));
857                                 sub_initializer
858                                         = get_initializer_compound_value(initializer, i);
859
860                                 if(mode != NULL) {
861                                         size_t offset_bits
862                                                 = get_entity_offset_bits_remainder(member);
863                                         size_t value_len   = get_mode_size_bits(mode);
864
865                                         if(offset_bits != 0 ||
866                                                 (value_len != 8 && value_len != 16 && value_len != 32
867                                                  && value_len != 64)) {
868                                                 dump_bitfield(&vals[offset], offset_bits,
869                                                               sub_initializer, subtype);
870                                                 continue;
871                                         }
872                                 }
873
874                                 dump_ir_initializer(&vals[offset], sub_initializer, subtype);
875                         }
876                 }
877
878                 return;
879         }
880         }
881         panic("invalid ir_initializer kind found");
882 }
883
884 static void dump_initializer(be_gas_decl_env_t *env, ir_entity *entity)
885 {
886         const ir_initializer_t *initializer = entity->attr.initializer;
887         ir_type                *type;
888         normal_or_bitfield     *vals;
889         size_t                  size;
890         size_t                  k;
891
892         if(initializer_is_string_const(initializer)) {
893                 dump_string_initializer(initializer);
894                 return;
895         }
896
897         type = get_entity_type(entity);
898         size = get_initializer_size(initializer, type);
899
900         if (size == 0)
901                 return;
902
903         /*
904          * In the worst case, every initializer allocates one byte.
905          * Moreover, initializer might be big, do not allocate on stack.
906          */
907         vals = xcalloc(size, sizeof(vals[0]));
908
909 #ifndef NDEBUG
910         glob_vals = vals;
911         max_vals  = size;
912 #endif
913
914         dump_ir_initializer(vals, initializer, type);
915
916         /* now write values sorted */
917         for (k = 0; k < size; ) {
918                 int space = 0, skip = 0;
919                 if (vals[k].kind == NORMAL) {
920                         if(vals[k].v.value != NULL) {
921                                 dump_atomic_init(env, vals[k].v.value);
922                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
923                         } else {
924                                 space = 1;
925                         }
926                 } else if(vals[k].kind == TARVAL) {
927                         tarval *tv   = vals[k].v.tarval;
928                         size_t  size = get_mode_size_bytes(get_tarval_mode(tv));
929
930                         assert(tv != NULL);
931
932                         skip = size - 1;
933                         dump_size_type(size);
934                         dump_arith_tarval(tv, size);
935                         be_emit_char('\n');
936                         be_emit_write_line();
937                 } else {
938                         assert(vals[k].kind == BITFIELD);
939                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
940                         be_emit_write_line();
941                 }
942
943                 ++k;
944                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
945                         ++space;
946                         ++k;
947                 }
948                 space -= skip;
949                 assert(space >= 0);
950
951                 /* a gap */
952                 if (space > 0) {
953                         be_emit_irprintf("\t.skip\t%d\n", space);
954                         be_emit_write_line();
955                 }
956         }
957         xfree(vals);
958 }
959
960 /**
961  * Dump an initializer for a compound entity.
962  */
963 static void dump_compound_init(be_gas_decl_env_t *env, ir_entity *ent)
964 {
965         normal_or_bitfield *vals;
966         int i, j, n;
967         unsigned k, last_ofs;
968
969         if(ent->has_initializer) {
970                 dump_initializer(env, ent);
971                 return;
972         }
973
974         n = get_compound_ent_n_values(ent);
975
976         /* Find the initializer size. Sorrily gcc support a nasty feature:
977            The last field of a compound may be a flexible array. This allows
978            initializers bigger than the type size. */
979         last_ofs = get_type_size_bytes(get_entity_type(ent));
980         for (i = 0; i < n; ++i) {
981                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
982                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
983                 ir_node  *value         = get_compound_ent_value(ent, i);
984                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
985
986                 offset += (value_len + bits_remainder + 7) >> 3;
987
988                 if (offset > last_ofs) {
989                         last_ofs = offset;
990                 }
991         }
992
993         /*
994          * In the worst case, every initializer allocates one byte.
995          * Moreover, initializer might be big, do not allocate on stack.
996          */
997         vals = xcalloc(last_ofs, sizeof(vals[0]));
998
999         /* collect the values and store them at the offsets */
1000         for (i = 0; i < n; ++i) {
1001                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1002                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1003                 ir_node  *value      = get_compound_ent_value(ent, i);
1004                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1005
1006                 assert(offset_bits >= 0);
1007
1008                 if (offset_bits != 0 ||
1009                         (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1010                         tarval *tv = get_atomic_init_tv(value);
1011                         unsigned char curr_bits, last_bits = 0;
1012                         if (tv == NULL) {
1013                                 panic("Couldn't get numeric value for bitfield initializer '%s'\n",
1014                                       get_entity_ld_name(ent));
1015                         }
1016                         /* normalize offset */
1017                         offset += offset_bits >> 3;
1018                         offset_bits &= 7;
1019
1020                         for (j = 0; value_len + offset_bits > 0; ++j) {
1021                                 assert(offset + j < last_ofs);
1022                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1023                                 vals[offset + j].kind = BITFIELD;
1024                                 curr_bits = get_tarval_sub_bits(tv, j);
1025                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1026                                 value_len -= 8;
1027                                 last_bits = curr_bits;
1028                         }
1029                 } else {
1030                         int i;
1031
1032                         assert(offset < last_ofs);
1033                         assert(vals[offset].kind == NORMAL);
1034                         for (i = 1; i < value_len / 8; ++i) {
1035                                 assert(vals[offset + i].v.value == NULL);
1036                         }
1037                         vals[offset].v.value = value;
1038                 }
1039         }
1040
1041         /* now write them sorted */
1042         for (k = 0; k < last_ofs; ) {
1043                 int space = 0, skip = 0;
1044                 if (vals[k].kind == NORMAL) {
1045                         if(vals[k].v.value != NULL) {
1046                                 dump_atomic_init(env, vals[k].v.value);
1047                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1048                         } else {
1049                                 space = 1;
1050                         }
1051                 } else {
1052                         assert(vals[k].kind == BITFIELD);
1053                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1054                 }
1055
1056                 ++k;
1057                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1058                         ++space;
1059                         ++k;
1060                 }
1061                 space -= skip;
1062                 assert(space >= 0);
1063
1064                 /* a gap */
1065                 if (space > 0) {
1066                         be_emit_irprintf("\t.skip\t%d\n", space);
1067                         be_emit_write_line();
1068                 }
1069         }
1070         xfree(vals);
1071 }
1072
1073 static void emit_align(unsigned alignment)
1074 {
1075         if (!is_po2(alignment))
1076                 panic("alignment not a power of 2");
1077
1078         be_emit_irprintf(".p2align\t%u\n", log2_floor(alignment));
1079         be_emit_write_line();
1080 }
1081
1082 /**
1083  * Dump a global entity.
1084  *
1085  * @param env           the gas output environment
1086  * @param ent           the entity to be dumped
1087  * @param emit_commons  if non-zero, emit commons (non-local uninitialized entities)
1088  */
1089 static void dump_global(be_gas_decl_env_t *env, ir_entity *ent, int emit_commons)
1090 {
1091         ir_type          *type           = get_entity_type(ent);
1092         ident            *ld_ident       = get_entity_ld_ident(ent);
1093         unsigned          align          = get_type_alignment_bytes(type);
1094         int               emit_as_common = 0;
1095         be_gas_section_t  section;
1096         ir_variability    variability;
1097         ir_visibility     visibility;
1098
1099         if (is_Method_type(type)) {
1100                 if (be_gas_flavour != GAS_FLAVOUR_MACH_O
1101                                 && get_method_img_section(ent) == section_constructors) {
1102                         be_gas_emit_switch_section(GAS_SECTION_CTOR);
1103                         emit_align(align);
1104                         dump_size_type(align);
1105                         be_emit_ident(ld_ident);
1106                         be_emit_char('\n');
1107                         be_emit_write_line();
1108                 }
1109
1110                 return;
1111         }
1112
1113         variability = get_entity_variability(ent);
1114         visibility  = get_entity_visibility(ent);
1115         section     = GAS_SECTION_DATA;
1116         if (variability == variability_constant) {
1117                 /* a constant entity, put it on the rdata */
1118                 section = GAS_SECTION_RODATA;
1119         } else if (variability == variability_uninitialized) {
1120                 /* uninitialized entity put it in bss segment */
1121                 section = GAS_SECTION_COMMON;
1122                 if (emit_commons && visibility != visibility_local)
1123                         emit_as_common = 1;
1124         }
1125
1126         if(!emit_as_common) {
1127                 be_gas_emit_switch_section(section);
1128         }
1129
1130         be_dbg_variable(ent);
1131
1132         /* global or not global */
1133         if (visibility == visibility_external_visible && !emit_as_common) {
1134                 be_emit_cstring(".globl\t");
1135                 be_emit_ident(ld_ident);
1136                 be_emit_char('\n');
1137                 be_emit_write_line();
1138         } else if(visibility == visibility_external_allocated) {
1139                 be_emit_cstring(".globl\t");
1140                 be_emit_ident(ld_ident);
1141                 be_emit_char('\n');
1142                 be_emit_write_line();
1143                 /* we can return now... */
1144                 return;
1145         }
1146         /* alignment */
1147         if (align > 1 && !emit_as_common) {
1148                 emit_align(align);
1149         }
1150
1151         if (!emit_as_common) {
1152                 be_emit_ident(ld_ident);
1153                 be_emit_cstring(":\n");
1154                 be_emit_write_line();
1155         }
1156
1157         if (variability == variability_uninitialized) {
1158                 if (emit_as_common) {
1159                         switch (be_gas_flavour) {
1160                         case GAS_FLAVOUR_ELF:
1161                         case GAS_FLAVOUR_MACH_O:
1162                         case GAS_FLAVOUR_YASM:
1163                                 be_emit_irprintf("\t.comm %s,%u,%u\n",
1164                                         get_id_str(ld_ident), get_type_size_bytes(type), align);
1165                                 be_emit_write_line();
1166                                 break;
1167                         case GAS_FLAVOUR_MINGW:
1168                                 be_emit_irprintf("\t.comm %s,%u # %u\n",
1169                                         get_id_str(ld_ident), get_type_size_bytes(type), align);
1170                                 be_emit_write_line();
1171                                 break;
1172                         }
1173                 } else {
1174                         be_emit_irprintf("\t.zero %u\n", get_type_size_bytes(type));
1175                         be_emit_write_line();
1176                 }
1177         } else {
1178                 if (is_atomic_entity(ent)) {
1179                         dump_atomic_init(env, get_atomic_ent_value(ent));
1180                 } else {
1181                         /* sort_compound_ent_values(ent); */
1182
1183                         switch (get_type_tpop_code(get_entity_type(ent))) {
1184                         case tpo_array:
1185                                 if (ent_is_string_const(ent))
1186                                         dump_string_cst(ent);
1187                                 else
1188                                         dump_compound_init(env, ent);
1189                                 break;
1190                         case tpo_struct:
1191                         case tpo_class:
1192                         case tpo_union:
1193                                 dump_compound_init(env, ent);
1194                                 break;
1195                         default:
1196                                 assert(0);
1197                         }
1198                 }
1199         }
1200 }
1201
1202 /**
1203  * Dumps declarations of global variables and the initialization code.
1204  *
1205  * @param gt                a global like type, either the global or the TLS one
1206  * @param env               an environment
1207  * @param emit_commons      if non-zero, emit commons (non-local uninitialized entities)
1208  * @param only_emit_marked  if non-zero, external allocated entities that do not have
1209  *                          its visited flag set are ignored
1210  */
1211 static void be_gas_dump_globals(ir_type *gt, be_gas_decl_env_t *env,
1212                               int emit_commons, int only_emit_marked)
1213 {
1214         int i, n = get_compound_n_members(gt);
1215         waitq *worklist = new_waitq();
1216
1217         if (only_emit_marked) {
1218                 for (i = 0; i < n; i++) {
1219                         ir_entity *ent = get_compound_member(gt, i);
1220                         if (is_entity_backend_marked(ent) ||
1221                             get_entity_visibility(ent) != visibility_external_allocated) {
1222                                 waitq_put(worklist, ent);
1223                                 set_entity_backend_marked(ent, 1);
1224                         }
1225                 }
1226         } else {
1227                 for (i = 0; i < n; i++) {
1228                         ir_entity *ent = get_compound_member(gt, i);
1229                         set_entity_backend_marked(ent, 1);
1230                         waitq_put(worklist, ent);
1231                 }
1232         }
1233
1234         env->worklist = worklist;
1235
1236         while (!waitq_empty(worklist)) {
1237                 ir_entity *ent = waitq_get(worklist);
1238
1239                 dump_global(env, ent, emit_commons);
1240         }
1241
1242         del_waitq(worklist);
1243         env->worklist = NULL;
1244 }
1245
1246 /************************************************************************/
1247
1248 /* Generate all entities. */
1249 void be_gas_emit_decls(const be_main_env_t *main_env,
1250                        int only_emit_marked_entities)
1251 {
1252         be_gas_decl_env_t env;
1253
1254         env.main_env = main_env;
1255
1256         /* dump global type */
1257         be_gas_dump_globals(get_glob_type(), &env, 1, only_emit_marked_entities);
1258
1259         /* dump the Thread Local Storage */
1260         if (be_gas_flavour != GAS_FLAVOUR_MACH_O) {
1261                 be_gas_emit_switch_section(GAS_SECTION_TLS);
1262                 force_section = 1;
1263                 be_gas_dump_globals(get_tls_type(), &env, 0, only_emit_marked_entities);
1264                 force_section = 0;
1265         }
1266 }