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