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