libcpp, c, middle-end: Optimize initializers using #embed in C
[official-gcc.git] / gcc / fortran / trans-common.cc
blob481d468040e03a3e65aea34204ae991a2d26a401
1 /* Common block and equivalence list handling
2 Copyright (C) 2000-2024 Free Software Foundation, Inc.
3 Contributed by Canqun Yang <canqun@nudt.edu.cn>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 /* The core algorithm is based on Andy Vaught's g95 tree. Also the
22 way to build UNION_TYPE is borrowed from Richard Henderson.
24 Transform common blocks. An integral part of this is processing
25 equivalence variables. Equivalenced variables that are not in a
26 common block end up in a private block of their own.
28 Each common block or local equivalence list is declared as a union.
29 Variables within the block are represented as a field within the
30 block with the proper offset.
32 So if two variables are equivalenced, they just point to a common
33 area in memory.
35 Mathematically, laying out an equivalence block is equivalent to
36 solving a linear system of equations. The matrix is usually a
37 sparse matrix in which each row contains all zero elements except
38 for a +1 and a -1, a sort of a generalized Vandermonde matrix. The
39 matrix is usually block diagonal. The system can be
40 overdetermined, underdetermined or have a unique solution. If the
41 system is inconsistent, the program is not standard conforming.
42 The solution vector is integral, since all of the pivots are +1 or -1.
44 How we lay out an equivalence block is a little less complicated.
45 In an equivalence list with n elements, there are n-1 conditions to
46 be satisfied. The conditions partition the variables into what we
47 will call segments. If A and B are equivalenced then A and B are
48 in the same segment. If B and C are equivalenced as well, then A,
49 B and C are in a segment and so on. Each segment is a block of
50 memory that has one or more variables equivalenced in some way. A
51 common block is made up of a series of segments that are joined one
52 after the other. In the linear system, a segment is a block
53 diagonal.
55 To lay out a segment we first start with some variable and
56 determine its length. The first variable is assumed to start at
57 offset one and extends to however long it is. We then traverse the
58 list of equivalences to find an unused condition that involves at
59 least one of the variables currently in the segment.
61 Each equivalence condition amounts to the condition B+b=C+c where B
62 and C are the offsets of the B and C variables, and b and c are
63 constants which are nonzero for array elements, substrings or
64 structure components. So for
66 EQUIVALENCE(B(2), C(3))
67 we have
68 B + 2*size of B's elements = C + 3*size of C's elements.
70 If B and C are known we check to see if the condition already
71 holds. If B is known we can solve for C. Since we know the length
72 of C, we can see if the minimum and maximum extents of the segment
73 are affected. Eventually, we make a full pass through the
74 equivalence list without finding any new conditions and the segment
75 is fully specified.
77 At this point, the segment is added to the current common block.
78 Since we know the minimum extent of the segment, everything in the
79 segment is translated to its position in the common block. The
80 usual case here is that there are no equivalence statements and the
81 common block is series of segments with one variable each, which is
82 a diagonal matrix in the matrix formulation.
84 Each segment is described by a chain of segment_info structures. Each
85 segment_info structure describes the extents of a single variable within
86 the segment. This list is maintained in the order the elements are
87 positioned within the segment. If two elements have the same starting
88 offset the smaller will come first. If they also have the same size their
89 ordering is undefined.
91 Once all common blocks have been created, the list of equivalences
92 is examined for still-unused equivalence conditions. We create a
93 block for each merged equivalence list. */
95 #include "config.h"
96 #define INCLUDE_MAP
97 #include "system.h"
98 #include "coretypes.h"
99 #include "tm.h"
100 #include "tree.h"
101 #include "cgraph.h"
102 #include "context.h"
103 #include "omp-offload.h"
104 #include "gfortran.h"
105 #include "trans.h"
106 #include "stringpool.h"
107 #include "fold-const.h"
108 #include "stor-layout.h"
109 #include "varasm.h"
110 #include "trans-types.h"
111 #include "trans-const.h"
112 #include "target-memory.h"
115 /* Holds a single variable in an equivalence set. */
116 typedef struct segment_info
118 gfc_symbol *sym;
119 HOST_WIDE_INT offset;
120 HOST_WIDE_INT length;
121 /* This will contain the field type until the field is created. */
122 tree field;
123 struct segment_info *next;
124 } segment_info;
126 static segment_info * current_segment;
128 /* Store decl of all common blocks in this translation unit; the first
129 tree is the identifier. */
130 static std::map<tree, tree> gfc_map_of_all_commons;
133 /* Make a segment_info based on a symbol. */
135 static segment_info *
136 get_segment_info (gfc_symbol * sym, HOST_WIDE_INT offset)
138 segment_info *s;
140 /* Make sure we've got the character length. */
141 if (sym->ts.type == BT_CHARACTER)
142 gfc_conv_const_charlen (sym->ts.u.cl);
144 /* Create the segment_info and fill it in. */
145 s = XCNEW (segment_info);
146 s->sym = sym;
147 /* We will use this type when building the segment aggregate type. */
148 s->field = gfc_sym_type (sym);
149 s->length = int_size_in_bytes (s->field);
150 s->offset = offset;
152 return s;
156 /* Add a copy of a segment list to the namespace. This is specifically for
157 equivalence segments, so that dependency checking can be done on
158 equivalence group members. */
160 static void
161 copy_equiv_list_to_ns (segment_info *c)
163 segment_info *f;
164 gfc_equiv_info *s;
165 gfc_equiv_list *l;
167 l = XCNEW (gfc_equiv_list);
169 l->next = c->sym->ns->equiv_lists;
170 c->sym->ns->equiv_lists = l;
172 for (f = c; f; f = f->next)
174 s = XCNEW (gfc_equiv_info);
175 s->next = l->equiv;
176 l->equiv = s;
177 s->sym = f->sym;
178 s->offset = f->offset;
179 s->length = f->length;
184 /* Add combine segment V and segment LIST. */
186 static segment_info *
187 add_segments (segment_info *list, segment_info *v)
189 segment_info *s;
190 segment_info *p;
191 segment_info *next;
193 p = NULL;
194 s = list;
196 while (v)
198 /* Find the location of the new element. */
199 while (s)
201 if (v->offset < s->offset)
202 break;
203 if (v->offset == s->offset
204 && v->length <= s->length)
205 break;
207 p = s;
208 s = s->next;
211 /* Insert the new element in between p and s. */
212 next = v->next;
213 v->next = s;
214 if (p == NULL)
215 list = v;
216 else
217 p->next = v;
219 p = v;
220 v = next;
223 return list;
227 /* Construct mangled common block name from symbol name. */
229 /* We need the bind(c) flag to tell us how/if we should mangle the symbol
230 name. There are few calls to this function, so few places that this
231 would need to be added. At the moment, there is only one call, in
232 build_common_decl(). We can't attempt to look up the common block
233 because we may be building it for the first time and therefore, it won't
234 be in the common_root. We also need the binding label, if it's bind(c).
235 Therefore, send in the pointer to the common block, so whatever info we
236 have so far can be used. All of the necessary info should be available
237 in the gfc_common_head by now, so it should be accurate to test the
238 isBindC flag and use the binding label given if it is bind(c).
240 We may NOT know yet if it's bind(c) or not, but we can try at least.
241 Will have to figure out what to do later if it's labeled bind(c)
242 after this is called. */
244 static tree
245 gfc_sym_mangled_common_id (gfc_common_head *com)
247 int has_underscore;
248 /* Provide sufficient space to hold "symbol.symbol.eq.1234567890__". */
249 char mangled_name[2*GFC_MAX_MANGLED_SYMBOL_LEN + 1 + 16 + 1];
250 char name[sizeof (mangled_name) - 2];
252 /* Get the name out of the common block pointer. */
253 size_t len = strlen (com->name);
254 gcc_assert (len < sizeof (name));
255 strcpy (name, com->name);
257 /* If we're suppose to do a bind(c). */
258 if (com->is_bind_c == 1 && com->binding_label)
259 return get_identifier (com->binding_label);
261 if (strcmp (name, BLANK_COMMON_NAME) == 0)
262 return get_identifier (name);
264 if (flag_underscoring)
266 has_underscore = strchr (name, '_') != 0;
267 if (flag_second_underscore && has_underscore)
268 snprintf (mangled_name, sizeof mangled_name, "%s__", name);
269 else
270 snprintf (mangled_name, sizeof mangled_name, "%s_", name);
272 return get_identifier (mangled_name);
274 else
275 return get_identifier (name);
279 /* Build a field declaration for a common variable or a local equivalence
280 object. */
282 static void
283 build_field (segment_info *h, tree union_type, record_layout_info rli)
285 tree field;
286 tree name;
287 HOST_WIDE_INT offset = h->offset;
288 unsigned HOST_WIDE_INT desired_align, known_align;
290 name = get_identifier (h->sym->name);
291 field = build_decl (gfc_get_location (&h->sym->declared_at),
292 FIELD_DECL, name, h->field);
293 known_align = (offset & -offset) * BITS_PER_UNIT;
294 if (known_align == 0 || known_align > BIGGEST_ALIGNMENT)
295 known_align = BIGGEST_ALIGNMENT;
297 desired_align = update_alignment_for_field (rli, field, known_align);
298 if (desired_align > known_align)
299 DECL_PACKED (field) = 1;
301 DECL_FIELD_CONTEXT (field) = union_type;
302 DECL_FIELD_OFFSET (field) = size_int (offset);
303 DECL_FIELD_BIT_OFFSET (field) = bitsize_zero_node;
304 SET_DECL_OFFSET_ALIGN (field, known_align);
306 rli->offset = size_binop (MAX_EXPR, rli->offset,
307 size_binop (PLUS_EXPR,
308 DECL_FIELD_OFFSET (field),
309 DECL_SIZE_UNIT (field)));
310 /* If this field is assigned to a label, we create another two variables.
311 One will hold the address of target label or format label. The other will
312 hold the length of format label string. */
313 if (h->sym->attr.assign)
315 tree len;
316 tree addr;
318 gfc_allocate_lang_decl (field);
319 GFC_DECL_ASSIGN (field) = 1;
320 len = gfc_create_var_np (gfc_charlen_type_node,h->sym->name);
321 addr = gfc_create_var_np (pvoid_type_node, h->sym->name);
322 TREE_STATIC (len) = 1;
323 TREE_STATIC (addr) = 1;
324 DECL_INITIAL (len) = build_int_cst (gfc_charlen_type_node, -2);
325 gfc_set_decl_location (len, &h->sym->declared_at);
326 gfc_set_decl_location (addr, &h->sym->declared_at);
327 GFC_DECL_STRING_LEN (field) = pushdecl_top_level (len);
328 GFC_DECL_ASSIGN_ADDR (field) = pushdecl_top_level (addr);
331 /* If this field is volatile, mark it. */
332 if (h->sym->attr.volatile_)
334 tree new_type;
335 TREE_THIS_VOLATILE (field) = 1;
336 TREE_SIDE_EFFECTS (field) = 1;
337 new_type = build_qualified_type (TREE_TYPE (field), TYPE_QUAL_VOLATILE);
338 TREE_TYPE (field) = new_type;
341 h->field = field;
344 #if !defined (NO_DOT_IN_LABEL)
345 #define GFC_EQUIV_FMT "equiv.%d"
346 #elif !defined (NO_DOLLAR_IN_LABEL)
347 #define GFC_EQUIV_FMT "_Equiv$%d"
348 #else
349 #define GFC_EQUIV_FMT "_Equiv_%d"
350 #endif
352 /* Get storage for local equivalence. */
354 static tree
355 build_equiv_decl (tree union_type, bool is_init, bool is_saved, bool is_auto)
357 tree decl;
358 char name[18];
359 static int serial = 0;
361 if (is_init)
363 decl = gfc_create_var (union_type, "equiv");
364 TREE_STATIC (decl) = 1;
365 GFC_DECL_COMMON_OR_EQUIV (decl) = 1;
366 return decl;
369 snprintf (name, sizeof (name), GFC_EQUIV_FMT, serial++);
370 decl = build_decl (input_location,
371 VAR_DECL, get_identifier (name), union_type);
372 DECL_ARTIFICIAL (decl) = 1;
373 DECL_IGNORED_P (decl) = 1;
375 if (!is_auto && (!gfc_can_put_var_on_stack (DECL_SIZE_UNIT (decl))
376 || is_saved))
377 TREE_STATIC (decl) = 1;
379 TREE_ADDRESSABLE (decl) = 1;
380 TREE_USED (decl) = 1;
381 GFC_DECL_COMMON_OR_EQUIV (decl) = 1;
383 /* The source location has been lost, and doesn't really matter.
384 We need to set it to something though. */
385 gfc_set_decl_location (decl, &gfc_current_locus);
387 gfc_add_decl_to_function (decl);
389 return decl;
393 /* Get storage for common block. */
395 static tree
396 build_common_decl (gfc_common_head *com, tree union_type, bool is_init)
398 tree decl, identifier;
400 identifier = gfc_sym_mangled_common_id (com);
401 decl = gfc_map_of_all_commons.count(identifier)
402 ? gfc_map_of_all_commons[identifier] : NULL_TREE;
404 /* Update the size of this common block as needed. */
405 if (decl != NULL_TREE)
407 tree size = TYPE_SIZE_UNIT (union_type);
409 /* Named common blocks of the same name shall be of the same size
410 in all scoping units of a program in which they appear, but
411 blank common blocks may be of different sizes. */
412 if (!tree_int_cst_equal (DECL_SIZE_UNIT (decl), size)
413 && strcmp (com->name, BLANK_COMMON_NAME))
414 gfc_warning (0, "Named COMMON block %qs at %L shall be of the "
415 "same size as elsewhere (%wu vs %wu bytes)", com->name,
416 &com->where,
417 TREE_INT_CST_LOW (size),
418 TREE_INT_CST_LOW (DECL_SIZE_UNIT (decl)));
420 if (tree_int_cst_lt (DECL_SIZE_UNIT (decl), size))
422 DECL_SIZE (decl) = TYPE_SIZE (union_type);
423 DECL_SIZE_UNIT (decl) = size;
424 SET_DECL_MODE (decl, TYPE_MODE (union_type));
425 TREE_TYPE (decl) = union_type;
426 layout_decl (decl, 0);
430 /* If this common block has been declared in a previous program unit,
431 and either it is already initialized or there is no new initialization
432 for it, just return. */
433 if ((decl != NULL_TREE) && (!is_init || DECL_INITIAL (decl)))
434 return decl;
436 /* If there is no backend_decl for the common block, build it. */
437 if (decl == NULL_TREE)
439 tree omp_clauses = NULL_TREE;
441 if (com->is_bind_c == 1 && com->binding_label)
442 decl = build_decl (input_location, VAR_DECL, identifier, union_type);
443 else
445 decl = build_decl (input_location, VAR_DECL, get_identifier (com->name),
446 union_type);
447 gfc_set_decl_assembler_name (decl, identifier);
450 TREE_PUBLIC (decl) = 1;
451 TREE_STATIC (decl) = 1;
452 DECL_IGNORED_P (decl) = 1;
453 if (!com->is_bind_c)
454 SET_DECL_ALIGN (decl, BIGGEST_ALIGNMENT);
455 else
457 /* Do not set the alignment for bind(c) common blocks to
458 BIGGEST_ALIGNMENT because that won't match what C does. Also,
459 for common blocks with one element, the alignment must be
460 that of the field within the common block in order to match
461 what C will do. */
462 tree field = NULL_TREE;
463 field = TYPE_FIELDS (TREE_TYPE (decl));
464 if (DECL_CHAIN (field) == NULL_TREE)
465 SET_DECL_ALIGN (decl, TYPE_ALIGN (TREE_TYPE (field)));
467 DECL_USER_ALIGN (decl) = 0;
468 GFC_DECL_COMMON_OR_EQUIV (decl) = 1;
470 gfc_set_decl_location (decl, &com->where);
472 if (com->threadprivate)
473 set_decl_tls_model (decl, decl_default_tls_model (decl));
475 if (com->omp_device_type != OMP_DEVICE_TYPE_UNSET)
477 tree c = build_omp_clause (UNKNOWN_LOCATION, OMP_CLAUSE_DEVICE_TYPE);
478 switch (com->omp_device_type)
480 case OMP_DEVICE_TYPE_HOST:
481 OMP_CLAUSE_DEVICE_TYPE_KIND (c) = OMP_CLAUSE_DEVICE_TYPE_HOST;
482 break;
483 case OMP_DEVICE_TYPE_NOHOST:
484 OMP_CLAUSE_DEVICE_TYPE_KIND (c) = OMP_CLAUSE_DEVICE_TYPE_NOHOST;
485 break;
486 case OMP_DEVICE_TYPE_ANY:
487 OMP_CLAUSE_DEVICE_TYPE_KIND (c) = OMP_CLAUSE_DEVICE_TYPE_ANY;
488 break;
489 default:
490 gcc_unreachable ();
492 omp_clauses = c;
494 if (com->omp_declare_target_link)
495 DECL_ATTRIBUTES (decl)
496 = tree_cons (get_identifier ("omp declare target link"),
497 omp_clauses, DECL_ATTRIBUTES (decl));
498 else if (com->omp_declare_target)
499 DECL_ATTRIBUTES (decl)
500 = tree_cons (get_identifier ("omp declare target"),
501 omp_clauses, DECL_ATTRIBUTES (decl));
503 if (com->omp_declare_target_link || com->omp_declare_target)
505 /* Add to offload_vars; get_create does so for omp_declare_target,
506 omp_declare_target_link requires manual work. */
507 gcc_assert (symtab_node::get (decl) == 0);
508 symtab_node *node = symtab_node::get_create (decl);
509 if (node != NULL && com->omp_declare_target_link)
511 node->offloadable = 1;
512 if (ENABLE_OFFLOADING)
514 g->have_offload = true;
515 if (is_a <varpool_node *> (node))
516 vec_safe_push (offload_vars, decl);
521 /* Place the back end declaration for this common block in
522 GLOBAL_BINDING_LEVEL. */
523 gfc_map_of_all_commons[identifier] = pushdecl_top_level (decl);
526 /* Has no initial values. */
527 if (!is_init)
529 DECL_INITIAL (decl) = NULL_TREE;
530 DECL_COMMON (decl) = 1;
531 DECL_DEFER_OUTPUT (decl) = 1;
533 else
535 DECL_INITIAL (decl) = error_mark_node;
536 DECL_COMMON (decl) = 0;
537 DECL_DEFER_OUTPUT (decl) = 0;
539 return decl;
543 /* Return a field that is the size of the union, if an equivalence has
544 overlapping initializers. Merge the initializers into a single
545 initializer for this new field, then free the old ones. */
547 static tree
548 get_init_field (segment_info *head, tree union_type, tree *field_init,
549 record_layout_info rli)
551 segment_info *s;
552 HOST_WIDE_INT length = 0;
553 HOST_WIDE_INT offset = 0;
554 unsigned HOST_WIDE_INT known_align, desired_align;
555 bool overlap = false;
556 tree tmp, field;
557 tree init;
558 unsigned char *data, *chk;
559 vec<constructor_elt, va_gc> *v = NULL;
561 tree type = unsigned_char_type_node;
562 int i;
564 /* Obtain the size of the union and check if there are any overlapping
565 initializers. */
566 for (s = head; s; s = s->next)
568 HOST_WIDE_INT slen = s->offset + s->length;
569 if (s->sym->value)
571 if (s->offset < offset)
572 overlap = true;
573 offset = slen;
575 length = length < slen ? slen : length;
578 if (!overlap)
579 return NULL_TREE;
581 /* Now absorb all the initializer data into a single vector,
582 whilst checking for overlapping, unequal values. */
583 data = XCNEWVEC (unsigned char, (size_t)length);
584 chk = XCNEWVEC (unsigned char, (size_t)length);
586 /* TODO - change this when default initialization is implemented. */
587 memset (data, '\0', (size_t)length);
588 memset (chk, '\0', (size_t)length);
589 for (s = head; s; s = s->next)
590 if (s->sym->value)
592 locus *loc = NULL;
593 if (s->sym->ns->equiv && s->sym->ns->equiv->eq)
594 loc = &s->sym->ns->equiv->eq->expr->where;
595 gfc_merge_initializers (s->sym->ts, s->sym->value, loc,
596 &data[s->offset],
597 &chk[s->offset],
598 (size_t)s->length);
601 for (i = 0; i < length; i++)
602 CONSTRUCTOR_APPEND_ELT (v, NULL, build_int_cst (type, data[i]));
604 free (data);
605 free (chk);
607 /* Build a char[length] array to hold the initializers. Much of what
608 follows is borrowed from build_field, above. */
610 tmp = build_int_cst (gfc_array_index_type, length - 1);
611 tmp = build_range_type (gfc_array_index_type,
612 gfc_index_zero_node, tmp);
613 tmp = build_array_type (type, tmp);
614 field = build_decl (gfc_get_location (&gfc_current_locus),
615 FIELD_DECL, NULL_TREE, tmp);
617 known_align = BIGGEST_ALIGNMENT;
619 desired_align = update_alignment_for_field (rli, field, known_align);
620 if (desired_align > known_align)
621 DECL_PACKED (field) = 1;
623 DECL_FIELD_CONTEXT (field) = union_type;
624 DECL_FIELD_OFFSET (field) = size_int (0);
625 DECL_FIELD_BIT_OFFSET (field) = bitsize_zero_node;
626 SET_DECL_OFFSET_ALIGN (field, known_align);
628 rli->offset = size_binop (MAX_EXPR, rli->offset,
629 size_binop (PLUS_EXPR,
630 DECL_FIELD_OFFSET (field),
631 DECL_SIZE_UNIT (field)));
633 init = build_constructor (TREE_TYPE (field), v);
634 TREE_CONSTANT (init) = 1;
636 *field_init = init;
638 for (s = head; s; s = s->next)
640 if (s->sym->value == NULL)
641 continue;
643 gfc_free_expr (s->sym->value);
644 s->sym->value = NULL;
647 return field;
651 /* Declare memory for the common block or local equivalence, and create
652 backend declarations for all of the elements. */
654 static void
655 create_common (gfc_common_head *com, segment_info *head, bool saw_equiv)
657 segment_info *s, *next_s;
658 tree union_type;
659 tree *field_link;
660 tree field;
661 tree field_init = NULL_TREE;
662 record_layout_info rli;
663 tree decl;
664 bool is_init = false;
665 bool is_saved = false;
666 bool is_auto = false;
668 /* Declare the variables inside the common block.
669 If the current common block contains any equivalence object, then
670 make a UNION_TYPE node, otherwise RECORD_TYPE. This will let the
671 alias analyzer work well when there is no address overlapping for
672 common variables in the current common block. */
673 if (saw_equiv)
674 union_type = make_node (UNION_TYPE);
675 else
676 union_type = make_node (RECORD_TYPE);
678 rli = start_record_layout (union_type);
679 field_link = &TYPE_FIELDS (union_type);
681 /* Check for overlapping initializers and replace them with a single,
682 artificial field that contains all the data. */
683 if (saw_equiv)
684 field = get_init_field (head, union_type, &field_init, rli);
685 else
686 field = NULL_TREE;
688 if (field != NULL_TREE)
690 is_init = true;
691 *field_link = field;
692 field_link = &DECL_CHAIN (field);
695 for (s = head; s; s = s->next)
697 build_field (s, union_type, rli);
699 /* Link the field into the type. */
700 *field_link = s->field;
701 field_link = &DECL_CHAIN (s->field);
703 /* Has initial value. */
704 if (s->sym->value)
705 is_init = true;
707 /* Has SAVE attribute. */
708 if (s->sym->attr.save)
709 is_saved = true;
711 /* Has AUTOMATIC attribute. */
712 if (s->sym->attr.automatic)
713 is_auto = true;
716 finish_record_layout (rli, true);
718 if (com)
719 decl = build_common_decl (com, union_type, is_init);
720 else
721 decl = build_equiv_decl (union_type, is_init, is_saved, is_auto);
723 if (is_init)
725 tree ctor, tmp;
726 vec<constructor_elt, va_gc> *v = NULL;
728 if (field != NULL_TREE && field_init != NULL_TREE)
729 CONSTRUCTOR_APPEND_ELT (v, field, field_init);
730 else
731 for (s = head; s; s = s->next)
733 if (s->sym->value)
735 /* Add the initializer for this field. */
736 tmp = gfc_conv_initializer (s->sym->value, &s->sym->ts,
737 TREE_TYPE (s->field),
738 s->sym->attr.dimension,
739 s->sym->attr.pointer
740 || s->sym->attr.allocatable, false);
742 CONSTRUCTOR_APPEND_ELT (v, s->field, tmp);
746 gcc_assert (!v->is_empty ());
747 ctor = build_constructor (union_type, v);
748 TREE_CONSTANT (ctor) = 1;
749 TREE_STATIC (ctor) = 1;
750 DECL_INITIAL (decl) = ctor;
752 if (flag_checking)
754 tree field, value;
755 unsigned HOST_WIDE_INT idx;
756 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), idx, field, value)
757 gcc_assert (TREE_CODE (field) == FIELD_DECL);
761 /* Build component reference for each variable. */
762 for (s = head; s; s = next_s)
764 tree var_decl;
766 var_decl = build_decl (gfc_get_location (&s->sym->declared_at),
767 VAR_DECL, DECL_NAME (s->field),
768 TREE_TYPE (s->field));
769 TREE_STATIC (var_decl) = TREE_STATIC (decl);
770 /* Mark the variable as used in order to avoid warnings about
771 unused variables. */
772 TREE_USED (var_decl) = 1;
773 if (s->sym->attr.use_assoc)
774 DECL_IGNORED_P (var_decl) = 1;
775 if (s->sym->attr.target)
776 TREE_ADDRESSABLE (var_decl) = 1;
777 /* Fake variables are not visible from other translation units. */
778 TREE_PUBLIC (var_decl) = 0;
779 gfc_finish_decl_attrs (var_decl, &s->sym->attr);
781 /* To preserve identifier names in COMMON, chain to procedure
782 scope unless at top level in a module definition. */
783 if (com
784 && s->sym->ns->proc_name
785 && s->sym->ns->proc_name->attr.flavor == FL_MODULE)
786 var_decl = pushdecl_top_level (var_decl);
787 else
788 gfc_add_decl_to_function (var_decl);
790 tree comp = build3_loc (input_location, COMPONENT_REF,
791 TREE_TYPE (s->field), decl, s->field, NULL_TREE);
792 if (TREE_THIS_VOLATILE (s->field))
793 TREE_THIS_VOLATILE (comp) = 1;
794 SET_DECL_VALUE_EXPR (var_decl, comp);
795 DECL_HAS_VALUE_EXPR_P (var_decl) = 1;
796 GFC_DECL_COMMON_OR_EQUIV (var_decl) = 1;
798 if (s->sym->attr.assign)
800 gfc_allocate_lang_decl (var_decl);
801 GFC_DECL_ASSIGN (var_decl) = 1;
802 GFC_DECL_STRING_LEN (var_decl) = GFC_DECL_STRING_LEN (s->field);
803 GFC_DECL_ASSIGN_ADDR (var_decl) = GFC_DECL_ASSIGN_ADDR (s->field);
806 s->sym->backend_decl = var_decl;
808 next_s = s->next;
809 free (s);
814 /* Given a symbol, find it in the current segment list. Returns NULL if
815 not found. */
817 static segment_info *
818 find_segment_info (gfc_symbol *symbol)
820 segment_info *n;
822 for (n = current_segment; n; n = n->next)
824 if (n->sym == symbol)
825 return n;
828 return NULL;
832 /* Given an expression node, make sure it is a constant integer and return
833 the mpz_t value. */
835 static mpz_t *
836 get_mpz (gfc_expr *e)
839 if (e->expr_type != EXPR_CONSTANT)
840 gfc_internal_error ("get_mpz(): Not an integer constant");
842 return &e->value.integer;
846 /* Given an array specification and an array reference, figure out the
847 array element number (zero based). Bounds and elements are guaranteed
848 to be constants. If something goes wrong we generate an error and
849 return zero. */
851 static HOST_WIDE_INT
852 element_number (gfc_array_ref *ar)
854 mpz_t multiplier, offset, extent, n;
855 gfc_array_spec *as;
856 HOST_WIDE_INT i, rank;
858 as = ar->as;
859 rank = as->rank;
860 mpz_init_set_ui (multiplier, 1);
861 mpz_init_set_ui (offset, 0);
862 mpz_init (extent);
863 mpz_init (n);
865 for (i = 0; i < rank; i++)
867 if (ar->dimen_type[i] != DIMEN_ELEMENT)
868 gfc_internal_error ("element_number(): Bad dimension type");
870 if (as && as->lower[i])
871 mpz_sub (n, *get_mpz (ar->start[i]), *get_mpz (as->lower[i]));
872 else
873 mpz_sub_ui (n, *get_mpz (ar->start[i]), 1);
875 mpz_mul (n, n, multiplier);
876 mpz_add (offset, offset, n);
878 if (as && as->upper[i] && as->lower[i])
880 mpz_sub (extent, *get_mpz (as->upper[i]), *get_mpz (as->lower[i]));
881 mpz_add_ui (extent, extent, 1);
883 else
884 mpz_set_ui (extent, 0);
886 if (mpz_sgn (extent) < 0)
887 mpz_set_ui (extent, 0);
889 mpz_mul (multiplier, multiplier, extent);
892 i = mpz_get_ui (offset);
894 mpz_clear (multiplier);
895 mpz_clear (offset);
896 mpz_clear (extent);
897 mpz_clear (n);
899 return i;
903 /* Given a single element of an equivalence list, figure out the offset
904 from the base symbol. For simple variables or full arrays, this is
905 simply zero. For an array element we have to calculate the array
906 element number and multiply by the element size. For a substring we
907 have to calculate the further reference. */
909 static HOST_WIDE_INT
910 calculate_offset (gfc_expr *e)
912 HOST_WIDE_INT n, element_size, offset;
913 gfc_typespec *element_type;
914 gfc_ref *reference;
916 offset = 0;
917 element_type = &e->symtree->n.sym->ts;
919 for (reference = e->ref; reference; reference = reference->next)
920 switch (reference->type)
922 case REF_ARRAY:
923 switch (reference->u.ar.type)
925 case AR_FULL:
926 break;
928 case AR_ELEMENT:
929 n = element_number (&reference->u.ar);
930 if (element_type->type == BT_CHARACTER)
931 gfc_conv_const_charlen (element_type->u.cl);
932 element_size =
933 int_size_in_bytes (gfc_typenode_for_spec (element_type));
934 offset += n * element_size;
935 break;
937 default:
938 gfc_error ("Bad array reference at %L", &e->where);
940 break;
941 case REF_SUBSTRING:
942 if (reference->u.ss.start != NULL)
943 offset += mpz_get_ui (*get_mpz (reference->u.ss.start)) - 1;
944 break;
945 default:
946 gfc_error ("Illegal reference type at %L as EQUIVALENCE object",
947 &e->where);
949 return offset;
953 /* Add a new segment_info structure to the current segment. eq1 is already
954 in the list, eq2 is not. */
956 static void
957 new_condition (segment_info *v, gfc_equiv *eq1, gfc_equiv *eq2)
959 HOST_WIDE_INT offset1, offset2;
960 segment_info *a;
962 offset1 = calculate_offset (eq1->expr);
963 offset2 = calculate_offset (eq2->expr);
965 a = get_segment_info (eq2->expr->symtree->n.sym,
966 v->offset + offset1 - offset2);
968 current_segment = add_segments (current_segment, a);
972 /* Given two equivalence structures that are both already in the list, make
973 sure that this new condition is not violated, generating an error if it
974 is. */
976 static void
977 confirm_condition (segment_info *s1, gfc_equiv *eq1, segment_info *s2,
978 gfc_equiv *eq2)
980 HOST_WIDE_INT offset1, offset2;
982 offset1 = calculate_offset (eq1->expr);
983 offset2 = calculate_offset (eq2->expr);
985 if (s1->offset + offset1 != s2->offset + offset2)
986 gfc_error ("Inconsistent equivalence rules involving %qs at %L and "
987 "%qs at %L", s1->sym->name, &s1->sym->declared_at,
988 s2->sym->name, &s2->sym->declared_at);
992 /* Process a new equivalence condition. eq1 is know to be in segment f.
993 If eq2 is also present then confirm that the condition holds.
994 Otherwise add a new variable to the segment list. */
996 static void
997 add_condition (segment_info *f, gfc_equiv *eq1, gfc_equiv *eq2)
999 segment_info *n;
1001 n = find_segment_info (eq2->expr->symtree->n.sym);
1003 if (n == NULL)
1004 new_condition (f, eq1, eq2);
1005 else
1006 confirm_condition (f, eq1, n, eq2);
1009 static void
1010 accumulate_equivalence_attributes (symbol_attribute *dummy_symbol, gfc_equiv *e)
1012 symbol_attribute attr = e->expr->symtree->n.sym->attr;
1014 dummy_symbol->dummy |= attr.dummy;
1015 dummy_symbol->pointer |= attr.pointer;
1016 dummy_symbol->target |= attr.target;
1017 dummy_symbol->external |= attr.external;
1018 dummy_symbol->intrinsic |= attr.intrinsic;
1019 dummy_symbol->allocatable |= attr.allocatable;
1020 dummy_symbol->elemental |= attr.elemental;
1021 dummy_symbol->recursive |= attr.recursive;
1022 dummy_symbol->in_common |= attr.in_common;
1023 dummy_symbol->result |= attr.result;
1024 dummy_symbol->in_namelist |= attr.in_namelist;
1025 dummy_symbol->optional |= attr.optional;
1026 dummy_symbol->entry |= attr.entry;
1027 dummy_symbol->function |= attr.function;
1028 dummy_symbol->subroutine |= attr.subroutine;
1029 dummy_symbol->dimension |= attr.dimension;
1030 dummy_symbol->in_equivalence |= attr.in_equivalence;
1031 dummy_symbol->use_assoc |= attr.use_assoc;
1032 dummy_symbol->cray_pointer |= attr.cray_pointer;
1033 dummy_symbol->cray_pointee |= attr.cray_pointee;
1034 dummy_symbol->data |= attr.data;
1035 dummy_symbol->value |= attr.value;
1036 dummy_symbol->volatile_ |= attr.volatile_;
1037 dummy_symbol->is_protected |= attr.is_protected;
1038 dummy_symbol->is_bind_c |= attr.is_bind_c;
1039 dummy_symbol->procedure |= attr.procedure;
1040 dummy_symbol->proc_pointer |= attr.proc_pointer;
1041 dummy_symbol->abstract |= attr.abstract;
1042 dummy_symbol->asynchronous |= attr.asynchronous;
1043 dummy_symbol->codimension |= attr.codimension;
1044 dummy_symbol->contiguous |= attr.contiguous;
1045 dummy_symbol->generic |= attr.generic;
1046 dummy_symbol->automatic |= attr.automatic;
1047 dummy_symbol->threadprivate |= attr.threadprivate;
1048 dummy_symbol->omp_declare_target |= attr.omp_declare_target;
1049 dummy_symbol->omp_declare_target_link |= attr.omp_declare_target_link;
1050 dummy_symbol->oacc_declare_copyin |= attr.oacc_declare_copyin;
1051 dummy_symbol->oacc_declare_create |= attr.oacc_declare_create;
1052 dummy_symbol->oacc_declare_deviceptr |= attr.oacc_declare_deviceptr;
1053 dummy_symbol->oacc_declare_device_resident
1054 |= attr.oacc_declare_device_resident;
1056 /* Not strictly correct, but probably close enough. */
1057 if (attr.save > dummy_symbol->save)
1058 dummy_symbol->save = attr.save;
1059 if (attr.access > dummy_symbol->access)
1060 dummy_symbol->access = attr.access;
1063 /* Given a segment element, search through the equivalence lists for unused
1064 conditions that involve the symbol. Add these rules to the segment. */
1066 static bool
1067 find_equivalence (segment_info *n)
1069 gfc_equiv *e1, *e2, *eq;
1070 bool found;
1072 found = false;
1074 for (e1 = n->sym->ns->equiv; e1; e1 = e1->next)
1076 eq = NULL;
1078 /* Search the equivalence list, including the root (first) element
1079 for the symbol that owns the segment. */
1080 symbol_attribute dummy_symbol;
1081 memset (&dummy_symbol, 0, sizeof (dummy_symbol));
1082 for (e2 = e1; e2; e2 = e2->eq)
1084 accumulate_equivalence_attributes (&dummy_symbol, e2);
1085 if (!e2->used && e2->expr->symtree->n.sym == n->sym)
1087 eq = e2;
1088 break;
1092 gfc_check_conflict (&dummy_symbol, e1->expr->symtree->name, &e1->expr->where);
1094 /* Go to the next root element. */
1095 if (eq == NULL)
1096 continue;
1098 eq->used = 1;
1100 /* Now traverse the equivalence list matching the offsets. */
1101 for (e2 = e1; e2; e2 = e2->eq)
1103 if (!e2->used && e2 != eq)
1105 add_condition (n, eq, e2);
1106 e2->used = 1;
1107 found = true;
1111 return found;
1115 /* Add all symbols equivalenced within a segment. We need to scan the
1116 segment list multiple times to include indirect equivalences. Since
1117 a new segment_info can inserted at the beginning of the segment list,
1118 depending on its offset, we have to force a final pass through the
1119 loop by demanding that completion sees a pass with no matches; i.e.,
1120 all symbols with equiv_built set and no new equivalences found. */
1122 static void
1123 add_equivalences (bool *saw_equiv)
1125 segment_info *f;
1126 bool more = true;
1128 while (more)
1130 more = false;
1131 for (f = current_segment; f; f = f->next)
1133 if (!f->sym->equiv_built)
1135 f->sym->equiv_built = 1;
1136 bool seen_one = find_equivalence (f);
1137 if (seen_one)
1139 *saw_equiv = true;
1140 more = true;
1146 /* Add a copy of this segment list to the namespace. */
1147 copy_equiv_list_to_ns (current_segment);
1151 /* Returns the offset necessary to properly align the current equivalence.
1152 Sets *palign to the required alignment. */
1154 static HOST_WIDE_INT
1155 align_segment (unsigned HOST_WIDE_INT *palign)
1157 segment_info *s;
1158 unsigned HOST_WIDE_INT offset;
1159 unsigned HOST_WIDE_INT max_align;
1160 unsigned HOST_WIDE_INT this_align;
1161 unsigned HOST_WIDE_INT this_offset;
1163 max_align = 1;
1164 offset = 0;
1165 for (s = current_segment; s; s = s->next)
1167 this_align = TYPE_ALIGN_UNIT (s->field);
1168 if (s->offset & (this_align - 1))
1170 /* Field is misaligned. */
1171 this_offset = this_align - ((s->offset + offset) & (this_align - 1));
1172 if (this_offset & (max_align - 1))
1174 /* Aligning this field would misalign a previous field. */
1175 gfc_error ("The equivalence set for variable %qs "
1176 "declared at %L violates alignment requirements",
1177 s->sym->name, &s->sym->declared_at);
1179 offset += this_offset;
1181 max_align = this_align;
1183 if (palign)
1184 *palign = max_align;
1185 return offset;
1189 /* Adjust segment offsets by the given amount. */
1191 static void
1192 apply_segment_offset (segment_info *s, HOST_WIDE_INT offset)
1194 for (; s; s = s->next)
1195 s->offset += offset;
1199 /* Lay out a symbol in a common block. If the symbol has already been seen
1200 then check the location is consistent. Otherwise create segments
1201 for that symbol and all the symbols equivalenced with it. */
1203 /* Translate a single common block. */
1205 static void
1206 translate_common (gfc_common_head *common, gfc_symbol *var_list)
1208 gfc_symbol *sym;
1209 segment_info *s;
1210 segment_info *common_segment;
1211 HOST_WIDE_INT offset;
1212 HOST_WIDE_INT current_offset;
1213 unsigned HOST_WIDE_INT align;
1214 bool saw_equiv;
1216 common_segment = NULL;
1217 offset = 0;
1218 current_offset = 0;
1219 align = 1;
1220 saw_equiv = false;
1222 if (var_list->attr.omp_allocate)
1223 gfc_error ("Sorry, !$OMP allocate for COMMON block variable %qs at %L "
1224 "not supported", common->name, &common->where);
1226 /* Add symbols to the segment. */
1227 for (sym = var_list; sym; sym = sym->common_next)
1229 current_segment = common_segment;
1230 s = find_segment_info (sym);
1232 /* Symbol has already been added via an equivalence. Multiple
1233 use associations of the same common block result in equiv_built
1234 being set but no information about the symbol in the segment. */
1235 if (s && sym->equiv_built)
1237 /* Ensure the current location is properly aligned. */
1238 align = TYPE_ALIGN_UNIT (s->field);
1239 current_offset = (current_offset + align - 1) &~ (align - 1);
1241 /* Verify that it ended up where we expect it. */
1242 if (s->offset != current_offset)
1244 gfc_error ("Equivalence for %qs does not match ordering of "
1245 "COMMON %qs at %L", sym->name,
1246 common->name, &common->where);
1249 else
1251 /* A symbol we haven't seen before. */
1252 s = current_segment = get_segment_info (sym, current_offset);
1254 /* Add all objects directly or indirectly equivalenced with this
1255 symbol. */
1256 add_equivalences (&saw_equiv);
1258 if (current_segment->offset < 0)
1259 gfc_error ("The equivalence set for %qs cause an invalid "
1260 "extension to COMMON %qs at %L", sym->name,
1261 common->name, &common->where);
1263 if (flag_align_commons)
1264 offset = align_segment (&align);
1266 if (offset)
1268 /* The required offset conflicts with previous alignment
1269 requirements. Insert padding immediately before this
1270 segment. */
1271 if (warn_align_commons)
1273 if (strcmp (common->name, BLANK_COMMON_NAME))
1274 gfc_warning (OPT_Walign_commons,
1275 "Padding of %d bytes required before %qs in "
1276 "COMMON %qs at %L; reorder elements or use "
1277 "%<-fno-align-commons%>", (int)offset,
1278 s->sym->name, common->name, &common->where);
1279 else
1280 gfc_warning (OPT_Walign_commons,
1281 "Padding of %d bytes required before %qs in "
1282 "COMMON at %L; reorder elements or use "
1283 "%<-fno-align-commons%>", (int)offset,
1284 s->sym->name, &common->where);
1288 /* Apply the offset to the new segments. */
1289 apply_segment_offset (current_segment, offset);
1290 current_offset += offset;
1292 /* Add the new segments to the common block. */
1293 common_segment = add_segments (common_segment, current_segment);
1296 /* The offset of the next common variable. */
1297 current_offset += s->length;
1300 if (common_segment == NULL)
1302 gfc_error ("COMMON %qs at %L does not exist",
1303 common->name, &common->where);
1304 return;
1307 if (common_segment->offset != 0 && warn_align_commons)
1309 if (strcmp (common->name, BLANK_COMMON_NAME))
1310 gfc_warning (OPT_Walign_commons,
1311 "COMMON %qs at %L requires %d bytes of padding; "
1312 "reorder elements or use %<-fno-align-commons%>",
1313 common->name, &common->where, (int)common_segment->offset);
1314 else
1315 gfc_warning (OPT_Walign_commons,
1316 "COMMON at %L requires %d bytes of padding; "
1317 "reorder elements or use %<-fno-align-commons%>",
1318 &common->where, (int)common_segment->offset);
1321 create_common (common, common_segment, saw_equiv);
1325 /* Create a new block for each merged equivalence list. */
1327 static void
1328 finish_equivalences (gfc_namespace *ns)
1330 gfc_equiv *z, *y;
1331 gfc_symbol *sym;
1332 gfc_common_head * c;
1333 HOST_WIDE_INT offset;
1334 unsigned HOST_WIDE_INT align;
1335 bool dummy;
1337 for (z = ns->equiv; z; z = z->next)
1338 for (y = z->eq; y; y = y->eq)
1340 if (y->used)
1341 continue;
1342 sym = z->expr->symtree->n.sym;
1343 current_segment = get_segment_info (sym, 0);
1345 /* All objects directly or indirectly equivalenced with this
1346 symbol. */
1347 add_equivalences (&dummy);
1349 /* Align the block. */
1350 offset = align_segment (&align);
1352 /* Ensure all offsets are positive. */
1353 offset -= current_segment->offset & ~(align - 1);
1355 apply_segment_offset (current_segment, offset);
1357 /* Create the decl. If this is a module equivalence, it has a
1358 unique name, pointed to by z->module. This is written to a
1359 gfc_common_header to push create_common into using
1360 build_common_decl, so that the equivalence appears as an
1361 external symbol. Otherwise, a local declaration is built using
1362 build_equiv_decl. */
1363 if (z->module)
1365 c = gfc_get_common_head ();
1366 /* We've lost the real location, so use the location of the
1367 enclosing procedure. If we're in a BLOCK DATA block, then
1368 use the location in the sym_root. */
1369 if (ns->proc_name)
1370 c->where = ns->proc_name->declared_at;
1371 else if (ns->is_block_data)
1372 c->where = ns->sym_root->n.sym->declared_at;
1374 size_t len = strlen (z->module);
1375 gcc_assert (len < sizeof (c->name));
1376 memcpy (c->name, z->module, len);
1377 c->name[len] = '\0';
1379 else
1380 c = NULL;
1382 create_common (c, current_segment, true);
1383 break;
1388 /* Work function for translating a named common block. */
1390 static void
1391 named_common (gfc_symtree *st)
1393 translate_common (st->n.common, st->n.common->head);
1397 /* Translate the common blocks in a namespace. Unlike other variables,
1398 these have to be created before code, because the backend_decl depends
1399 on the rest of the common block. */
1401 void
1402 gfc_trans_common (gfc_namespace *ns)
1404 gfc_common_head *c;
1406 /* Translate the blank common block. */
1407 if (ns->blank_common.head != NULL)
1409 c = gfc_get_common_head ();
1410 c->where = ns->blank_common.head->common_head->where;
1411 strcpy (c->name, BLANK_COMMON_NAME);
1412 translate_common (c, ns->blank_common.head);
1415 /* Translate all named common blocks. */
1416 gfc_traverse_symtree (ns->common_root, named_common);
1418 /* Translate local equivalence. */
1419 finish_equivalences (ns);
1421 /* Commit the newly created symbols for common blocks and module
1422 equivalences. */
1423 gfc_commit_symbols ();