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