f67f76366072a9552da94859f5493f6c37000a16
[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 object_file_format_t  be_gas_object_file_format = OBJECT_FILE_FORMAT_ELF;
50 bool                  be_gas_emit_types         = true;
51 char                  be_gas_elf_type_char = '@';
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 {
65         static const char *text[OBJECT_FILE_FORMAT_LAST+1][GAS_SECTION_LAST+1] = {
66                 { /* OBJECT_FILE_FORMAT_ELF */
67                         ".section\t.text",
68                         ".section\t.data",
69                         ".section\t.rodata",
70                         ".section\t.bss",
71                         ".section\t.tbss,\"awT\",@nobits",
72                         ".section\t.ctors,\"aw\",@progbits",
73                         ".section\t.dtors,\"aw\",@progbits",
74                         NULL, /* no cstring section */
75                         NULL,
76                         NULL
77                 },
78                 { /* OBJECT_FILE_FORMAT_COFF */
79                         ".section\t.text",
80                         ".section\t.data",
81                         ".section .rdata,\"dr\"",
82                         ".section\t.bss",
83                         ".section\t.tbss,\"awT\",@nobits",
84                         ".section\t.ctors,\"w\"",
85                         ".section\t.dtors,\"w\"",
86                         NULL,
87                         NULL,
88                         NULL
89                 },
90                 { /* OBJECT_FILE_FORMAT_MACH_O */
91                         ".text",
92                         ".data",
93                         ".const",
94                         ".data",
95                         NULL,             /* TLS is not supported on Mach-O */
96                         ".mod_init_func",
97                         NULL,             /* are there destructors on mach-o? */
98                         ".cstring",
99                         ".section\t__IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5",
100                         ".section\t__IMPORT,__pointers,non_lazy_symbol_pointers"
101                 }
102         };
103
104         assert((int) be_gas_object_file_format >= 0
105                         && be_gas_object_file_format <= OBJECT_FILE_FORMAT_LAST);
106         assert((int) section >= 0 && section <= GAS_SECTION_LAST);
107         return text[be_gas_object_file_format][section];
108 }
109
110 void be_gas_emit_switch_section(be_gas_section_t section)
111 {
112         if (current_section == section)
113                 return;
114
115         be_emit_char('\t');
116         be_emit_string(get_section_name(section));
117         be_emit_char('\n');
118         be_emit_write_line();
119         current_section = section;
120 }
121
122 static void emit_entity_visibility(const ir_entity *entity)
123 {
124         ir_linkage linkage = get_entity_linkage(entity);
125
126         if (! (linkage & IR_LINKAGE_LOCAL)) {
127                 be_emit_cstring(".globl ");
128                 be_emit_ident(get_entity_ld_ident(entity));
129                 be_emit_char('\n');
130                 be_emit_write_line();
131         }
132         if (linkage & IR_LINKAGE_WEAK) {
133                 if (! (linkage & IR_LINKAGE_MERGE)) {
134                         panic("Weak symbols only supported in combination with IR_LINKAGE_MERGE on this architecture");
135                 }
136                 be_emit_cstring(".weak ");
137                 be_emit_ident(get_entity_ld_ident(entity));
138                 be_emit_char('\n');
139                 be_emit_write_line();
140         }
141 }
142
143 void be_gas_emit_function_prolog(ir_entity *entity, unsigned po2alignment)
144 {
145         const char *name = get_entity_ld_name(entity);
146
147         be_gas_emit_switch_section(GAS_SECTION_TEXT);
148
149         /* write the begin line (makes the life easier for scripts parsing the
150          * assembler) */
151         be_emit_write_line();
152         be_emit_cstring("# -- Begin  ");
153         be_emit_string(name);
154         be_emit_char('\n');
155         be_emit_write_line();
156
157         if (po2alignment > 0) {
158                 const char *fill_byte = "";
159                 unsigned    maximum_skip = (1 << po2alignment) - 1;
160                 /* gcc fills space between function with 0x90... */
161                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
162                         fill_byte = "0x90";
163                 }
164                 be_emit_cstring("\t.p2align ");
165                 be_emit_irprintf("%u,%s,%u\n", po2alignment, fill_byte, maximum_skip);
166                 be_emit_write_line();
167         }
168         emit_entity_visibility(entity);
169
170         switch (be_gas_object_file_format) {
171         case OBJECT_FILE_FORMAT_ELF:
172                 be_emit_cstring("\t.type\t");
173                 be_emit_string(name);
174                 be_emit_cstring(", ");
175                 be_emit_char(be_gas_elf_type_char);
176                 be_emit_cstring("function\n");
177                 be_emit_write_line();
178                 break;
179         case OBJECT_FILE_FORMAT_COFF:
180                 be_emit_cstring("\t.def\t");
181                 be_emit_string(name);
182                 be_emit_cstring(";");
183                 if (get_entity_linkage(entity) & IR_LINKAGE_LOCAL) {
184                         be_emit_cstring("\t.scl\t3;");
185                 } else {
186                         be_emit_cstring("\t.scl\t2;");
187                 }
188                 be_emit_cstring("\t.type\t32;\t.endef\n");
189                 be_emit_write_line();
190                 break;
191         case OBJECT_FILE_FORMAT_MACH_O:
192                 break;
193         }
194         be_emit_string(name);
195         be_emit_cstring(":\n");
196         be_emit_write_line();
197 }
198
199 void be_gas_emit_function_epilog(ir_entity *entity)
200 {
201         const char *name = get_entity_ld_name(entity);
202
203         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF) {
204                 be_emit_cstring("\t.size\t");
205                 be_emit_string(name);
206                 be_emit_cstring(", .-");
207                 be_emit_string(name);
208                 be_emit_char('\n');
209                 be_emit_write_line();
210         }
211
212         be_emit_cstring("# -- End  ");
213         be_emit_string(name);
214         be_emit_char('\n');
215         be_emit_write_line();
216 }
217
218 /**
219  * An environment containing all needed dumper data.
220  * Currently we create the file completely in memory first, then
221  * write it to the disk. This is an artifact from the old C-generating backend
222  * and even there NOT needed. So we might change it in the future.
223  */
224 typedef struct _be_gas_decl_env {
225         be_gas_section_t     section;
226         waitq               *worklist;           /**< A worklist we use to place not yet handled entities on. */
227         const be_main_env_t       *main_env;
228 } be_gas_decl_env_t;
229
230 /************************************************************************/
231
232 /**
233  * Output a tarval.
234  *
235  * @param tv     the tarval
236  * @param bytes  the width of the tarvals value in bytes
237  */
238 static void dump_arith_tarval(tarval *tv, int bytes)
239 {
240         switch (bytes) {
241         case 1:
242                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
243                 return;
244
245         case 2:
246                 be_emit_irprintf("0x%02x%02x", get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
247                 return;
248
249         case 4:
250                 be_emit_irprintf("0x%02x%02x%02x%02x",
251                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
252                 return;
253
254         case 8:
255                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
256                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6), get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
257                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
258                 return;
259
260         case 12:
261                 /* Beware: Mixed endian output!  One little endian number emitted as
262                  * three longs.  Each long initializer is written in big endian. */
263                 be_emit_irprintf(
264                         "\t.long\t0x%02x%02x%02x%02x\n"
265                         "\t.long\t0x%02x%02x%02x%02x\n"
266                         "\t.long\t0x%02x%02x%02x%02x",
267                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
268                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
269                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
270                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
271                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
272                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
273                 );
274                 return;
275
276         case 16:
277                 be_emit_irprintf(
278                         "\t.long\t0x%02x%02x%02x%02x0x%02x%02x%02x%02x0x%02x%02x%02x%02x0x%02x%02x%02x%02x",
279                         get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 16),
280                         get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12),
281                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
282                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
283                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
284                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
285                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
286                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0)
287                 );
288                 return;
289         }
290
291         panic("Can't dump a tarval with %d bytes", bytes);
292 }
293
294 /**
295  * Return the label prefix for labeled blocks.
296  */
297 const char *be_gas_block_label_prefix(void)
298 {
299         return ".LG";
300 }
301
302 /**
303  * Return the label prefix for labeled instructions.
304  */
305 const char *be_gas_insn_label_prefix(void)
306 {
307         return ".LE";
308 }
309
310 void be_gas_emit_entity(ir_entity *entity)
311 {
312         if (entity->type == firm_code_type) {
313                 ir_label_t label = get_entity_label(entity);
314                 be_emit_string(be_gas_block_label_prefix());
315                 be_emit_irprintf("%lu", label);
316         } else {
317                 be_emit_ident(get_entity_ld_ident(entity));
318         }
319 }
320
321 /**
322  * Return the tarval of an atomic initializer.
323  *
324  * @param init  a node representing the initializer (on the const code irg)
325  *
326  * @return the tarval
327  */
328 static tarval *get_atomic_init_tv(ir_node *init)
329 {
330         for (;;) {
331                 ir_mode *mode = get_irn_mode(init);
332
333                 switch (get_irn_opcode(init)) {
334
335                 case iro_Cast:
336                         init = get_Cast_op(init);
337                         continue;
338
339                 case iro_Conv:
340                         init = get_Conv_op(init);
341                         continue;
342
343                 case iro_Const:
344                         return get_Const_tarval(init);
345
346                 case iro_SymConst:
347                         switch (get_SymConst_kind(init)) {
348                         case symconst_type_size:
349                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
350
351                         case symconst_type_align:
352                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
353
354                         case symconst_ofs_ent:
355                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
356
357                         case symconst_enum_const:
358                                 return get_enumeration_value(get_SymConst_enum(init));
359
360                         default:
361                                 return NULL;
362                         }
363
364                 default:
365                         return NULL;
366                 }
367         }
368 }
369
370 /**
371  * Dump an atomic value.
372  *
373  * @param env   the gas output environment
374  * @param init  a node representing the atomic value (on the const code irg)
375  */
376 static void do_dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
377 {
378         ir_mode *mode = get_irn_mode(init);
379         int bytes     = get_mode_size_bytes(mode);
380         tarval *tv;
381         ir_entity *ent;
382
383         init = skip_Id(init);
384
385         switch (get_irn_opcode(init)) {
386         case iro_Cast:
387                 do_dump_atomic_init(env, get_Cast_op(init));
388                 return;
389
390         case iro_Conv:
391                 do_dump_atomic_init(env, get_Conv_op(init));
392                 return;
393
394         case iro_Const:
395                 tv = get_Const_tarval(init);
396
397                 /* it's a arithmetic value */
398                 dump_arith_tarval(tv, bytes);
399                 return;
400
401         case iro_SymConst:
402                 switch (get_SymConst_kind(init)) {
403                 case symconst_addr_name:
404                         be_emit_ident(get_SymConst_name(init));
405                         break;
406
407                 case symconst_addr_ent:
408                         ent = get_SymConst_entity(init);
409                         if (!is_entity_backend_marked(ent)) {
410                                 waitq_put(env->worklist, ent);
411                                 set_entity_backend_marked(ent, 1);
412                         }
413                         be_gas_emit_entity(ent);
414                         break;
415
416                 case symconst_ofs_ent:
417                         ent = get_SymConst_entity(init);
418                         be_emit_irprintf("%d", get_entity_offset(ent));
419                         break;
420
421                 case symconst_type_size:
422                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
423                         break;
424
425                 case symconst_type_align:
426                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
427                         break;
428
429                 case symconst_enum_const:
430                         tv = get_enumeration_value(get_SymConst_enum(init));
431                         dump_arith_tarval(tv, bytes);
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         case iro_Unknown:
467                 be_emit_cstring("0");
468                 return;
469
470         default:
471                 panic("dump_atomic_init(): unsupported IR-node %+F", init);
472         }
473 }
474
475 /**
476  * Dumps the type for given size (.byte, .long, ...)
477  *
478  * @param size  the size in bytes
479  */
480 static void dump_size_type(size_t size) {
481         switch (size) {
482         case 1:
483                 be_emit_cstring("\t.byte\t");
484                 break;
485
486         case 2:
487                 be_emit_cstring("\t.short\t");
488                 break;
489
490         case 4:
491                 be_emit_cstring("\t.long\t");
492                 break;
493
494         case 8:
495                 be_emit_cstring("\t.quad\t");
496                 break;
497
498         case 10:
499         case 12:
500                 /* handled in arith */
501                 break;
502
503         case 16:
504                 be_emit_cstring("\t.octa\t");
505                 break;
506
507         default:
508                 panic("Try to dump a type with %u bytes", (unsigned)size);
509         }
510 }
511
512 /**
513  * Emit an atomic value.
514  *
515  * @param env   the gas output environment
516  * @param init  a node representing the atomic value (on the const code irg)
517  */
518 static void dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
519 {
520         ir_mode *mode = get_irn_mode(init);
521         int bytes     = get_mode_size_bytes(mode);
522
523         dump_size_type(bytes);
524         do_dump_atomic_init(env, init);
525         be_emit_char('\n');
526         be_emit_write_line();
527 }
528
529 /************************************************************************/
530 /* Routines to dump global variables                                    */
531 /************************************************************************/
532
533 static int initializer_is_string_const(const ir_initializer_t *initializer)
534 {
535         size_t i, len;
536         int found_printable = 0;
537
538         if (initializer->kind != IR_INITIALIZER_COMPOUND)
539                 return 0;
540
541         len = initializer->compound.n_initializers;
542         if (len < 1)
543                 return 0;
544         for (i = 0; i < len; ++i) {
545                 int               c;
546                 tarval           *tv;
547                 ir_mode          *mode;
548                 ir_initializer_t *sub_initializer
549                         = initializer->compound.initializers[i];
550
551                 if (sub_initializer->kind != IR_INITIALIZER_TARVAL)
552                         return 0;
553
554                 tv   = sub_initializer->tarval.value;
555                 mode = get_tarval_mode(tv);
556
557                 if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
558                         return 0;
559
560                 c = get_tarval_long(tv);
561                 if (isgraph(c) || isspace(c))
562                         found_printable = 1;
563                 else if (c != 0)
564                         return 0;
565
566                 if (i == len - 1 && c != '\0')
567                         return 0;
568         }
569
570         return found_printable;
571 }
572
573 /**
574  * Determine if an entity is a string constant
575  * @param ent The entity
576  * @return 1 if it is a string constant, 0 otherwise
577  */
578 static int ent_is_string_const(const ir_entity *ent)
579 {
580         ir_type *type, *element_type;
581         ir_mode *mode;
582         int i, c, n;
583
584         type = get_entity_type(ent);
585
586         /* if it's an array */
587         if (!is_Array_type(type))
588                 return 0;
589
590         element_type = get_array_element_type(type);
591
592         /* and the array's element type is primitive */
593         if (!is_Primitive_type(element_type))
594                 return 0;
595
596         /* and the mode of the element type is an int of
597          * the same size as the byte mode */
598         mode = get_type_mode(element_type);
599         if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
600                 return 0;
601
602         if (ent->initializer != NULL) {
603                 return initializer_is_string_const(ent->initializer);
604         } else if (entity_has_compound_ent_values(ent)) {
605                 int found_printable = 0;
606                 /* if it contains only printable chars and a 0 at the end */
607                 n = get_compound_ent_n_values(ent);
608                 for (i = 0; i < n; ++i) {
609                         ir_node *irn = get_compound_ent_value(ent, i);
610                         if (! is_Const(irn))
611                                 return 0;
612
613                         c = (int) get_tarval_long(get_Const_tarval(irn));
614
615                         if (isgraph(c) || isspace(c))
616                                 found_printable = 1;
617                         else if (c != 0)
618                                 return 0;
619
620                         if (i == n - 1 && c != '\0')
621                                 return 0;
622                 }
623                 return found_printable;
624         }
625
626         return 0;
627 }
628
629 /**
630  * Dump a string constant.
631  * No checks are made!!
632  *
633  * @param ent  The entity to dump.
634  */
635 static void dump_string_cst(const ir_entity *ent)
636 {
637         int      i, len;
638         int      output_len;
639         ir_type *type;
640         int      type_size;
641         int      remaining_space;
642
643         len        = get_compound_ent_n_values(ent);
644         output_len = len;
645         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
646                 be_emit_cstring("\t.ascii \"");
647         } else {
648                 be_emit_cstring("\t.string \"");
649                 output_len -= 1;
650         }
651
652         for (i = 0; i < output_len; ++i) {
653                 ir_node *irn;
654                 int c;
655
656                 irn = get_compound_ent_value(ent, i);
657                 c = (int) get_tarval_long(get_Const_tarval(irn));
658
659                 switch (c) {
660                 case '"' : be_emit_cstring("\\\""); break;
661                 case '\n': be_emit_cstring("\\n"); break;
662                 case '\r': be_emit_cstring("\\r"); break;
663                 case '\t': be_emit_cstring("\\t"); break;
664                 case '\\': be_emit_cstring("\\\\"); break;
665                 default  :
666                         if (isprint(c))
667                                 be_emit_char(c);
668                         else
669                                 be_emit_irprintf("\\%o", c);
670                         break;
671                 }
672         }
673         be_emit_cstring("\"\n");
674         be_emit_write_line();
675
676         type            = get_entity_type(ent);
677         type_size       = get_type_size_bytes(type);
678         remaining_space = type_size - len;
679         assert(remaining_space >= 0);
680         if (remaining_space > 0) {
681                 be_emit_irprintf("\t.space\t%d\n", remaining_space);
682         }
683 }
684
685 static void dump_string_initializer(const ir_initializer_t *initializer)
686 {
687         size_t i, len;
688
689         len = initializer->compound.n_initializers;
690         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
691                 be_emit_cstring("\t.ascii \"");
692         } else {
693                 be_emit_cstring("\t.string \"");
694                 len -= 1;
695         }
696
697         for (i = 0; i < len; ++i) {
698                 const ir_initializer_t *sub_initializer
699                         = get_initializer_compound_value(initializer, i);
700
701                 tarval *tv = get_initializer_tarval_value(sub_initializer);
702                 int     c  = get_tarval_long(tv);
703
704                 switch (c) {
705                 case '"' : be_emit_cstring("\\\""); break;
706                 case '\n': be_emit_cstring("\\n"); break;
707                 case '\r': be_emit_cstring("\\r"); break;
708                 case '\t': be_emit_cstring("\\t"); break;
709                 case '\\': be_emit_cstring("\\\\"); break;
710                 default  :
711                         if (isprint(c))
712                                 be_emit_char(c);
713                         else
714                                 be_emit_irprintf("\\%o", c);
715                         break;
716                 }
717         }
718         be_emit_cstring("\"\n");
719         be_emit_write_line();
720 }
721
722 enum normal_or_bitfield_kind {
723         NORMAL = 0,
724         TARVAL,
725         BITFIELD
726 };
727
728 typedef struct {
729         enum normal_or_bitfield_kind kind;
730         union {
731                 ir_node       *value;
732                 tarval        *tarval;
733                 unsigned char  bf_val;
734         } v;
735 } normal_or_bitfield;
736
737 static int is_type_variable_size(ir_type *type)
738 {
739         (void) type;
740         /* TODO */
741         return 0;
742 }
743
744 static size_t get_initializer_size(const ir_initializer_t *initializer,
745                                    ir_type *type)
746 {
747         switch (get_initializer_kind(initializer)) {
748         case IR_INITIALIZER_TARVAL:
749                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
750                 return get_type_size_bytes(type);
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         panic("found invalid initializer");
781 }
782
783 #ifndef NDEBUG
784 static normal_or_bitfield *glob_vals;
785 static size_t              max_vals;
786 #endif
787
788 static void dump_bitfield(normal_or_bitfield *vals, size_t offset_bits,
789                           const ir_initializer_t *initializer, ir_type *type)
790 {
791         unsigned char  last_bits = 0;
792         ir_mode       *mode      = get_type_mode(type);
793         tarval        *tv        = NULL;
794         unsigned char  curr_bits;
795         int            value_len;
796         int            j;
797
798         switch (get_initializer_kind(initializer)) {
799         case IR_INITIALIZER_NULL:
800                 return;
801         case IR_INITIALIZER_TARVAL:
802                 tv = get_initializer_tarval_value(initializer);
803                 break;
804         case IR_INITIALIZER_CONST: {
805                 ir_node *node = get_initializer_const_value(initializer);
806                 if (!is_Const(node)) {
807                         panic("bitfield initializer not a Const node");
808                 }
809                 tv = get_Const_tarval(node);
810                 break;
811         }
812         case IR_INITIALIZER_COMPOUND:
813                 panic("bitfield initializer is compound");
814         }
815         if (tv == NULL) {
816                 panic("Couldn't get numeric value for bitfield initializer");
817         }
818         tv = tarval_convert_to(tv, get_type_mode(type));
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, const ir_entity *entity)
934 {
935         const ir_initializer_t *initializer = entity->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 = XMALLOCNZ(normal_or_bitfield, size);
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 static void dump_compound_graph_init(be_gas_decl_env_t *env,
1009                                      const ir_entity *ent)
1010 {
1011         normal_or_bitfield *vals;
1012         int i, j, n;
1013         unsigned k, last_ofs;
1014
1015         if (ent_is_string_const(ent)) {
1016                 dump_string_cst(ent);
1017                 return;
1018         }
1019
1020         n = get_compound_ent_n_values(ent);
1021
1022         /* Find the initializer size. Sorrily gcc support a nasty feature:
1023            The last field of a compound may be a flexible array. This allows
1024            initializers bigger than the type size. */
1025         last_ofs = get_type_size_bytes(get_entity_type(ent));
1026         for (i = 0; i < n; ++i) {
1027                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1028                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1029                 ir_node  *value         = get_compound_ent_value(ent, i);
1030                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1031
1032                 offset += (value_len + bits_remainder + 7) >> 3;
1033
1034                 if (offset > last_ofs) {
1035                         last_ofs = offset;
1036                 }
1037         }
1038
1039         /*
1040          * In the worst case, every initializer allocates one byte.
1041          * Moreover, initializer might be big, do not allocate on stack.
1042          */
1043         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1044
1045         /* collect the values and store them at the offsets */
1046         for (i = 0; i < n; ++i) {
1047                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1048                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1049                 ir_node  *value      = get_compound_ent_value(ent, i);
1050                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1051
1052                 assert(offset_bits >= 0);
1053
1054                 if (offset_bits != 0 ||
1055                                 (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1056                         tarval *tv = get_atomic_init_tv(value);
1057                         unsigned char curr_bits, last_bits = 0;
1058                         if (tv == NULL) {
1059                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1060                                                 get_entity_ld_name(ent));
1061                         }
1062                         /* normalize offset */
1063                         offset += offset_bits >> 3;
1064                         offset_bits &= 7;
1065
1066                         for (j = 0; value_len + offset_bits > 0; ++j) {
1067                                 assert(offset + j < last_ofs);
1068                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1069                                 vals[offset + j].kind = BITFIELD;
1070                                 curr_bits = get_tarval_sub_bits(tv, j);
1071                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1072                                 value_len -= 8;
1073                                 last_bits = curr_bits;
1074                         }
1075                 } else {
1076                         int i;
1077
1078                         assert(offset < last_ofs);
1079                         assert(vals[offset].kind == NORMAL);
1080                         for (i = 1; i < value_len / 8; ++i) {
1081                                 assert(vals[offset + i].v.value == NULL);
1082                         }
1083                         vals[offset].v.value = value;
1084                 }
1085         }
1086
1087         /* now write them sorted */
1088         for (k = 0; k < last_ofs; ) {
1089                 int space = 0, skip = 0;
1090                 if (vals[k].kind == NORMAL) {
1091                         if (vals[k].v.value != NULL) {
1092                                 dump_atomic_init(env, vals[k].v.value);
1093                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1094                         } else {
1095                                 space = 1;
1096                         }
1097                 } else {
1098                         assert(vals[k].kind == BITFIELD);
1099                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1100                 }
1101
1102                 ++k;
1103                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1104                         ++space;
1105                         ++k;
1106                 }
1107                 space -= skip;
1108                 assert(space >= 0);
1109
1110                 /* a gap */
1111                 if (space > 0) {
1112                         be_emit_irprintf("\t.space\t%d\n", space);
1113                         be_emit_write_line();
1114                 }
1115         }
1116         xfree(vals);
1117 }
1118
1119 static void emit_align(unsigned p2alignment)
1120 {
1121         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1122         be_emit_write_line();
1123 }
1124
1125 static unsigned get_effective_entity_alignment(const ir_entity *entity)
1126 {
1127         unsigned alignment = get_entity_alignment(entity);
1128         if (alignment == 0) {
1129                 ir_type *type = get_entity_type(entity);
1130                 alignment     = get_type_alignment_bytes(type);
1131         }
1132         return alignment;
1133 }
1134
1135 static be_gas_section_t determine_section(be_gas_decl_env_t *env,
1136                                           const ir_entity *entity)
1137 {
1138         ir_type *owner = get_entity_owner(entity);
1139
1140         if (owner == get_segment_type(IR_SEGMENT_GLOBAL)) {
1141                 ir_linkage linkage = get_entity_linkage(entity);
1142                 if (linkage & IR_LINKAGE_CONSTANT) {
1143                         /* mach-o is the only one with a cstring section */
1144                         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
1145                                         && ent_is_string_const(entity))
1146                                 return GAS_SECTION_CSTRING;
1147
1148                         return GAS_SECTION_RODATA;
1149                 }
1150                 if (!entity_has_definition(entity))
1151                         return GAS_SECTION_BSS;
1152
1153                 return GAS_SECTION_DATA;
1154
1155         } else if (owner == env->main_env->pic_symbols_type) {
1156                 return GAS_SECTION_PIC_SYMBOLS;
1157         } else if (owner == env->main_env->pic_trampolines_type) {
1158                 return GAS_SECTION_PIC_TRAMPOLINES;
1159         } else if (owner == get_segment_type(IR_SEGMENT_CONSTRUCTORS)) {
1160                 return GAS_SECTION_CONSTRUCTORS;
1161         } else if (owner == get_segment_type(IR_SEGMENT_DESTRUCTORS)) {
1162                 return GAS_SECTION_DESTRUCTORS;
1163         } else if (owner == get_segment_type(IR_SEGMENT_THREAD_LOCAL)) {
1164                 return GAS_SECTION_TLS;
1165         }
1166
1167         panic("Couldn't determine section for %+F?!?", entity);
1168 }
1169
1170 static void emit_common(const ir_entity *ent)
1171 {
1172         const char *name      = get_entity_ld_name(ent);
1173         unsigned    size      = get_type_size_bytes(get_entity_type(ent));
1174         unsigned    alignment = get_effective_entity_alignment(ent);
1175
1176         switch (be_gas_object_file_format) {
1177         case OBJECT_FILE_FORMAT_MACH_O:
1178                 be_emit_irprintf("\t.comm %s,%u,%u\n", name, size,
1179                                  log2_floor(alignment));
1180                 be_emit_write_line();
1181                 return;
1182         case OBJECT_FILE_FORMAT_ELF:
1183                 be_emit_irprintf("\t.comm %s,%u,%u\n", name, size, alignment);
1184                 be_emit_write_line();
1185                 return;
1186         case OBJECT_FILE_FORMAT_COFF:
1187                 be_emit_irprintf("\t.comm %s,%u # %u\n", name, size, alignment);
1188                 be_emit_write_line();
1189                 return;
1190         }
1191         panic("invalid object file format");
1192 }
1193
1194 /**
1195  * Dump a global entity.
1196  *
1197  * @param env  the gas output environment
1198  * @param ent  the entity to be dumped
1199  */
1200 static void dump_global(be_gas_decl_env_t *env, const ir_entity *ent)
1201 {
1202         ir_type          *type           = get_entity_type(ent);
1203         ident            *ld_ident       = get_entity_ld_ident(ent);
1204         unsigned          alignment      = get_effective_entity_alignment(ent);
1205         be_gas_section_t  section        = determine_section(env, ent);
1206         ir_linkage        linkage        = get_entity_linkage(ent);
1207
1208         /* we already emitted all methods. Except for the trampolines which
1209          * the assembler/linker generates */
1210         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1211                 return;
1212         }
1213         /* block labels are already emittet in the code */
1214         if (type == firm_code_type)
1215                 return;
1216
1217         be_dbg_variable(ent);
1218
1219         /* nothing to do for externally defined values */
1220         if (linkage & IR_LINKAGE_EXTERN)
1221                 return;
1222
1223         if (!is_po2(alignment))
1224                 panic("alignment not a power of 2");
1225
1226         if (section == GAS_SECTION_BSS &&
1227                         (get_entity_linkage(ent) & IR_LINKAGE_MERGE)) {
1228                 emit_common(ent);
1229                 return;
1230         }
1231
1232         be_gas_emit_switch_section(section);
1233
1234         /* alignment */
1235         if (alignment > 1) {
1236                 emit_align(alignment);
1237         }
1238         emit_entity_visibility(ent);
1239         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF
1240                         && be_gas_emit_types) {
1241                 be_emit_cstring("\t.type\t");
1242                 be_emit_ident(ld_ident);
1243                 be_emit_cstring(", ");
1244                 be_emit_char(be_gas_elf_type_char);
1245                 be_emit_cstring("object\n\t.size\t");
1246                 be_emit_ident(ld_ident);
1247                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1248         }
1249         be_emit_ident(ld_ident);
1250         be_emit_cstring(":\n");
1251         be_emit_write_line();
1252
1253         if (ent->initializer != NULL) {
1254                 dump_initializer(env, ent);
1255         } else if(entity_has_compound_ent_values(ent)) {
1256                 dump_compound_graph_init(env, ent);
1257         } else {
1258                 /* uninitialized */
1259                 be_emit_irprintf("\t.space %u\n", get_type_size_bytes(type));
1260                 be_emit_write_line();
1261         }
1262 }
1263
1264 /**
1265  * Dumps declarations of global variables and the initialization code.
1266  *
1267  * @param gt                a global like type, either the global or the TLS one
1268  * @param env               an environment
1269  * @param only_emit_marked  if non-zero, external allocated entities that do not have
1270  *                          its visited flag set are ignored
1271  */
1272 static void be_gas_dump_globals(ir_type *gt, be_gas_decl_env_t *env,
1273                                 int only_emit_marked)
1274 {
1275         int i, n = get_compound_n_members(gt);
1276         waitq *worklist = new_waitq();
1277
1278         if (only_emit_marked) {
1279                 for (i = 0; i < n; i++) {
1280                         ir_entity *ent = get_compound_member(gt, i);
1281                         if (is_entity_backend_marked(ent) || entity_has_definition(ent)) {
1282                                 waitq_put(worklist, ent);
1283                                 set_entity_backend_marked(ent, 1);
1284                         }
1285                 }
1286         } else {
1287                 for (i = 0; i < n; i++) {
1288                         ir_entity *ent = get_compound_member(gt, i);
1289                         set_entity_backend_marked(ent, 1);
1290                         waitq_put(worklist, ent);
1291                 }
1292         }
1293
1294         env->worklist = worklist;
1295
1296         while (!waitq_empty(worklist)) {
1297                 ir_entity *ent = waitq_get(worklist);
1298
1299                 dump_global(env, ent);
1300         }
1301
1302         del_waitq(worklist);
1303         env->worklist = NULL;
1304 }
1305
1306 /************************************************************************/
1307
1308 /* Generate all entities. */
1309 void be_gas_emit_decls(const be_main_env_t *main_env,
1310                        int only_emit_marked_entities)
1311 {
1312         be_gas_decl_env_t env;
1313         memset(&env, 0, sizeof(env));
1314
1315         /* dump global type */
1316         env.main_env = main_env;
1317         env.section  = (be_gas_section_t) -1;
1318
1319         be_gas_dump_globals(get_glob_type(), &env, only_emit_marked_entities);
1320         be_gas_dump_globals(get_tls_type(), &env, only_emit_marked_entities);
1321         be_gas_dump_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env,
1322                             only_emit_marked_entities);
1323         be_gas_dump_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env,
1324                             only_emit_marked_entities);
1325         be_gas_dump_globals(main_env->pic_symbols_type, &env,
1326                             only_emit_marked_entities);
1327         be_gas_dump_globals(main_env->pic_trampolines_type, &env,
1328                                                 only_emit_marked_entities);
1329
1330         /**
1331          * ".subsections_via_symbols marks object files which are OK to divide
1332          * their section contents into individual blocks".
1333          * From my understanding this means no label points in the middle of an
1334          * object which we want to address as a whole. Firm code should be fine
1335          * with this.
1336          */
1337         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
1338                 be_emit_cstring("\t.subsections_via_symbols\n");
1339                 be_emit_write_line();
1340         }
1341 }