cleanup space generation logic and make it more robust for union constructs
[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                         do_dump_atomic_init(env, get_Add_left(init));
420                         be_emit_cstring(" + ");
421                         do_dump_atomic_init(env, get_Add_right(init));
422                         return;
423
424                 case iro_Sub:
425                         do_dump_atomic_init(env, get_Sub_left(init));
426                         be_emit_cstring(" - ");
427                         do_dump_atomic_init(env, get_Sub_right(init));
428                         return;
429
430                 case iro_Mul:
431                         do_dump_atomic_init(env, get_Mul_left(init));
432                         be_emit_cstring(" * ");
433                         do_dump_atomic_init(env, get_Mul_right(init));
434                         return;
435
436                 default:
437                         assert(0 && "dump_atomic_init(): unknown IR-node");
438         }
439 }
440
441 /**
442  * Dumps the type for given size (.byte, .long, ...)
443  *
444  * @param size  the size in bytes
445  */
446 static void dump_size_type(size_t size) {
447         switch (size) {
448         case 1:
449                 be_emit_cstring("\t.byte\t");
450                 break;
451
452         case 2:
453                 be_emit_cstring("\t.word\t");
454                 break;
455
456         case 4:
457                 be_emit_cstring("\t.long\t");
458                 break;
459
460         case 8:
461                 be_emit_cstring("\t.quad\t");
462                 break;
463
464         case 10:
465         case 12:
466                 /* handled in arith */
467                 break;
468
469         case 16:
470                 be_emit_cstring("\t.octa\t");
471                 break;
472
473         default:
474                 panic("Try to dump a type with %u bytes\n", (unsigned) size);
475         }
476 }
477
478 /**
479  * Emit an atomic value.
480  *
481  * @param env   the gas output environment
482  * @param init  a node representing the atomic value (on the const code irg)
483  */
484 static void dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
485 {
486         ir_mode *mode = get_irn_mode(init);
487         int bytes     = get_mode_size_bytes(mode);
488
489         dump_size_type(bytes);
490         do_dump_atomic_init(env, init);
491         be_emit_char('\n');
492         be_emit_write_line();
493 }
494
495 /************************************************************************/
496 /* Routines to dump global variables                                    */
497 /************************************************************************/
498
499 static int initializer_is_string_const(const ir_initializer_t *initializer)
500 {
501         size_t i, len;
502         int found_printable = 0;
503
504         if(initializer->kind != IR_INITIALIZER_COMPOUND)
505                 return 0;
506
507         len = initializer->compound.n_initializers;
508         if (len < 1)
509                 return 0;
510         for(i = 0; i < len; ++i) {
511                 int               c;
512                 tarval           *tv;
513                 ir_mode          *mode;
514                 ir_initializer_t *sub_initializer
515                         = initializer->compound.initializers[i];
516
517                 if(sub_initializer->kind != IR_INITIALIZER_TARVAL)
518                         return 0;
519
520                 tv   = sub_initializer->tarval.value;
521                 mode = get_tarval_mode(tv);
522
523                 if (!mode_is_int(mode)
524                                 || get_mode_size_bits(mode) != get_mode_size_bits(mode_Bs))
525                         return 0;
526
527                 c = get_tarval_long(tv);
528                 if (isgraph(c) || isspace(c))
529                         found_printable = 1;
530                 else if(c != 0)
531                         return 0;
532
533                 if (i == len - 1 && c != '\0')
534                         return 0;
535         }
536
537         return found_printable;
538 }
539
540 /**
541  * Determine if an entity is a string constant
542  * @param ent The entity
543  * @return 1 if it is a string constant, 0 otherwise
544  */
545 static int ent_is_string_const(ir_entity *ent)
546 {
547         ir_type *type, *element_type;
548         ir_mode *mode;
549         int i, c, n;
550         int found_printable = 0;
551
552         type = get_entity_type(ent);
553
554         /* if it's an array */
555         if (!is_Array_type(type))
556                 return 0;
557
558         element_type = get_array_element_type(type);
559
560         /* and the array's element type is primitive */
561         if (!is_Primitive_type(element_type))
562                 return 0;
563
564         /* and the mode of the element type is an int of
565          * the same size as the byte mode */
566         mode = get_type_mode(element_type);
567         if (!mode_is_int(mode)
568                 || get_mode_size_bits(mode) != get_mode_size_bits(mode_Bs))
569                 return 0;
570
571         if(ent->has_initializer) {
572                 /* TODO */
573                 return 0;
574         } else {
575                 /* if it contains only printable chars and a 0 at the end */
576                 n = get_compound_ent_n_values(ent);
577                 for (i = 0; i < n; ++i) {
578                         ir_node *irn = get_compound_ent_value(ent, i);
579                         if (! is_Const(irn))
580                                 return 0;
581
582                         c = (int) get_tarval_long(get_Const_tarval(irn));
583
584                         if (isgraph(c) || isspace(c))
585                                 found_printable = 1;
586                         else if(c != 0)
587                                 return 0;
588
589                         if (i == n - 1 && c != '\0')
590                                 return 0;
591                 }
592         }
593
594         /* then we can emit it as a string constant */
595         return found_printable;
596 }
597
598 /**
599  * Dump a string constant.
600  * No checks are made!!
601  *
602  * @param ent  The entity to dump.
603  */
604 static void dump_string_cst(ir_entity *ent)
605 {
606         int      i, len;
607         ir_type *type;
608         int      type_size;
609         int      remaining_space;
610
611         len = get_compound_ent_n_values(ent);
612         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
613                 be_emit_cstring("\t.ascii \"");
614         } else {
615                 be_emit_cstring("\t.string \"");
616                 len -= 1;
617         }
618
619         for (i = 0; i < len; ++i) {
620                 ir_node *irn;
621                 int c;
622
623                 irn = get_compound_ent_value(ent, i);
624                 c = (int) get_tarval_long(get_Const_tarval(irn));
625
626                 switch (c) {
627                 case '"' : be_emit_cstring("\\\""); break;
628                 case '\n': be_emit_cstring("\\n"); break;
629                 case '\r': be_emit_cstring("\\r"); break;
630                 case '\t': be_emit_cstring("\\t"); break;
631                 case '\\': be_emit_cstring("\\\\"); break;
632                 default  :
633                         if (isprint(c))
634                                 be_emit_char(c);
635                         else
636                                 be_emit_irprintf("\\%o", c);
637                         break;
638                 }
639         }
640         be_emit_cstring("\"\n");
641         be_emit_write_line();
642
643         type            = get_entity_type(ent);
644         type_size       = get_type_size_bytes(type);
645         remaining_space = type_size - len;
646         assert(remaining_space >= 0);
647         if(remaining_space > 0) {
648                 be_emit_irprintf("\t.skip\t%d\n", remaining_space);
649         }
650 }
651
652 static void dump_string_initializer(const ir_initializer_t *initializer)
653 {
654         size_t i, len;
655
656         len = initializer->compound.n_initializers;
657         if(be_gas_flavour == GAS_FLAVOUR_MACH_O) {
658                 be_emit_cstring("\t.ascii \"");
659         } else {
660                 be_emit_cstring("\t.string \"");
661                 len -= 1;
662         }
663
664         for(i = 0; i < len; ++i) {
665                 const ir_initializer_t *sub_initializer
666                         = get_initializer_compound_value(initializer, i);
667
668                 tarval *tv = get_initializer_tarval_value(sub_initializer);
669                 int     c  = get_tarval_long(tv);
670
671                 switch (c) {
672                 case '"' : be_emit_cstring("\\\""); break;
673                 case '\n': be_emit_cstring("\\n"); break;
674                 case '\r': be_emit_cstring("\\r"); break;
675                 case '\t': be_emit_cstring("\\t"); break;
676                 case '\\': be_emit_cstring("\\\\"); break;
677                 default  :
678                         if (isprint(c))
679                                 be_emit_char(c);
680                         else
681                                 be_emit_irprintf("\\%o", c);
682                         break;
683                 }
684         }
685         be_emit_cstring("\"\n");
686         be_emit_write_line();
687 }
688
689 enum normal_or_bitfield_kind {
690         NORMAL = 0,
691         TARVAL,
692         BITFIELD
693 };
694
695 typedef struct {
696         enum normal_or_bitfield_kind kind;
697         union {
698                 ir_node       *value;
699                 tarval        *tarval;
700                 unsigned char  bf_val;
701         } v;
702 } normal_or_bitfield;
703
704 static int is_type_variable_size(ir_type *type)
705 {
706         (void) type;
707         /* TODO */
708         return 0;
709 }
710
711 static size_t get_initializer_size(const ir_initializer_t *initializer,
712                                    ir_type *type)
713 {
714         switch(get_initializer_kind(initializer)) {
715         case IR_INITIALIZER_TARVAL: {
716                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
717                 return get_type_size_bytes(type);
718         }
719         case IR_INITIALIZER_CONST:
720         case IR_INITIALIZER_NULL:
721                 return get_type_size_bytes(type);
722         case IR_INITIALIZER_COMPOUND: {
723                 if(!is_type_variable_size(type)) {
724                         return get_type_size_bytes(type);
725                 } else {
726                         unsigned n_entries
727                                 = get_initializer_compound_n_entries(initializer);
728                         unsigned i;
729                         unsigned initializer_size = get_type_size_bytes(type);
730                         for(i = 0; i < n_entries; ++i) {
731                                 ir_entity *entity = get_compound_member(type, i);
732                                 ir_type   *type   = get_entity_type(entity);
733
734                                 const ir_initializer_t *sub_initializer
735                                         = get_initializer_compound_value(initializer, i);
736
737                                 unsigned offset = get_entity_offset(entity);
738                                 unsigned size   = get_initializer_size(sub_initializer, type);
739
740                                 if(offset + size > initializer_size) {
741                                         initializer_size = offset + size;
742                                 }
743                         }
744                         return initializer_size;
745                 }
746         }
747         }
748
749         panic("found invalid initializer");
750 }
751
752 #ifndef NDEBUG
753 static normal_or_bitfield *glob_vals;
754 static size_t              max_vals;
755 #endif
756
757 static void dump_bitfield(normal_or_bitfield *vals, size_t offset_bits,
758                           const ir_initializer_t *initializer, ir_type *type)
759 {
760         unsigned char  last_bits = 0;
761         ir_mode       *mode      = get_type_mode(type);
762         tarval        *tv        = NULL;
763         unsigned char  curr_bits;
764         int            value_len;
765         int            j;
766
767         switch(get_initializer_kind(initializer)) {
768         case IR_INITIALIZER_NULL:
769                 return;
770         case IR_INITIALIZER_TARVAL:
771                 tv = get_initializer_tarval_value(initializer);
772                 break;
773         case IR_INITIALIZER_CONST: {
774                 ir_node *node = get_initializer_const_value(initializer);
775                 if(!is_Const(node)) {
776                         panic("bitfield initializer not a Const node");
777                 }
778                 tv = get_Const_tarval(node);
779                 break;
780         }
781         case IR_INITIALIZER_COMPOUND:
782                 panic("bitfield initializer is compound");
783         }
784         if (tv == NULL) {
785                 panic("Couldn't get numeric value for bitfield initializer\n");
786         }
787
788         /* normalize offset */
789         vals        += offset_bits >> 3;
790         offset_bits &= 7;
791         value_len    = get_mode_size_bits(mode);
792
793         /* combine bits with existing bits */
794         for (j = 0; value_len + (int) offset_bits > 0; ++j) {
795                 assert((size_t) (vals - glob_vals) + j < max_vals);
796                 assert(vals[j].kind == BITFIELD ||
797                                 (vals[j].kind == NORMAL && vals[j].v.value == NULL));
798                 vals[j].kind = BITFIELD;
799                 curr_bits    = get_tarval_sub_bits(tv, j);
800                 vals[j].v.bf_val
801                         |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
802                 value_len -= 8;
803                 last_bits = curr_bits;
804         }
805 }
806
807 static void dump_ir_initializer(normal_or_bitfield *vals,
808                                 const ir_initializer_t *initializer,
809                                 ir_type *type)
810 {
811         assert((size_t) (vals - glob_vals) < max_vals);
812
813         switch(get_initializer_kind(initializer)) {
814         case IR_INITIALIZER_NULL:
815                 return;
816         case IR_INITIALIZER_TARVAL: {
817                 size_t i;
818
819                 assert(vals->kind != BITFIELD);
820                 vals->kind     = TARVAL;
821                 vals->v.tarval = get_initializer_tarval_value(initializer);
822                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
823                 for(i = 1; i < get_type_size_bytes(type); ++i) {
824                         vals[i].kind    = NORMAL;
825                         vals[i].v.value = NULL;
826                 }
827                 return;
828         }
829         case IR_INITIALIZER_CONST: {
830                 size_t i;
831
832                 assert(vals->kind != BITFIELD);
833                 vals->kind    = NORMAL;
834                 vals->v.value = get_initializer_const_value(initializer);
835                 for(i = 1; i < get_type_size_bytes(type); ++i) {
836                         vals[i].kind    = NORMAL;
837                         vals[i].v.value = NULL;
838                 }
839                 return;
840         }
841         case IR_INITIALIZER_COMPOUND: {
842                 size_t i = 0;
843                 size_t n = get_initializer_compound_n_entries(initializer);
844
845                 if(is_Array_type(type)) {
846                         ir_type *element_type = get_array_element_type(type);
847                         size_t   skip         = get_type_size_bytes(element_type);
848                         size_t   alignment    = get_type_alignment_bytes(element_type);
849                         size_t   misalign     = skip % alignment;
850                         if(misalign != 0) {
851                                 skip += alignment - misalign;
852                         }
853
854                         for(i = 0; i < n; ++i) {
855                                 ir_initializer_t *sub_initializer
856                                         = get_initializer_compound_value(initializer, i);
857
858                                 dump_ir_initializer(vals, sub_initializer, element_type);
859
860                                 vals += skip;
861                         }
862                 } else {
863                         size_t n_members, i;
864                         assert(is_compound_type(type));
865                         n_members = get_compound_n_members(type);
866                         for(i = 0; i < n_members; ++i) {
867                                 ir_entity        *member    = get_compound_member(type, i);
868                                 size_t            offset    = get_entity_offset(member);
869                                 ir_type          *subtype   = get_entity_type(member);
870                                 ir_mode          *mode      = get_type_mode(subtype);
871                                 ir_initializer_t *sub_initializer;
872
873                                 assert(i < get_initializer_compound_n_entries(initializer));
874                                 sub_initializer
875                                         = get_initializer_compound_value(initializer, i);
876
877                                 if(mode != NULL) {
878                                         size_t offset_bits
879                                                 = get_entity_offset_bits_remainder(member);
880                                         size_t value_len   = get_mode_size_bits(mode);
881
882                                         if(offset_bits != 0 ||
883                                                 (value_len != 8 && value_len != 16 && value_len != 32
884                                                  && value_len != 64)) {
885                                                 dump_bitfield(&vals[offset], offset_bits,
886                                                               sub_initializer, subtype);
887                                                 continue;
888                                         }
889                                 }
890
891                                 dump_ir_initializer(&vals[offset], sub_initializer, subtype);
892                         }
893                 }
894
895                 return;
896         }
897         }
898         panic("invalid ir_initializer kind found");
899 }
900
901 static void dump_initializer(be_gas_decl_env_t *env, ir_entity *entity)
902 {
903         const ir_initializer_t *initializer = entity->attr.initializer;
904         ir_type                *type;
905         normal_or_bitfield     *vals;
906         size_t                  size;
907         size_t                  k;
908
909         if(initializer_is_string_const(initializer)) {
910                 dump_string_initializer(initializer);
911                 return;
912         }
913
914         type = get_entity_type(entity);
915         size = get_initializer_size(initializer, type);
916
917         if (size == 0)
918                 return;
919
920         /*
921          * In the worst case, every initializer allocates one byte.
922          * Moreover, initializer might be big, do not allocate on stack.
923          */
924         vals = xcalloc(size, sizeof(vals[0]));
925
926 #ifndef NDEBUG
927         glob_vals = vals;
928         max_vals  = size;
929 #endif
930
931         dump_ir_initializer(vals, initializer, type);
932
933         /* now write values sorted */
934         for (k = 0; k < size; ) {
935                 int space     = 0;
936                 int elem_size = 1;
937                 if (vals[k].kind == NORMAL) {
938                         if(vals[k].v.value != NULL) {
939                                 dump_atomic_init(env, vals[k].v.value);
940                                 elem_size = get_mode_size_bytes(get_irn_mode(vals[k].v.value));
941                         } else {
942                                 elem_size = 0;
943                         }
944                 } else if(vals[k].kind == TARVAL) {
945                         tarval *tv   = vals[k].v.tarval;
946                         size_t  size = get_mode_size_bytes(get_tarval_mode(tv));
947
948                         assert(tv != NULL);
949
950                         elem_size = size;
951                         dump_size_type(size);
952                         dump_arith_tarval(tv, size);
953                         be_emit_char('\n');
954                         be_emit_write_line();
955                 } else {
956                         assert(vals[k].kind == BITFIELD);
957                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
958                         be_emit_write_line();
959                 }
960
961                 k += elem_size;
962                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
963                         ++space;
964                         ++k;
965                 }
966
967                 /* a gap */
968                 if (space > 0) {
969                         be_emit_irprintf("\t.skip\t%d\n", space);
970                         be_emit_write_line();
971                 }
972         }
973         xfree(vals);
974 }
975
976 /**
977  * Dump an initializer for a compound entity.
978  */
979 static void dump_compound_init(be_gas_decl_env_t *env, ir_entity *ent)
980 {
981         normal_or_bitfield *vals;
982         int i, j, n;
983         unsigned k, last_ofs;
984
985         if(ent->has_initializer) {
986                 dump_initializer(env, ent);
987                 return;
988         }
989
990         n = get_compound_ent_n_values(ent);
991
992         /* Find the initializer size. Sorrily gcc support a nasty feature:
993            The last field of a compound may be a flexible array. This allows
994            initializers bigger than the type size. */
995         last_ofs = get_type_size_bytes(get_entity_type(ent));
996         for (i = 0; i < n; ++i) {
997                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
998                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
999                 ir_node  *value         = get_compound_ent_value(ent, i);
1000                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1001
1002                 offset += (value_len + bits_remainder + 7) >> 3;
1003
1004                 if (offset > last_ofs) {
1005                         last_ofs = offset;
1006                 }
1007         }
1008
1009         /*
1010          * In the worst case, every initializer allocates one byte.
1011          * Moreover, initializer might be big, do not allocate on stack.
1012          */
1013         vals = xcalloc(last_ofs, sizeof(vals[0]));
1014
1015         /* collect the values and store them at the offsets */
1016         for (i = 0; i < n; ++i) {
1017                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1018                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1019                 ir_node  *value      = get_compound_ent_value(ent, i);
1020                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1021
1022                 assert(offset_bits >= 0);
1023
1024                 if (offset_bits != 0 ||
1025                         (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1026                         tarval *tv = get_atomic_init_tv(value);
1027                         unsigned char curr_bits, last_bits = 0;
1028                         if (tv == NULL) {
1029                                 panic("Couldn't get numeric value for bitfield initializer '%s'\n",
1030                                       get_entity_ld_name(ent));
1031                         }
1032                         /* normalize offset */
1033                         offset += offset_bits >> 3;
1034                         offset_bits &= 7;
1035
1036                         for (j = 0; value_len + offset_bits > 0; ++j) {
1037                                 assert(offset + j < last_ofs);
1038                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1039                                 vals[offset + j].kind = BITFIELD;
1040                                 curr_bits = get_tarval_sub_bits(tv, j);
1041                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1042                                 value_len -= 8;
1043                                 last_bits = curr_bits;
1044                         }
1045                 } else {
1046                         int i;
1047
1048                         assert(offset < last_ofs);
1049                         assert(vals[offset].kind == NORMAL);
1050                         for (i = 1; i < value_len / 8; ++i) {
1051                                 assert(vals[offset + i].v.value == NULL);
1052                         }
1053                         vals[offset].v.value = value;
1054                 }
1055         }
1056
1057         /* now write them sorted */
1058         for (k = 0; k < last_ofs; ) {
1059                 int space = 0, skip = 0;
1060                 if (vals[k].kind == NORMAL) {
1061                         if(vals[k].v.value != NULL) {
1062                                 dump_atomic_init(env, vals[k].v.value);
1063                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1064                         } else {
1065                                 space = 1;
1066                         }
1067                 } else {
1068                         assert(vals[k].kind == BITFIELD);
1069                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1070                 }
1071
1072                 ++k;
1073                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1074                         ++space;
1075                         ++k;
1076                 }
1077                 space -= skip;
1078                 assert(space >= 0);
1079
1080                 /* a gap */
1081                 if (space > 0) {
1082                         be_emit_irprintf("\t.skip\t%d\n", space);
1083                         be_emit_write_line();
1084                 }
1085         }
1086         xfree(vals);
1087 }
1088
1089 static void emit_align(unsigned alignment)
1090 {
1091         if (!is_po2(alignment))
1092                 panic("alignment not a power of 2");
1093
1094         be_emit_irprintf(".p2align\t%u\n", log2_floor(alignment));
1095         be_emit_write_line();
1096 }
1097
1098 /**
1099  * Dump a global entity.
1100  *
1101  * @param env           the gas output environment
1102  * @param ent           the entity to be dumped
1103  */
1104 static void dump_global(be_gas_decl_env_t *env, ir_entity *ent)
1105 {
1106         ir_type          *type           = get_entity_type(ent);
1107         ident            *ld_ident       = get_entity_ld_ident(ent);
1108         unsigned          align          = get_type_alignment_bytes(type);
1109         int               emit_as_common = 0;
1110         be_gas_section_t  section        = env->section;
1111         ir_variability    variability    = get_entity_variability(ent);
1112         ir_visibility     visibility     = get_entity_visibility(ent);
1113
1114         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1115                 return;
1116         }
1117
1118         if (section != (be_gas_section_t) -1) {
1119                 emit_as_common = 0;
1120         } else if (variability == variability_constant) {
1121                 /* a constant entity, put it on the rdata */
1122                 section = GAS_SECTION_RODATA;
1123                 if (be_gas_flavour == GAS_FLAVOUR_MACH_O
1124                                 && ent_is_string_const(ent)) {
1125                         section = GAS_SECTION_CSTRING;
1126                 }
1127         } else if (variability == variability_uninitialized) {
1128                 /* uninitialized entity put it in bss segment */
1129                 section = GAS_SECTION_COMMON;
1130                 if (visibility != visibility_local)
1131                         emit_as_common = 1;
1132         } else {
1133                 section = GAS_SECTION_DATA;
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 && section != GAS_SECTION_PIC_TRAMPOLINES
1158                         && section != GAS_SECTION_PIC_SYMBOLS) {
1159                 emit_align(align);
1160         }
1161
1162         if (!emit_as_common) {
1163                 be_emit_ident(ld_ident);
1164                 be_emit_cstring(":\n");
1165                 be_emit_write_line();
1166         }
1167
1168         if (variability == variability_uninitialized) {
1169                 if (emit_as_common) {
1170                         switch (be_gas_flavour) {
1171                         case GAS_FLAVOUR_ELF:
1172                         case GAS_FLAVOUR_MACH_O:
1173                         case GAS_FLAVOUR_YASM:
1174                                 be_emit_irprintf("\t.comm %s,%u,%u\n",
1175                                         get_id_str(ld_ident), get_type_size_bytes(type), align);
1176                                 be_emit_write_line();
1177                                 break;
1178                         case GAS_FLAVOUR_MINGW:
1179                                 be_emit_irprintf("\t.comm %s,%u # %u\n",
1180                                         get_id_str(ld_ident), get_type_size_bytes(type), align);
1181                                 be_emit_write_line();
1182                                 break;
1183                         }
1184                 } else if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1185                         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
1186                                 be_emit_cstring("\t.indirect_symbol ");
1187                                 be_emit_ident(get_entity_ident(ent));
1188                                 be_emit_char('\n');
1189                                 be_emit_write_line();
1190                                 be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1191                                 be_emit_write_line();
1192                         } else {
1193                                 panic("PIC trampolines not yet supported in this gas mode");
1194                         }
1195                 } else {
1196                         be_emit_irprintf("\t.space %u\n", get_type_size_bytes(type));
1197                         be_emit_write_line();
1198                 }
1199         } else {
1200                 if (is_atomic_entity(ent)) {
1201                         dump_atomic_init(env, get_atomic_ent_value(ent));
1202                 } else {
1203                         /* sort_compound_ent_values(ent); */
1204
1205                         switch (get_type_tpop_code(get_entity_type(ent))) {
1206                         case tpo_array:
1207                                 if (ent_is_string_const(ent))
1208                                         dump_string_cst(ent);
1209                                 else
1210                                         dump_compound_init(env, ent);
1211                                 break;
1212                         case tpo_struct:
1213                         case tpo_class:
1214                         case tpo_union:
1215                                 dump_compound_init(env, ent);
1216                                 break;
1217                         default:
1218                                 assert(0);
1219                         }
1220                 }
1221         }
1222 }
1223
1224 /**
1225  * Dumps declarations of global variables and the initialization code.
1226  *
1227  * @param gt                a global like type, either the global or the TLS one
1228  * @param env               an environment
1229  * @param only_emit_marked  if non-zero, external allocated entities that do not have
1230  *                          its visited flag set are ignored
1231  */
1232 static void be_gas_dump_globals(ir_type *gt, be_gas_decl_env_t *env,
1233                                 int only_emit_marked)
1234 {
1235         int i, n = get_compound_n_members(gt);
1236         waitq *worklist = new_waitq();
1237
1238         if (only_emit_marked) {
1239                 for (i = 0; i < n; i++) {
1240                         ir_entity *ent = get_compound_member(gt, i);
1241                         if (is_entity_backend_marked(ent) ||
1242                             get_entity_visibility(ent) != visibility_external_allocated) {
1243                                 waitq_put(worklist, ent);
1244                                 set_entity_backend_marked(ent, 1);
1245                         }
1246                 }
1247         } else {
1248                 for (i = 0; i < n; i++) {
1249                         ir_entity *ent = get_compound_member(gt, i);
1250                         set_entity_backend_marked(ent, 1);
1251                         waitq_put(worklist, ent);
1252                 }
1253         }
1254
1255         env->worklist = worklist;
1256
1257         while (!waitq_empty(worklist)) {
1258                 ir_entity *ent = waitq_get(worklist);
1259
1260                 dump_global(env, ent);
1261         }
1262
1263         del_waitq(worklist);
1264         env->worklist = NULL;
1265 }
1266
1267 /************************************************************************/
1268
1269 /* Generate all entities. */
1270 void be_gas_emit_decls(const be_main_env_t *main_env,
1271                        int only_emit_marked_entities)
1272 {
1273         be_gas_decl_env_t env;
1274         memset(&env, 0, sizeof(env));
1275
1276         env.main_env = main_env;
1277
1278         /* dump global type */
1279         env.section = (be_gas_section_t) -1;
1280         be_gas_dump_globals(get_glob_type(), &env, only_emit_marked_entities);
1281         env.section = GAS_SECTION_TLS;
1282         be_gas_dump_globals(get_tls_type(), &env, only_emit_marked_entities);
1283         env.section = GAS_SECTION_CTOR;
1284         be_gas_dump_globals(get_constructors_type(), &env,
1285                             only_emit_marked_entities);
1286         env.section = GAS_SECTION_PIC_SYMBOLS;
1287         be_gas_dump_globals(main_env->pic_symbols_type, &env,
1288                             only_emit_marked_entities);
1289
1290         if (get_compound_n_members(main_env->pic_trampolines_type) > 0) {
1291                 env.section = GAS_SECTION_PIC_TRAMPOLINES;
1292                 be_gas_dump_globals(main_env->pic_trampolines_type, &env,
1293                                     only_emit_marked_entities);
1294                 if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
1295                         be_emit_cstring("\t.subsections_via_symbols\n");
1296                         be_emit_write_line();
1297                 }
1298         }
1299 }