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