xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/stor-layout.c (revision 8feb0f0b7eaff0608f8350bbfa3098827b4bb91b)
1 /* C-compiler utilities for types and variables storage layout
2    Copyright (C) 1987-2020 Free Software Foundation, Inc.
3 
4 This file is part of GCC.
5 
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10 
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15 
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19 
20 
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "target.h"
25 #include "function.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "memmodel.h"
29 #include "tm_p.h"
30 #include "stringpool.h"
31 #include "regs.h"
32 #include "emit-rtl.h"
33 #include "cgraph.h"
34 #include "diagnostic-core.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "varasm.h"
38 #include "print-tree.h"
39 #include "langhooks.h"
40 #include "tree-inline.h"
41 #include "dumpfile.h"
42 #include "gimplify.h"
43 #include "attribs.h"
44 #include "debug.h"
45 #include "calls.h"
46 
47 /* Data type for the expressions representing sizes of data types.
48    It is the first integer type laid out.  */
49 tree sizetype_tab[(int) stk_type_kind_last];
50 
51 /* If nonzero, this is an upper limit on alignment of structure fields.
52    The value is measured in bits.  */
53 unsigned int maximum_field_alignment = TARGET_DEFAULT_PACK_STRUCT * BITS_PER_UNIT;
54 
55 static tree self_referential_size (tree);
56 static void finalize_record_size (record_layout_info);
57 static void finalize_type_size (tree);
58 static void place_union_field (record_layout_info, tree);
59 static int excess_unit_span (HOST_WIDE_INT, HOST_WIDE_INT, HOST_WIDE_INT,
60 			     HOST_WIDE_INT, tree);
61 extern void debug_rli (record_layout_info);
62 
63 /* Given a size SIZE that may not be a constant, return a SAVE_EXPR
64    to serve as the actual size-expression for a type or decl.  */
65 
66 tree
variable_size(tree size)67 variable_size (tree size)
68 {
69   /* Obviously.  */
70   if (TREE_CONSTANT (size))
71     return size;
72 
73   /* If the size is self-referential, we can't make a SAVE_EXPR (see
74      save_expr for the rationale).  But we can do something else.  */
75   if (CONTAINS_PLACEHOLDER_P (size))
76     return self_referential_size (size);
77 
78   /* If we are in the global binding level, we can't make a SAVE_EXPR
79      since it may end up being shared across functions, so it is up
80      to the front-end to deal with this case.  */
81   if (lang_hooks.decls.global_bindings_p ())
82     return size;
83 
84   return save_expr (size);
85 }
86 
87 /* An array of functions used for self-referential size computation.  */
88 static GTY(()) vec<tree, va_gc> *size_functions;
89 
90 /* Return true if T is a self-referential component reference.  */
91 
92 static bool
self_referential_component_ref_p(tree t)93 self_referential_component_ref_p (tree t)
94 {
95   if (TREE_CODE (t) != COMPONENT_REF)
96     return false;
97 
98   while (REFERENCE_CLASS_P (t))
99     t = TREE_OPERAND (t, 0);
100 
101   return (TREE_CODE (t) == PLACEHOLDER_EXPR);
102 }
103 
104 /* Similar to copy_tree_r but do not copy component references involving
105    PLACEHOLDER_EXPRs.  These nodes are spotted in find_placeholder_in_expr
106    and substituted in substitute_in_expr.  */
107 
108 static tree
copy_self_referential_tree_r(tree * tp,int * walk_subtrees,void * data)109 copy_self_referential_tree_r (tree *tp, int *walk_subtrees, void *data)
110 {
111   enum tree_code code = TREE_CODE (*tp);
112 
113   /* Stop at types, decls, constants like copy_tree_r.  */
114   if (TREE_CODE_CLASS (code) == tcc_type
115       || TREE_CODE_CLASS (code) == tcc_declaration
116       || TREE_CODE_CLASS (code) == tcc_constant)
117     {
118       *walk_subtrees = 0;
119       return NULL_TREE;
120     }
121 
122   /* This is the pattern built in ada/make_aligning_type.  */
123   else if (code == ADDR_EXPR
124 	   && TREE_CODE (TREE_OPERAND (*tp, 0)) == PLACEHOLDER_EXPR)
125     {
126       *walk_subtrees = 0;
127       return NULL_TREE;
128     }
129 
130   /* Default case: the component reference.  */
131   else if (self_referential_component_ref_p (*tp))
132     {
133       *walk_subtrees = 0;
134       return NULL_TREE;
135     }
136 
137   /* We're not supposed to have them in self-referential size trees
138      because we wouldn't properly control when they are evaluated.
139      However, not creating superfluous SAVE_EXPRs requires accurate
140      tracking of readonly-ness all the way down to here, which we
141      cannot always guarantee in practice.  So punt in this case.  */
142   else if (code == SAVE_EXPR)
143     return error_mark_node;
144 
145   else if (code == STATEMENT_LIST)
146     gcc_unreachable ();
147 
148   return copy_tree_r (tp, walk_subtrees, data);
149 }
150 
151 /* Given a SIZE expression that is self-referential, return an equivalent
152    expression to serve as the actual size expression for a type.  */
153 
154 static tree
self_referential_size(tree size)155 self_referential_size (tree size)
156 {
157   static unsigned HOST_WIDE_INT fnno = 0;
158   vec<tree> self_refs = vNULL;
159   tree param_type_list = NULL, param_decl_list = NULL;
160   tree t, ref, return_type, fntype, fnname, fndecl;
161   unsigned int i;
162   char buf[128];
163   vec<tree, va_gc> *args = NULL;
164 
165   /* Do not factor out simple operations.  */
166   t = skip_simple_constant_arithmetic (size);
167   if (TREE_CODE (t) == CALL_EXPR || self_referential_component_ref_p (t))
168     return size;
169 
170   /* Collect the list of self-references in the expression.  */
171   find_placeholder_in_expr (size, &self_refs);
172   gcc_assert (self_refs.length () > 0);
173 
174   /* Obtain a private copy of the expression.  */
175   t = size;
176   if (walk_tree (&t, copy_self_referential_tree_r, NULL, NULL) != NULL_TREE)
177     return size;
178   size = t;
179 
180   /* Build the parameter and argument lists in parallel; also
181      substitute the former for the latter in the expression.  */
182   vec_alloc (args, self_refs.length ());
183   FOR_EACH_VEC_ELT (self_refs, i, ref)
184     {
185       tree subst, param_name, param_type, param_decl;
186 
187       if (DECL_P (ref))
188 	{
189 	  /* We shouldn't have true variables here.  */
190 	  gcc_assert (TREE_READONLY (ref));
191 	  subst = ref;
192 	}
193       /* This is the pattern built in ada/make_aligning_type.  */
194       else if (TREE_CODE (ref) == ADDR_EXPR)
195         subst = ref;
196       /* Default case: the component reference.  */
197       else
198 	subst = TREE_OPERAND (ref, 1);
199 
200       sprintf (buf, "p%d", i);
201       param_name = get_identifier (buf);
202       param_type = TREE_TYPE (ref);
203       param_decl
204 	= build_decl (input_location, PARM_DECL, param_name, param_type);
205       DECL_ARG_TYPE (param_decl) = param_type;
206       DECL_ARTIFICIAL (param_decl) = 1;
207       TREE_READONLY (param_decl) = 1;
208 
209       size = substitute_in_expr (size, subst, param_decl);
210 
211       param_type_list = tree_cons (NULL_TREE, param_type, param_type_list);
212       param_decl_list = chainon (param_decl, param_decl_list);
213       args->quick_push (ref);
214     }
215 
216   self_refs.release ();
217 
218   /* Append 'void' to indicate that the number of parameters is fixed.  */
219   param_type_list = tree_cons (NULL_TREE, void_type_node, param_type_list);
220 
221   /* The 3 lists have been created in reverse order.  */
222   param_type_list = nreverse (param_type_list);
223   param_decl_list = nreverse (param_decl_list);
224 
225   /* Build the function type.  */
226   return_type = TREE_TYPE (size);
227   fntype = build_function_type (return_type, param_type_list);
228 
229   /* Build the function declaration.  */
230   sprintf (buf, "SZ" HOST_WIDE_INT_PRINT_UNSIGNED, fnno++);
231   fnname = get_file_function_name (buf);
232   fndecl = build_decl (input_location, FUNCTION_DECL, fnname, fntype);
233   for (t = param_decl_list; t; t = DECL_CHAIN (t))
234     DECL_CONTEXT (t) = fndecl;
235   DECL_ARGUMENTS (fndecl) = param_decl_list;
236   DECL_RESULT (fndecl)
237     = build_decl (input_location, RESULT_DECL, 0, return_type);
238   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
239 
240   /* The function has been created by the compiler and we don't
241      want to emit debug info for it.  */
242   DECL_ARTIFICIAL (fndecl) = 1;
243   DECL_IGNORED_P (fndecl) = 1;
244 
245   /* It is supposed to be "const" and never throw.  */
246   TREE_READONLY (fndecl) = 1;
247   TREE_NOTHROW (fndecl) = 1;
248 
249   /* We want it to be inlined when this is deemed profitable, as
250      well as discarded if every call has been integrated.  */
251   DECL_DECLARED_INLINE_P (fndecl) = 1;
252 
253   /* It is made up of a unique return statement.  */
254   DECL_INITIAL (fndecl) = make_node (BLOCK);
255   BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
256   t = build2 (MODIFY_EXPR, return_type, DECL_RESULT (fndecl), size);
257   DECL_SAVED_TREE (fndecl) = build1 (RETURN_EXPR, void_type_node, t);
258   TREE_STATIC (fndecl) = 1;
259 
260   /* Put it onto the list of size functions.  */
261   vec_safe_push (size_functions, fndecl);
262 
263   /* Replace the original expression with a call to the size function.  */
264   return build_call_expr_loc_vec (UNKNOWN_LOCATION, fndecl, args);
265 }
266 
267 /* Take, queue and compile all the size functions.  It is essential that
268    the size functions be gimplified at the very end of the compilation
269    in order to guarantee transparent handling of self-referential sizes.
270    Otherwise the GENERIC inliner would not be able to inline them back
271    at each of their call sites, thus creating artificial non-constant
272    size expressions which would trigger nasty problems later on.  */
273 
274 void
finalize_size_functions(void)275 finalize_size_functions (void)
276 {
277   unsigned int i;
278   tree fndecl;
279 
280   for (i = 0; size_functions && size_functions->iterate (i, &fndecl); i++)
281     {
282       allocate_struct_function (fndecl, false);
283       set_cfun (NULL);
284       dump_function (TDI_original, fndecl);
285 
286       /* As these functions are used to describe the layout of variable-length
287          structures, debug info generation needs their implementation.  */
288       debug_hooks->size_function (fndecl);
289       gimplify_function_tree (fndecl);
290       cgraph_node::finalize_function (fndecl, false);
291     }
292 
293   vec_free (size_functions);
294 }
295 
296 /* Return a machine mode of class MCLASS with SIZE bits of precision,
297    if one exists.  The mode may have padding bits as well the SIZE
298    value bits.  If LIMIT is nonzero, disregard modes wider than
299    MAX_FIXED_MODE_SIZE.  */
300 
301 opt_machine_mode
mode_for_size(poly_uint64 size,enum mode_class mclass,int limit)302 mode_for_size (poly_uint64 size, enum mode_class mclass, int limit)
303 {
304   machine_mode mode;
305   int i;
306 
307   if (limit && maybe_gt (size, (unsigned int) MAX_FIXED_MODE_SIZE))
308     return opt_machine_mode ();
309 
310   /* Get the first mode which has this size, in the specified class.  */
311   FOR_EACH_MODE_IN_CLASS (mode, mclass)
312     if (known_eq (GET_MODE_PRECISION (mode), size))
313       return mode;
314 
315   if (mclass == MODE_INT || mclass == MODE_PARTIAL_INT)
316     for (i = 0; i < NUM_INT_N_ENTS; i ++)
317       if (known_eq (int_n_data[i].bitsize, size)
318 	  && int_n_enabled_p[i])
319 	return int_n_data[i].m;
320 
321   return opt_machine_mode ();
322 }
323 
324 /* Similar, except passed a tree node.  */
325 
326 opt_machine_mode
mode_for_size_tree(const_tree size,enum mode_class mclass,int limit)327 mode_for_size_tree (const_tree size, enum mode_class mclass, int limit)
328 {
329   unsigned HOST_WIDE_INT uhwi;
330   unsigned int ui;
331 
332   if (!tree_fits_uhwi_p (size))
333     return opt_machine_mode ();
334   uhwi = tree_to_uhwi (size);
335   ui = uhwi;
336   if (uhwi != ui)
337     return opt_machine_mode ();
338   return mode_for_size (ui, mclass, limit);
339 }
340 
341 /* Return the narrowest mode of class MCLASS that contains at least
342    SIZE bits.  Abort if no such mode exists.  */
343 
344 machine_mode
smallest_mode_for_size(poly_uint64 size,enum mode_class mclass)345 smallest_mode_for_size (poly_uint64 size, enum mode_class mclass)
346 {
347   machine_mode mode = VOIDmode;
348   int i;
349 
350   /* Get the first mode which has at least this size, in the
351      specified class.  */
352   FOR_EACH_MODE_IN_CLASS (mode, mclass)
353     if (known_ge (GET_MODE_PRECISION (mode), size))
354       break;
355 
356   gcc_assert (mode != VOIDmode);
357 
358   if (mclass == MODE_INT || mclass == MODE_PARTIAL_INT)
359     for (i = 0; i < NUM_INT_N_ENTS; i ++)
360       if (known_ge (int_n_data[i].bitsize, size)
361 	  && known_lt (int_n_data[i].bitsize, GET_MODE_PRECISION (mode))
362 	  && int_n_enabled_p[i])
363 	mode = int_n_data[i].m;
364 
365   return mode;
366 }
367 
368 /* Return an integer mode of exactly the same size as MODE, if one exists.  */
369 
370 opt_scalar_int_mode
int_mode_for_mode(machine_mode mode)371 int_mode_for_mode (machine_mode mode)
372 {
373   switch (GET_MODE_CLASS (mode))
374     {
375     case MODE_INT:
376     case MODE_PARTIAL_INT:
377       return as_a <scalar_int_mode> (mode);
378 
379     case MODE_COMPLEX_INT:
380     case MODE_COMPLEX_FLOAT:
381     case MODE_FLOAT:
382     case MODE_DECIMAL_FLOAT:
383     case MODE_FRACT:
384     case MODE_ACCUM:
385     case MODE_UFRACT:
386     case MODE_UACCUM:
387     case MODE_VECTOR_BOOL:
388     case MODE_VECTOR_INT:
389     case MODE_VECTOR_FLOAT:
390     case MODE_VECTOR_FRACT:
391     case MODE_VECTOR_ACCUM:
392     case MODE_VECTOR_UFRACT:
393     case MODE_VECTOR_UACCUM:
394       return int_mode_for_size (GET_MODE_BITSIZE (mode), 0);
395 
396     case MODE_RANDOM:
397       if (mode == BLKmode)
398 	return opt_scalar_int_mode ();
399 
400       /* fall through */
401 
402     case MODE_CC:
403     default:
404       gcc_unreachable ();
405     }
406 }
407 
408 /* Find a mode that can be used for efficient bitwise operations on MODE,
409    if one exists.  */
410 
411 opt_machine_mode
bitwise_mode_for_mode(machine_mode mode)412 bitwise_mode_for_mode (machine_mode mode)
413 {
414   /* Quick exit if we already have a suitable mode.  */
415   scalar_int_mode int_mode;
416   if (is_a <scalar_int_mode> (mode, &int_mode)
417       && GET_MODE_BITSIZE (int_mode) <= MAX_FIXED_MODE_SIZE)
418     return int_mode;
419 
420   /* Reuse the sanity checks from int_mode_for_mode.  */
421   gcc_checking_assert ((int_mode_for_mode (mode), true));
422 
423   poly_int64 bitsize = GET_MODE_BITSIZE (mode);
424 
425   /* Try to replace complex modes with complex modes.  In general we
426      expect both components to be processed independently, so we only
427      care whether there is a register for the inner mode.  */
428   if (COMPLEX_MODE_P (mode))
429     {
430       machine_mode trial = mode;
431       if ((GET_MODE_CLASS (trial) == MODE_COMPLEX_INT
432 	   || mode_for_size (bitsize, MODE_COMPLEX_INT, false).exists (&trial))
433 	  && have_regs_of_mode[GET_MODE_INNER (trial)])
434 	return trial;
435     }
436 
437   /* Try to replace vector modes with vector modes.  Also try using vector
438      modes if an integer mode would be too big.  */
439   if (VECTOR_MODE_P (mode)
440       || maybe_gt (bitsize, MAX_FIXED_MODE_SIZE))
441     {
442       machine_mode trial = mode;
443       if ((GET_MODE_CLASS (trial) == MODE_VECTOR_INT
444 	   || mode_for_size (bitsize, MODE_VECTOR_INT, 0).exists (&trial))
445 	  && have_regs_of_mode[trial]
446 	  && targetm.vector_mode_supported_p (trial))
447 	return trial;
448     }
449 
450   /* Otherwise fall back on integers while honoring MAX_FIXED_MODE_SIZE.  */
451   return mode_for_size (bitsize, MODE_INT, true);
452 }
453 
454 /* Find a type that can be used for efficient bitwise operations on MODE.
455    Return null if no such mode exists.  */
456 
457 tree
bitwise_type_for_mode(machine_mode mode)458 bitwise_type_for_mode (machine_mode mode)
459 {
460   if (!bitwise_mode_for_mode (mode).exists (&mode))
461     return NULL_TREE;
462 
463   unsigned int inner_size = GET_MODE_UNIT_BITSIZE (mode);
464   tree inner_type = build_nonstandard_integer_type (inner_size, true);
465 
466   if (VECTOR_MODE_P (mode))
467     return build_vector_type_for_mode (inner_type, mode);
468 
469   if (COMPLEX_MODE_P (mode))
470     return build_complex_type (inner_type);
471 
472   gcc_checking_assert (GET_MODE_INNER (mode) == mode);
473   return inner_type;
474 }
475 
476 /* Find a mode that is suitable for representing a vector with NUNITS
477    elements of mode INNERMODE, if one exists.  The returned mode can be
478    either an integer mode or a vector mode.  */
479 
480 opt_machine_mode
mode_for_vector(scalar_mode innermode,poly_uint64 nunits)481 mode_for_vector (scalar_mode innermode, poly_uint64 nunits)
482 {
483   machine_mode mode;
484 
485   /* First, look for a supported vector type.  */
486   if (SCALAR_FLOAT_MODE_P (innermode))
487     mode = MIN_MODE_VECTOR_FLOAT;
488   else if (SCALAR_FRACT_MODE_P (innermode))
489     mode = MIN_MODE_VECTOR_FRACT;
490   else if (SCALAR_UFRACT_MODE_P (innermode))
491     mode = MIN_MODE_VECTOR_UFRACT;
492   else if (SCALAR_ACCUM_MODE_P (innermode))
493     mode = MIN_MODE_VECTOR_ACCUM;
494   else if (SCALAR_UACCUM_MODE_P (innermode))
495     mode = MIN_MODE_VECTOR_UACCUM;
496   else
497     mode = MIN_MODE_VECTOR_INT;
498 
499   /* Do not check vector_mode_supported_p here.  We'll do that
500      later in vector_type_mode.  */
501   FOR_EACH_MODE_FROM (mode, mode)
502     if (known_eq (GET_MODE_NUNITS (mode), nunits)
503 	&& GET_MODE_INNER (mode) == innermode)
504       return mode;
505 
506   /* For integers, try mapping it to a same-sized scalar mode.  */
507   if (GET_MODE_CLASS (innermode) == MODE_INT)
508     {
509       poly_uint64 nbits = nunits * GET_MODE_BITSIZE (innermode);
510       if (int_mode_for_size (nbits, 0).exists (&mode)
511 	  && have_regs_of_mode[mode])
512 	return mode;
513     }
514 
515   return opt_machine_mode ();
516 }
517 
518 /* If a piece of code is using vector mode VECTOR_MODE and also wants
519    to operate on elements of mode ELEMENT_MODE, return the vector mode
520    it should use for those elements.  If NUNITS is nonzero, ensure that
521    the mode has exactly NUNITS elements, otherwise pick whichever vector
522    size pairs the most naturally with VECTOR_MODE; this may mean choosing
523    a mode with a different size and/or number of elements, depending on
524    what the target prefers.  Return an empty opt_machine_mode if there
525    is no supported vector mode with the required properties.
526 
527    Unlike mode_for_vector. any returned mode is guaranteed to satisfy
528    both VECTOR_MODE_P and targetm.vector_mode_supported_p.  */
529 
530 opt_machine_mode
related_vector_mode(machine_mode vector_mode,scalar_mode element_mode,poly_uint64 nunits)531 related_vector_mode (machine_mode vector_mode, scalar_mode element_mode,
532 		     poly_uint64 nunits)
533 {
534   gcc_assert (VECTOR_MODE_P (vector_mode));
535   return targetm.vectorize.related_mode (vector_mode, element_mode, nunits);
536 }
537 
538 /* If a piece of code is using vector mode VECTOR_MODE and also wants
539    to operate on integer vectors with the same element size and number
540    of elements, return the vector mode it should use.  Return an empty
541    opt_machine_mode if there is no supported vector mode with the
542    required properties.
543 
544    Unlike mode_for_vector. any returned mode is guaranteed to satisfy
545    both VECTOR_MODE_P and targetm.vector_mode_supported_p.  */
546 
547 opt_machine_mode
related_int_vector_mode(machine_mode vector_mode)548 related_int_vector_mode (machine_mode vector_mode)
549 {
550   gcc_assert (VECTOR_MODE_P (vector_mode));
551   scalar_int_mode int_mode;
552   if (int_mode_for_mode (GET_MODE_INNER (vector_mode)).exists (&int_mode))
553     return related_vector_mode (vector_mode, int_mode,
554 				GET_MODE_NUNITS (vector_mode));
555   return opt_machine_mode ();
556 }
557 
558 /* Return the alignment of MODE. This will be bounded by 1 and
559    BIGGEST_ALIGNMENT.  */
560 
561 unsigned int
get_mode_alignment(machine_mode mode)562 get_mode_alignment (machine_mode mode)
563 {
564   return MIN (BIGGEST_ALIGNMENT, MAX (1, mode_base_align[mode]*BITS_PER_UNIT));
565 }
566 
567 /* Return the natural mode of an array, given that it is SIZE bytes in
568    total and has elements of type ELEM_TYPE.  */
569 
570 static machine_mode
mode_for_array(tree elem_type,tree size)571 mode_for_array (tree elem_type, tree size)
572 {
573   tree elem_size;
574   poly_uint64 int_size, int_elem_size;
575   unsigned HOST_WIDE_INT num_elems;
576   bool limit_p;
577 
578   /* One-element arrays get the component type's mode.  */
579   elem_size = TYPE_SIZE (elem_type);
580   if (simple_cst_equal (size, elem_size))
581     return TYPE_MODE (elem_type);
582 
583   limit_p = true;
584   if (poly_int_tree_p (size, &int_size)
585       && poly_int_tree_p (elem_size, &int_elem_size)
586       && maybe_ne (int_elem_size, 0U)
587       && constant_multiple_p (int_size, int_elem_size, &num_elems))
588     {
589       machine_mode elem_mode = TYPE_MODE (elem_type);
590       machine_mode mode;
591       if (targetm.array_mode (elem_mode, num_elems).exists (&mode))
592 	return mode;
593       if (targetm.array_mode_supported_p (elem_mode, num_elems))
594 	limit_p = false;
595     }
596   return mode_for_size_tree (size, MODE_INT, limit_p).else_blk ();
597 }
598 
599 /* Subroutine of layout_decl: Force alignment required for the data type.
600    But if the decl itself wants greater alignment, don't override that.  */
601 
602 static inline void
do_type_align(tree type,tree decl)603 do_type_align (tree type, tree decl)
604 {
605   if (TYPE_ALIGN (type) > DECL_ALIGN (decl))
606     {
607       SET_DECL_ALIGN (decl, TYPE_ALIGN (type));
608       if (TREE_CODE (decl) == FIELD_DECL)
609 	DECL_USER_ALIGN (decl) = TYPE_USER_ALIGN (type);
610     }
611   if (TYPE_WARN_IF_NOT_ALIGN (type) > DECL_WARN_IF_NOT_ALIGN (decl))
612     SET_DECL_WARN_IF_NOT_ALIGN (decl, TYPE_WARN_IF_NOT_ALIGN (type));
613 }
614 
615 /* Set the size, mode and alignment of a ..._DECL node.
616    TYPE_DECL does need this for C++.
617    Note that LABEL_DECL and CONST_DECL nodes do not need this,
618    and FUNCTION_DECL nodes have them set up in a special (and simple) way.
619    Don't call layout_decl for them.
620 
621    KNOWN_ALIGN is the amount of alignment we can assume this
622    decl has with no special effort.  It is relevant only for FIELD_DECLs
623    and depends on the previous fields.
624    All that matters about KNOWN_ALIGN is which powers of 2 divide it.
625    If KNOWN_ALIGN is 0, it means, "as much alignment as you like":
626    the record will be aligned to suit.  */
627 
628 void
layout_decl(tree decl,unsigned int known_align)629 layout_decl (tree decl, unsigned int known_align)
630 {
631   tree type = TREE_TYPE (decl);
632   enum tree_code code = TREE_CODE (decl);
633   rtx rtl = NULL_RTX;
634   location_t loc = DECL_SOURCE_LOCATION (decl);
635 
636   if (code == CONST_DECL)
637     return;
638 
639   gcc_assert (code == VAR_DECL || code == PARM_DECL || code == RESULT_DECL
640 	      || code == TYPE_DECL || code == FIELD_DECL);
641 
642   rtl = DECL_RTL_IF_SET (decl);
643 
644   if (type == error_mark_node)
645     type = void_type_node;
646 
647   /* Usually the size and mode come from the data type without change,
648      however, the front-end may set the explicit width of the field, so its
649      size may not be the same as the size of its type.  This happens with
650      bitfields, of course (an `int' bitfield may be only 2 bits, say), but it
651      also happens with other fields.  For example, the C++ front-end creates
652      zero-sized fields corresponding to empty base classes, and depends on
653      layout_type setting DECL_FIELD_BITPOS correctly for the field.  Set the
654      size in bytes from the size in bits.  If we have already set the mode,
655      don't set it again since we can be called twice for FIELD_DECLs.  */
656 
657   DECL_UNSIGNED (decl) = TYPE_UNSIGNED (type);
658   if (DECL_MODE (decl) == VOIDmode)
659     SET_DECL_MODE (decl, TYPE_MODE (type));
660 
661   if (DECL_SIZE (decl) == 0)
662     {
663       DECL_SIZE (decl) = TYPE_SIZE (type);
664       DECL_SIZE_UNIT (decl) = TYPE_SIZE_UNIT (type);
665     }
666   else if (DECL_SIZE_UNIT (decl) == 0)
667     DECL_SIZE_UNIT (decl)
668       = fold_convert_loc (loc, sizetype,
669 			  size_binop_loc (loc, CEIL_DIV_EXPR, DECL_SIZE (decl),
670 					  bitsize_unit_node));
671 
672   if (code != FIELD_DECL)
673     /* For non-fields, update the alignment from the type.  */
674     do_type_align (type, decl);
675   else
676     /* For fields, it's a bit more complicated...  */
677     {
678       bool old_user_align = DECL_USER_ALIGN (decl);
679       bool zero_bitfield = false;
680       bool packed_p = DECL_PACKED (decl);
681       unsigned int mfa;
682 
683       if (DECL_BIT_FIELD (decl))
684 	{
685 	  DECL_BIT_FIELD_TYPE (decl) = type;
686 
687 	  /* A zero-length bit-field affects the alignment of the next
688 	     field.  In essence such bit-fields are not influenced by
689 	     any packing due to #pragma pack or attribute packed.  */
690 	  if (integer_zerop (DECL_SIZE (decl))
691 	      && ! targetm.ms_bitfield_layout_p (DECL_FIELD_CONTEXT (decl)))
692 	    {
693 	      zero_bitfield = true;
694 	      packed_p = false;
695 	      if (PCC_BITFIELD_TYPE_MATTERS)
696 		do_type_align (type, decl);
697 	      else
698 		{
699 #ifdef EMPTY_FIELD_BOUNDARY
700 		  if (EMPTY_FIELD_BOUNDARY > DECL_ALIGN (decl))
701 		    {
702 		      SET_DECL_ALIGN (decl, EMPTY_FIELD_BOUNDARY);
703 		      DECL_USER_ALIGN (decl) = 0;
704 		    }
705 #endif
706 		}
707 	    }
708 
709 	  /* See if we can use an ordinary integer mode for a bit-field.
710 	     Conditions are: a fixed size that is correct for another mode,
711 	     occupying a complete byte or bytes on proper boundary.  */
712 	  if (TYPE_SIZE (type) != 0
713 	      && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
714 	      && GET_MODE_CLASS (TYPE_MODE (type)) == MODE_INT)
715 	    {
716 	      machine_mode xmode;
717 	      if (mode_for_size_tree (DECL_SIZE (decl),
718 				      MODE_INT, 1).exists (&xmode))
719 		{
720 		  unsigned int xalign = GET_MODE_ALIGNMENT (xmode);
721 		  if (!(xalign > BITS_PER_UNIT && DECL_PACKED (decl))
722 		      && (known_align == 0 || known_align >= xalign))
723 		    {
724 		      SET_DECL_ALIGN (decl, MAX (xalign, DECL_ALIGN (decl)));
725 		      SET_DECL_MODE (decl, xmode);
726 		      DECL_BIT_FIELD (decl) = 0;
727 		    }
728 		}
729 	    }
730 
731 	  /* Turn off DECL_BIT_FIELD if we won't need it set.  */
732 	  if (TYPE_MODE (type) == BLKmode && DECL_MODE (decl) == BLKmode
733 	      && known_align >= TYPE_ALIGN (type)
734 	      && DECL_ALIGN (decl) >= TYPE_ALIGN (type))
735 	    DECL_BIT_FIELD (decl) = 0;
736 	}
737       else if (packed_p && DECL_USER_ALIGN (decl))
738 	/* Don't touch DECL_ALIGN.  For other packed fields, go ahead and
739 	   round up; we'll reduce it again below.  We want packing to
740 	   supersede USER_ALIGN inherited from the type, but defer to
741 	   alignment explicitly specified on the field decl.  */;
742       else
743 	do_type_align (type, decl);
744 
745       /* If the field is packed and not explicitly aligned, give it the
746 	 minimum alignment.  Note that do_type_align may set
747 	 DECL_USER_ALIGN, so we need to check old_user_align instead.  */
748       if (packed_p
749 	  && !old_user_align)
750 	SET_DECL_ALIGN (decl, MIN (DECL_ALIGN (decl), BITS_PER_UNIT));
751 
752       if (! packed_p && ! DECL_USER_ALIGN (decl))
753 	{
754 	  /* Some targets (i.e. i386, VMS) limit struct field alignment
755 	     to a lower boundary than alignment of variables unless
756 	     it was overridden by attribute aligned.  */
757 #ifdef BIGGEST_FIELD_ALIGNMENT
758 	  SET_DECL_ALIGN (decl, MIN (DECL_ALIGN (decl),
759 				     (unsigned) BIGGEST_FIELD_ALIGNMENT));
760 #endif
761 #ifdef ADJUST_FIELD_ALIGN
762 	  SET_DECL_ALIGN (decl, ADJUST_FIELD_ALIGN (decl, TREE_TYPE (decl),
763 						    DECL_ALIGN (decl)));
764 #endif
765 	}
766 
767       if (zero_bitfield)
768         mfa = initial_max_fld_align * BITS_PER_UNIT;
769       else
770 	mfa = maximum_field_alignment;
771       /* Should this be controlled by DECL_USER_ALIGN, too?  */
772       if (mfa != 0)
773 	SET_DECL_ALIGN (decl, MIN (DECL_ALIGN (decl), mfa));
774     }
775 
776   /* Evaluate nonconstant size only once, either now or as soon as safe.  */
777   if (DECL_SIZE (decl) != 0 && TREE_CODE (DECL_SIZE (decl)) != INTEGER_CST)
778     DECL_SIZE (decl) = variable_size (DECL_SIZE (decl));
779   if (DECL_SIZE_UNIT (decl) != 0
780       && TREE_CODE (DECL_SIZE_UNIT (decl)) != INTEGER_CST)
781     DECL_SIZE_UNIT (decl) = variable_size (DECL_SIZE_UNIT (decl));
782 
783   /* If requested, warn about definitions of large data objects.  */
784   if ((code == PARM_DECL || (code == VAR_DECL && !DECL_NONLOCAL_FRAME (decl)))
785       && !DECL_EXTERNAL (decl))
786     {
787       tree size = DECL_SIZE_UNIT (decl);
788 
789       if (size != 0 && TREE_CODE (size) == INTEGER_CST)
790 	{
791 	  /* -Wlarger-than= argument of HOST_WIDE_INT_MAX is treated
792 	     as if PTRDIFF_MAX had been specified, with the value
793 	     being that on the target rather than the host.  */
794 	  unsigned HOST_WIDE_INT max_size = warn_larger_than_size;
795 	  if (max_size == HOST_WIDE_INT_MAX)
796 	    max_size = tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node));
797 
798 	  if (compare_tree_int (size, max_size) > 0)
799 	    warning (OPT_Wlarger_than_, "size of %q+D %E bytes exceeds "
800 		     "maximum object size %wu",
801 		     decl, size, max_size);
802 	}
803     }
804 
805   /* If the RTL was already set, update its mode and mem attributes.  */
806   if (rtl)
807     {
808       PUT_MODE (rtl, DECL_MODE (decl));
809       SET_DECL_RTL (decl, 0);
810       if (MEM_P (rtl))
811 	set_mem_attributes (rtl, decl, 1);
812       SET_DECL_RTL (decl, rtl);
813     }
814 }
815 
816 /* Given a VAR_DECL, PARM_DECL, RESULT_DECL, or FIELD_DECL, clears the
817    results of a previous call to layout_decl and calls it again.  */
818 
819 void
relayout_decl(tree decl)820 relayout_decl (tree decl)
821 {
822   DECL_SIZE (decl) = DECL_SIZE_UNIT (decl) = 0;
823   SET_DECL_MODE (decl, VOIDmode);
824   if (!DECL_USER_ALIGN (decl))
825     SET_DECL_ALIGN (decl, 0);
826   if (DECL_RTL_SET_P (decl))
827     SET_DECL_RTL (decl, 0);
828 
829   layout_decl (decl, 0);
830 }
831 
832 /* Begin laying out type T, which may be a RECORD_TYPE, UNION_TYPE, or
833    QUAL_UNION_TYPE.  Return a pointer to a struct record_layout_info which
834    is to be passed to all other layout functions for this record.  It is the
835    responsibility of the caller to call `free' for the storage returned.
836    Note that garbage collection is not permitted until we finish laying
837    out the record.  */
838 
839 record_layout_info
start_record_layout(tree t)840 start_record_layout (tree t)
841 {
842   record_layout_info rli = XNEW (struct record_layout_info_s);
843 
844   rli->t = t;
845 
846   /* If the type has a minimum specified alignment (via an attribute
847      declaration, for example) use it -- otherwise, start with a
848      one-byte alignment.  */
849   rli->record_align = MAX (BITS_PER_UNIT, TYPE_ALIGN (t));
850   rli->unpacked_align = rli->record_align;
851   rli->offset_align = MAX (rli->record_align, BIGGEST_ALIGNMENT);
852 
853 #ifdef STRUCTURE_SIZE_BOUNDARY
854   /* Packed structures don't need to have minimum size.  */
855   if (! TYPE_PACKED (t))
856     {
857       unsigned tmp;
858 
859       /* #pragma pack overrides STRUCTURE_SIZE_BOUNDARY.  */
860       tmp = (unsigned) STRUCTURE_SIZE_BOUNDARY;
861       if (maximum_field_alignment != 0)
862 	tmp = MIN (tmp, maximum_field_alignment);
863       rli->record_align = MAX (rli->record_align, tmp);
864     }
865 #endif
866 
867   rli->offset = size_zero_node;
868   rli->bitpos = bitsize_zero_node;
869   rli->prev_field = 0;
870   rli->pending_statics = 0;
871   rli->packed_maybe_necessary = 0;
872   rli->remaining_in_alignment = 0;
873 
874   return rli;
875 }
876 
877 /* Fold sizetype value X to bitsizetype, given that X represents a type
878    size or offset.  */
879 
880 static tree
bits_from_bytes(tree x)881 bits_from_bytes (tree x)
882 {
883   if (POLY_INT_CST_P (x))
884     /* The runtime calculation isn't allowed to overflow sizetype;
885        increasing the runtime values must always increase the size
886        or offset of the object.  This means that the object imposes
887        a maximum value on the runtime parameters, but we don't record
888        what that is.  */
889     return build_poly_int_cst
890       (bitsizetype,
891        poly_wide_int::from (poly_int_cst_value (x),
892 			    TYPE_PRECISION (bitsizetype),
893 			    TYPE_SIGN (TREE_TYPE (x))));
894   x = fold_convert (bitsizetype, x);
895   gcc_checking_assert (x);
896   return x;
897 }
898 
899 /* Return the combined bit position for the byte offset OFFSET and the
900    bit position BITPOS.
901 
902    These functions operate on byte and bit positions present in FIELD_DECLs
903    and assume that these expressions result in no (intermediate) overflow.
904    This assumption is necessary to fold the expressions as much as possible,
905    so as to avoid creating artificially variable-sized types in languages
906    supporting variable-sized types like Ada.  */
907 
908 tree
bit_from_pos(tree offset,tree bitpos)909 bit_from_pos (tree offset, tree bitpos)
910 {
911   return size_binop (PLUS_EXPR, bitpos,
912 		     size_binop (MULT_EXPR, bits_from_bytes (offset),
913 				 bitsize_unit_node));
914 }
915 
916 /* Return the combined truncated byte position for the byte offset OFFSET and
917    the bit position BITPOS.  */
918 
919 tree
byte_from_pos(tree offset,tree bitpos)920 byte_from_pos (tree offset, tree bitpos)
921 {
922   tree bytepos;
923   if (TREE_CODE (bitpos) == MULT_EXPR
924       && tree_int_cst_equal (TREE_OPERAND (bitpos, 1), bitsize_unit_node))
925     bytepos = TREE_OPERAND (bitpos, 0);
926   else
927     bytepos = size_binop (TRUNC_DIV_EXPR, bitpos, bitsize_unit_node);
928   return size_binop (PLUS_EXPR, offset, fold_convert (sizetype, bytepos));
929 }
930 
931 /* Split the bit position POS into a byte offset *POFFSET and a bit
932    position *PBITPOS with the byte offset aligned to OFF_ALIGN bits.  */
933 
934 void
pos_from_bit(tree * poffset,tree * pbitpos,unsigned int off_align,tree pos)935 pos_from_bit (tree *poffset, tree *pbitpos, unsigned int off_align,
936 	      tree pos)
937 {
938   tree toff_align = bitsize_int (off_align);
939   if (TREE_CODE (pos) == MULT_EXPR
940       && tree_int_cst_equal (TREE_OPERAND (pos, 1), toff_align))
941     {
942       *poffset = size_binop (MULT_EXPR,
943 			     fold_convert (sizetype, TREE_OPERAND (pos, 0)),
944 			     size_int (off_align / BITS_PER_UNIT));
945       *pbitpos = bitsize_zero_node;
946     }
947   else
948     {
949       *poffset = size_binop (MULT_EXPR,
950 			     fold_convert (sizetype,
951 					   size_binop (FLOOR_DIV_EXPR, pos,
952 						       toff_align)),
953 			     size_int (off_align / BITS_PER_UNIT));
954       *pbitpos = size_binop (FLOOR_MOD_EXPR, pos, toff_align);
955     }
956 }
957 
958 /* Given a pointer to bit and byte offsets and an offset alignment,
959    normalize the offsets so they are within the alignment.  */
960 
961 void
normalize_offset(tree * poffset,tree * pbitpos,unsigned int off_align)962 normalize_offset (tree *poffset, tree *pbitpos, unsigned int off_align)
963 {
964   /* If the bit position is now larger than it should be, adjust it
965      downwards.  */
966   if (compare_tree_int (*pbitpos, off_align) >= 0)
967     {
968       tree offset, bitpos;
969       pos_from_bit (&offset, &bitpos, off_align, *pbitpos);
970       *poffset = size_binop (PLUS_EXPR, *poffset, offset);
971       *pbitpos = bitpos;
972     }
973 }
974 
975 /* Print debugging information about the information in RLI.  */
976 
977 DEBUG_FUNCTION void
debug_rli(record_layout_info rli)978 debug_rli (record_layout_info rli)
979 {
980   print_node_brief (stderr, "type", rli->t, 0);
981   print_node_brief (stderr, "\noffset", rli->offset, 0);
982   print_node_brief (stderr, " bitpos", rli->bitpos, 0);
983 
984   fprintf (stderr, "\naligns: rec = %u, unpack = %u, off = %u\n",
985 	   rli->record_align, rli->unpacked_align,
986 	   rli->offset_align);
987 
988   /* The ms_struct code is the only that uses this.  */
989   if (targetm.ms_bitfield_layout_p (rli->t))
990     fprintf (stderr, "remaining in alignment = %u\n", rli->remaining_in_alignment);
991 
992   if (rli->packed_maybe_necessary)
993     fprintf (stderr, "packed may be necessary\n");
994 
995   if (!vec_safe_is_empty (rli->pending_statics))
996     {
997       fprintf (stderr, "pending statics:\n");
998       debug (rli->pending_statics);
999     }
1000 }
1001 
1002 /* Given an RLI with a possibly-incremented BITPOS, adjust OFFSET and
1003    BITPOS if necessary to keep BITPOS below OFFSET_ALIGN.  */
1004 
1005 void
normalize_rli(record_layout_info rli)1006 normalize_rli (record_layout_info rli)
1007 {
1008   normalize_offset (&rli->offset, &rli->bitpos, rli->offset_align);
1009 }
1010 
1011 /* Returns the size in bytes allocated so far.  */
1012 
1013 tree
rli_size_unit_so_far(record_layout_info rli)1014 rli_size_unit_so_far (record_layout_info rli)
1015 {
1016   return byte_from_pos (rli->offset, rli->bitpos);
1017 }
1018 
1019 /* Returns the size in bits allocated so far.  */
1020 
1021 tree
rli_size_so_far(record_layout_info rli)1022 rli_size_so_far (record_layout_info rli)
1023 {
1024   return bit_from_pos (rli->offset, rli->bitpos);
1025 }
1026 
1027 /* FIELD is about to be added to RLI->T.  The alignment (in bits) of
1028    the next available location within the record is given by KNOWN_ALIGN.
1029    Update the variable alignment fields in RLI, and return the alignment
1030    to give the FIELD.  */
1031 
1032 unsigned int
update_alignment_for_field(record_layout_info rli,tree field,unsigned int known_align)1033 update_alignment_for_field (record_layout_info rli, tree field,
1034 			    unsigned int known_align)
1035 {
1036   /* The alignment required for FIELD.  */
1037   unsigned int desired_align;
1038   /* The type of this field.  */
1039   tree type = TREE_TYPE (field);
1040   /* True if the field was explicitly aligned by the user.  */
1041   bool user_align;
1042   bool is_bitfield;
1043 
1044   /* Do not attempt to align an ERROR_MARK node */
1045   if (TREE_CODE (type) == ERROR_MARK)
1046     return 0;
1047 
1048   /* Lay out the field so we know what alignment it needs.  */
1049   layout_decl (field, known_align);
1050   desired_align = DECL_ALIGN (field);
1051   user_align = DECL_USER_ALIGN (field);
1052 
1053   is_bitfield = (type != error_mark_node
1054 		 && DECL_BIT_FIELD_TYPE (field)
1055 		 && ! integer_zerop (TYPE_SIZE (type)));
1056 
1057   /* Record must have at least as much alignment as any field.
1058      Otherwise, the alignment of the field within the record is
1059      meaningless.  */
1060   if (targetm.ms_bitfield_layout_p (rli->t))
1061     {
1062       /* Here, the alignment of the underlying type of a bitfield can
1063 	 affect the alignment of a record; even a zero-sized field
1064 	 can do this.  The alignment should be to the alignment of
1065 	 the type, except that for zero-size bitfields this only
1066 	 applies if there was an immediately prior, nonzero-size
1067 	 bitfield.  (That's the way it is, experimentally.) */
1068       if (!is_bitfield
1069 	  || ((DECL_SIZE (field) == NULL_TREE
1070 	       || !integer_zerop (DECL_SIZE (field)))
1071 	      ? !DECL_PACKED (field)
1072 	      : (rli->prev_field
1073 		 && DECL_BIT_FIELD_TYPE (rli->prev_field)
1074 		 && ! integer_zerop (DECL_SIZE (rli->prev_field)))))
1075 	{
1076 	  unsigned int type_align = TYPE_ALIGN (type);
1077 	  if (!is_bitfield && DECL_PACKED (field))
1078 	    type_align = desired_align;
1079 	  else
1080 	    type_align = MAX (type_align, desired_align);
1081 	  if (maximum_field_alignment != 0)
1082 	    type_align = MIN (type_align, maximum_field_alignment);
1083 	  rli->record_align = MAX (rli->record_align, type_align);
1084 	  rli->unpacked_align = MAX (rli->unpacked_align, TYPE_ALIGN (type));
1085 	}
1086     }
1087   else if (is_bitfield && PCC_BITFIELD_TYPE_MATTERS)
1088     {
1089       /* Named bit-fields cause the entire structure to have the
1090 	 alignment implied by their type.  Some targets also apply the same
1091 	 rules to unnamed bitfields.  */
1092       if (DECL_NAME (field) != 0
1093 	  || targetm.align_anon_bitfield ())
1094 	{
1095 	  unsigned int type_align = TYPE_ALIGN (type);
1096 
1097 #ifdef ADJUST_FIELD_ALIGN
1098 	  if (! TYPE_USER_ALIGN (type))
1099 	    type_align = ADJUST_FIELD_ALIGN (field, type, type_align);
1100 #endif
1101 
1102 	  /* Targets might chose to handle unnamed and hence possibly
1103 	     zero-width bitfield.  Those are not influenced by #pragmas
1104 	     or packed attributes.  */
1105 	  if (integer_zerop (DECL_SIZE (field)))
1106 	    {
1107 	      if (initial_max_fld_align)
1108 	        type_align = MIN (type_align,
1109 				  initial_max_fld_align * BITS_PER_UNIT);
1110 	    }
1111 	  else if (maximum_field_alignment != 0)
1112 	    type_align = MIN (type_align, maximum_field_alignment);
1113 	  else if (DECL_PACKED (field))
1114 	    type_align = MIN (type_align, BITS_PER_UNIT);
1115 
1116 	  /* The alignment of the record is increased to the maximum
1117 	     of the current alignment, the alignment indicated on the
1118 	     field (i.e., the alignment specified by an __aligned__
1119 	     attribute), and the alignment indicated by the type of
1120 	     the field.  */
1121 	  rli->record_align = MAX (rli->record_align, desired_align);
1122 	  rli->record_align = MAX (rli->record_align, type_align);
1123 
1124 	  if (warn_packed)
1125 	    rli->unpacked_align = MAX (rli->unpacked_align, TYPE_ALIGN (type));
1126 	  user_align |= TYPE_USER_ALIGN (type);
1127 	}
1128     }
1129   else
1130     {
1131       rli->record_align = MAX (rli->record_align, desired_align);
1132       rli->unpacked_align = MAX (rli->unpacked_align, TYPE_ALIGN (type));
1133     }
1134 
1135   TYPE_USER_ALIGN (rli->t) |= user_align;
1136 
1137   return desired_align;
1138 }
1139 
1140 /* Issue a warning if the record alignment, RECORD_ALIGN, is less than
1141    the field alignment of FIELD or FIELD isn't aligned. */
1142 
1143 static void
handle_warn_if_not_align(tree field,unsigned int record_align)1144 handle_warn_if_not_align (tree field, unsigned int record_align)
1145 {
1146   tree type = TREE_TYPE (field);
1147 
1148   if (type == error_mark_node)
1149     return;
1150 
1151   unsigned int warn_if_not_align = 0;
1152 
1153   int opt_w = 0;
1154 
1155   if (warn_if_not_aligned)
1156     {
1157       warn_if_not_align = DECL_WARN_IF_NOT_ALIGN (field);
1158       if (!warn_if_not_align)
1159 	warn_if_not_align = TYPE_WARN_IF_NOT_ALIGN (type);
1160       if (warn_if_not_align)
1161 	opt_w = OPT_Wif_not_aligned;
1162     }
1163 
1164   if (!warn_if_not_align
1165       && warn_packed_not_aligned
1166       && lookup_attribute ("aligned", TYPE_ATTRIBUTES (type)))
1167     {
1168       warn_if_not_align = TYPE_ALIGN (type);
1169       opt_w = OPT_Wpacked_not_aligned;
1170     }
1171 
1172   if (!warn_if_not_align)
1173     return;
1174 
1175   tree context = DECL_CONTEXT (field);
1176 
1177   warn_if_not_align /= BITS_PER_UNIT;
1178   record_align /= BITS_PER_UNIT;
1179   if ((record_align % warn_if_not_align) != 0)
1180     warning (opt_w, "alignment %u of %qT is less than %u",
1181 	     record_align, context, warn_if_not_align);
1182 
1183   tree off = byte_position (field);
1184   if (!multiple_of_p (TREE_TYPE (off), off, size_int (warn_if_not_align)))
1185     {
1186       if (TREE_CODE (off) == INTEGER_CST)
1187 	warning (opt_w, "%q+D offset %E in %qT isn%'t aligned to %u",
1188 		 field, off, context, warn_if_not_align);
1189       else
1190 	warning (opt_w, "%q+D offset %E in %qT may not be aligned to %u",
1191 		 field, off, context, warn_if_not_align);
1192     }
1193 }
1194 
1195 /* Called from place_field to handle unions.  */
1196 
1197 static void
place_union_field(record_layout_info rli,tree field)1198 place_union_field (record_layout_info rli, tree field)
1199 {
1200   update_alignment_for_field (rli, field, /*known_align=*/0);
1201 
1202   DECL_FIELD_OFFSET (field) = size_zero_node;
1203   DECL_FIELD_BIT_OFFSET (field) = bitsize_zero_node;
1204   SET_DECL_OFFSET_ALIGN (field, BIGGEST_ALIGNMENT);
1205   handle_warn_if_not_align (field, rli->record_align);
1206 
1207   /* If this is an ERROR_MARK return *after* having set the
1208      field at the start of the union. This helps when parsing
1209      invalid fields. */
1210   if (TREE_CODE (TREE_TYPE (field)) == ERROR_MARK)
1211     return;
1212 
1213   if (AGGREGATE_TYPE_P (TREE_TYPE (field))
1214       && TYPE_TYPELESS_STORAGE (TREE_TYPE (field)))
1215     TYPE_TYPELESS_STORAGE (rli->t) = 1;
1216 
1217   /* We assume the union's size will be a multiple of a byte so we don't
1218      bother with BITPOS.  */
1219   if (TREE_CODE (rli->t) == UNION_TYPE)
1220     rli->offset = size_binop (MAX_EXPR, rli->offset, DECL_SIZE_UNIT (field));
1221   else if (TREE_CODE (rli->t) == QUAL_UNION_TYPE)
1222     rli->offset = fold_build3 (COND_EXPR, sizetype, DECL_QUALIFIER (field),
1223 			       DECL_SIZE_UNIT (field), rli->offset);
1224 }
1225 
1226 /* A bitfield of SIZE with a required access alignment of ALIGN is allocated
1227    at BYTE_OFFSET / BIT_OFFSET.  Return nonzero if the field would span more
1228    units of alignment than the underlying TYPE.  */
1229 static int
excess_unit_span(HOST_WIDE_INT byte_offset,HOST_WIDE_INT bit_offset,HOST_WIDE_INT size,HOST_WIDE_INT align,tree type)1230 excess_unit_span (HOST_WIDE_INT byte_offset, HOST_WIDE_INT bit_offset,
1231 		  HOST_WIDE_INT size, HOST_WIDE_INT align, tree type)
1232 {
1233   /* Note that the calculation of OFFSET might overflow; we calculate it so
1234      that we still get the right result as long as ALIGN is a power of two.  */
1235   unsigned HOST_WIDE_INT offset = byte_offset * BITS_PER_UNIT + bit_offset;
1236 
1237   offset = offset % align;
1238   return ((offset + size + align - 1) / align
1239 	  > tree_to_uhwi (TYPE_SIZE (type)) / align);
1240 }
1241 
1242 /* RLI contains information about the layout of a RECORD_TYPE.  FIELD
1243    is a FIELD_DECL to be added after those fields already present in
1244    T.  (FIELD is not actually added to the TYPE_FIELDS list here;
1245    callers that desire that behavior must manually perform that step.)  */
1246 
1247 void
place_field(record_layout_info rli,tree field)1248 place_field (record_layout_info rli, tree field)
1249 {
1250   /* The alignment required for FIELD.  */
1251   unsigned int desired_align;
1252   /* The alignment FIELD would have if we just dropped it into the
1253      record as it presently stands.  */
1254   unsigned int known_align;
1255   unsigned int actual_align;
1256   /* The type of this field.  */
1257   tree type = TREE_TYPE (field);
1258 
1259   gcc_assert (TREE_CODE (field) != ERROR_MARK);
1260 
1261   /* If FIELD is static, then treat it like a separate variable, not
1262      really like a structure field.  If it is a FUNCTION_DECL, it's a
1263      method.  In both cases, all we do is lay out the decl, and we do
1264      it *after* the record is laid out.  */
1265   if (VAR_P (field))
1266     {
1267       vec_safe_push (rli->pending_statics, field);
1268       return;
1269     }
1270 
1271   /* Enumerators and enum types which are local to this class need not
1272      be laid out.  Likewise for initialized constant fields.  */
1273   else if (TREE_CODE (field) != FIELD_DECL)
1274     return;
1275 
1276   /* Unions are laid out very differently than records, so split
1277      that code off to another function.  */
1278   else if (TREE_CODE (rli->t) != RECORD_TYPE)
1279     {
1280       place_union_field (rli, field);
1281       return;
1282     }
1283 
1284   else if (TREE_CODE (type) == ERROR_MARK)
1285     {
1286       /* Place this field at the current allocation position, so we
1287 	 maintain monotonicity.  */
1288       DECL_FIELD_OFFSET (field) = rli->offset;
1289       DECL_FIELD_BIT_OFFSET (field) = rli->bitpos;
1290       SET_DECL_OFFSET_ALIGN (field, rli->offset_align);
1291       handle_warn_if_not_align (field, rli->record_align);
1292       return;
1293     }
1294 
1295   if (AGGREGATE_TYPE_P (type)
1296       && TYPE_TYPELESS_STORAGE (type))
1297     TYPE_TYPELESS_STORAGE (rli->t) = 1;
1298 
1299   /* Work out the known alignment so far.  Note that A & (-A) is the
1300      value of the least-significant bit in A that is one.  */
1301   if (! integer_zerop (rli->bitpos))
1302     known_align = least_bit_hwi (tree_to_uhwi (rli->bitpos));
1303   else if (integer_zerop (rli->offset))
1304     known_align = 0;
1305   else if (tree_fits_uhwi_p (rli->offset))
1306     known_align = (BITS_PER_UNIT
1307 		   * least_bit_hwi (tree_to_uhwi (rli->offset)));
1308   else
1309     known_align = rli->offset_align;
1310 
1311   desired_align = update_alignment_for_field (rli, field, known_align);
1312   if (known_align == 0)
1313     known_align = MAX (BIGGEST_ALIGNMENT, rli->record_align);
1314 
1315   if (warn_packed && DECL_PACKED (field))
1316     {
1317       if (known_align >= TYPE_ALIGN (type))
1318 	{
1319 	  if (TYPE_ALIGN (type) > desired_align)
1320 	    {
1321 	      if (STRICT_ALIGNMENT)
1322 		warning (OPT_Wattributes, "packed attribute causes "
1323                          "inefficient alignment for %q+D", field);
1324 	      /* Don't warn if DECL_PACKED was set by the type.  */
1325 	      else if (!TYPE_PACKED (rli->t))
1326 		warning (OPT_Wattributes, "packed attribute is "
1327 			 "unnecessary for %q+D", field);
1328 	    }
1329 	}
1330       else
1331 	rli->packed_maybe_necessary = 1;
1332     }
1333 
1334   /* Does this field automatically have alignment it needs by virtue
1335      of the fields that precede it and the record's own alignment?  */
1336   if (known_align < desired_align
1337       && (! targetm.ms_bitfield_layout_p (rli->t)
1338 	  || rli->prev_field == NULL))
1339     {
1340       /* No, we need to skip space before this field.
1341 	 Bump the cumulative size to multiple of field alignment.  */
1342 
1343       if (!targetm.ms_bitfield_layout_p (rli->t)
1344 	  && DECL_SOURCE_LOCATION (field) != BUILTINS_LOCATION
1345 	  && !TYPE_ARTIFICIAL (rli->t))
1346 	warning (OPT_Wpadded, "padding struct to align %q+D", field);
1347 
1348       /* If the alignment is still within offset_align, just align
1349 	 the bit position.  */
1350       if (desired_align < rli->offset_align)
1351 	rli->bitpos = round_up (rli->bitpos, desired_align);
1352       else
1353 	{
1354 	  /* First adjust OFFSET by the partial bits, then align.  */
1355 	  rli->offset
1356 	    = size_binop (PLUS_EXPR, rli->offset,
1357 			  fold_convert (sizetype,
1358 					size_binop (CEIL_DIV_EXPR, rli->bitpos,
1359 						    bitsize_unit_node)));
1360 	  rli->bitpos = bitsize_zero_node;
1361 
1362 	  rli->offset = round_up (rli->offset, desired_align / BITS_PER_UNIT);
1363 	}
1364 
1365       if (! TREE_CONSTANT (rli->offset))
1366 	rli->offset_align = desired_align;
1367     }
1368 
1369   /* Handle compatibility with PCC.  Note that if the record has any
1370      variable-sized fields, we need not worry about compatibility.  */
1371   if (PCC_BITFIELD_TYPE_MATTERS
1372       && ! targetm.ms_bitfield_layout_p (rli->t)
1373       && TREE_CODE (field) == FIELD_DECL
1374       && type != error_mark_node
1375       && DECL_BIT_FIELD (field)
1376       && (! DECL_PACKED (field)
1377 	  /* Enter for these packed fields only to issue a warning.  */
1378 	  || TYPE_ALIGN (type) <= BITS_PER_UNIT)
1379       && maximum_field_alignment == 0
1380       && ! integer_zerop (DECL_SIZE (field))
1381       && tree_fits_uhwi_p (DECL_SIZE (field))
1382       && tree_fits_uhwi_p (rli->offset)
1383       && tree_fits_uhwi_p (TYPE_SIZE (type)))
1384     {
1385       unsigned int type_align = TYPE_ALIGN (type);
1386       tree dsize = DECL_SIZE (field);
1387       HOST_WIDE_INT field_size = tree_to_uhwi (dsize);
1388       HOST_WIDE_INT offset = tree_to_uhwi (rli->offset);
1389       HOST_WIDE_INT bit_offset = tree_to_shwi (rli->bitpos);
1390 
1391 #ifdef ADJUST_FIELD_ALIGN
1392       if (! TYPE_USER_ALIGN (type))
1393 	type_align = ADJUST_FIELD_ALIGN (field, type, type_align);
1394 #endif
1395 
1396       /* A bit field may not span more units of alignment of its type
1397 	 than its type itself.  Advance to next boundary if necessary.  */
1398       if (excess_unit_span (offset, bit_offset, field_size, type_align, type))
1399 	{
1400 	  if (DECL_PACKED (field))
1401 	    {
1402 	      if (warn_packed_bitfield_compat == 1)
1403 		inform
1404 		  (input_location,
1405 		   "offset of packed bit-field %qD has changed in GCC 4.4",
1406 		   field);
1407 	    }
1408 	  else
1409 	    rli->bitpos = round_up (rli->bitpos, type_align);
1410 	}
1411 
1412       if (! DECL_PACKED (field))
1413 	TYPE_USER_ALIGN (rli->t) |= TYPE_USER_ALIGN (type);
1414 
1415       SET_TYPE_WARN_IF_NOT_ALIGN (rli->t,
1416 				  TYPE_WARN_IF_NOT_ALIGN (type));
1417     }
1418 
1419 #ifdef BITFIELD_NBYTES_LIMITED
1420   if (BITFIELD_NBYTES_LIMITED
1421       && ! targetm.ms_bitfield_layout_p (rli->t)
1422       && TREE_CODE (field) == FIELD_DECL
1423       && type != error_mark_node
1424       && DECL_BIT_FIELD_TYPE (field)
1425       && ! DECL_PACKED (field)
1426       && ! integer_zerop (DECL_SIZE (field))
1427       && tree_fits_uhwi_p (DECL_SIZE (field))
1428       && tree_fits_uhwi_p (rli->offset)
1429       && tree_fits_uhwi_p (TYPE_SIZE (type)))
1430     {
1431       unsigned int type_align = TYPE_ALIGN (type);
1432       tree dsize = DECL_SIZE (field);
1433       HOST_WIDE_INT field_size = tree_to_uhwi (dsize);
1434       HOST_WIDE_INT offset = tree_to_uhwi (rli->offset);
1435       HOST_WIDE_INT bit_offset = tree_to_shwi (rli->bitpos);
1436 
1437 #ifdef ADJUST_FIELD_ALIGN
1438       if (! TYPE_USER_ALIGN (type))
1439 	type_align = ADJUST_FIELD_ALIGN (field, type, type_align);
1440 #endif
1441 
1442       if (maximum_field_alignment != 0)
1443 	type_align = MIN (type_align, maximum_field_alignment);
1444       /* ??? This test is opposite the test in the containing if
1445 	 statement, so this code is unreachable currently.  */
1446       else if (DECL_PACKED (field))
1447 	type_align = MIN (type_align, BITS_PER_UNIT);
1448 
1449       /* A bit field may not span the unit of alignment of its type.
1450 	 Advance to next boundary if necessary.  */
1451       if (excess_unit_span (offset, bit_offset, field_size, type_align, type))
1452 	rli->bitpos = round_up (rli->bitpos, type_align);
1453 
1454       TYPE_USER_ALIGN (rli->t) |= TYPE_USER_ALIGN (type);
1455       SET_TYPE_WARN_IF_NOT_ALIGN (rli->t,
1456 				  TYPE_WARN_IF_NOT_ALIGN (type));
1457     }
1458 #endif
1459 
1460   /* See the docs for TARGET_MS_BITFIELD_LAYOUT_P for details.
1461      A subtlety:
1462 	When a bit field is inserted into a packed record, the whole
1463 	size of the underlying type is used by one or more same-size
1464 	adjacent bitfields.  (That is, if its long:3, 32 bits is
1465 	used in the record, and any additional adjacent long bitfields are
1466 	packed into the same chunk of 32 bits. However, if the size
1467 	changes, a new field of that size is allocated.)  In an unpacked
1468 	record, this is the same as using alignment, but not equivalent
1469 	when packing.
1470 
1471      Note: for compatibility, we use the type size, not the type alignment
1472      to determine alignment, since that matches the documentation */
1473 
1474   if (targetm.ms_bitfield_layout_p (rli->t))
1475     {
1476       tree prev_saved = rli->prev_field;
1477       tree prev_type = prev_saved ? DECL_BIT_FIELD_TYPE (prev_saved) : NULL;
1478 
1479       /* This is a bitfield if it exists.  */
1480       if (rli->prev_field)
1481 	{
1482 	  bool realign_p = known_align < desired_align;
1483 
1484 	  /* If both are bitfields, nonzero, and the same size, this is
1485 	     the middle of a run.  Zero declared size fields are special
1486 	     and handled as "end of run". (Note: it's nonzero declared
1487 	     size, but equal type sizes!) (Since we know that both
1488 	     the current and previous fields are bitfields by the
1489 	     time we check it, DECL_SIZE must be present for both.) */
1490 	  if (DECL_BIT_FIELD_TYPE (field)
1491 	      && !integer_zerop (DECL_SIZE (field))
1492 	      && !integer_zerop (DECL_SIZE (rli->prev_field))
1493 	      && tree_fits_shwi_p (DECL_SIZE (rli->prev_field))
1494 	      && tree_fits_uhwi_p (TYPE_SIZE (type))
1495 	      && simple_cst_equal (TYPE_SIZE (type), TYPE_SIZE (prev_type)))
1496 	    {
1497 	      /* We're in the middle of a run of equal type size fields; make
1498 		 sure we realign if we run out of bits.  (Not decl size,
1499 		 type size!) */
1500 	      HOST_WIDE_INT bitsize = tree_to_uhwi (DECL_SIZE (field));
1501 
1502 	      if (rli->remaining_in_alignment < bitsize)
1503 		{
1504 		  HOST_WIDE_INT typesize = tree_to_uhwi (TYPE_SIZE (type));
1505 
1506 		  /* out of bits; bump up to next 'word'.  */
1507 		  rli->bitpos
1508 		    = size_binop (PLUS_EXPR, rli->bitpos,
1509 				  bitsize_int (rli->remaining_in_alignment));
1510 		  rli->prev_field = field;
1511 		  if (typesize < bitsize)
1512 		    rli->remaining_in_alignment = 0;
1513 		  else
1514 		    rli->remaining_in_alignment = typesize - bitsize;
1515 		}
1516 	      else
1517 		{
1518 		  rli->remaining_in_alignment -= bitsize;
1519 		  realign_p = false;
1520 		}
1521 	    }
1522 	  else
1523 	    {
1524 	      /* End of a run: if leaving a run of bitfields of the same type
1525 		 size, we have to "use up" the rest of the bits of the type
1526 		 size.
1527 
1528 		 Compute the new position as the sum of the size for the prior
1529 		 type and where we first started working on that type.
1530 		 Note: since the beginning of the field was aligned then
1531 		 of course the end will be too.  No round needed.  */
1532 
1533 	      if (!integer_zerop (DECL_SIZE (rli->prev_field)))
1534 		{
1535 		  rli->bitpos
1536 		    = size_binop (PLUS_EXPR, rli->bitpos,
1537 				  bitsize_int (rli->remaining_in_alignment));
1538 		}
1539 	      else
1540 		/* We "use up" size zero fields; the code below should behave
1541 		   as if the prior field was not a bitfield.  */
1542 		prev_saved = NULL;
1543 
1544 	      /* Cause a new bitfield to be captured, either this time (if
1545 		 currently a bitfield) or next time we see one.  */
1546 	      if (!DECL_BIT_FIELD_TYPE (field)
1547 		  || integer_zerop (DECL_SIZE (field)))
1548 		rli->prev_field = NULL;
1549 	    }
1550 
1551 	  /* Does this field automatically have alignment it needs by virtue
1552 	     of the fields that precede it and the record's own alignment?  */
1553 	  if (realign_p)
1554 	    {
1555 	      /* If the alignment is still within offset_align, just align
1556 		 the bit position.  */
1557 	      if (desired_align < rli->offset_align)
1558 		rli->bitpos = round_up (rli->bitpos, desired_align);
1559 	      else
1560 		{
1561 		  /* First adjust OFFSET by the partial bits, then align.  */
1562 		  tree d = size_binop (CEIL_DIV_EXPR, rli->bitpos,
1563 				       bitsize_unit_node);
1564 		  rli->offset = size_binop (PLUS_EXPR, rli->offset,
1565 					    fold_convert (sizetype, d));
1566 		  rli->bitpos = bitsize_zero_node;
1567 
1568 		  rli->offset = round_up (rli->offset,
1569 					  desired_align / BITS_PER_UNIT);
1570 		}
1571 
1572 	      if (! TREE_CONSTANT (rli->offset))
1573 		rli->offset_align = desired_align;
1574 	    }
1575 
1576 	  normalize_rli (rli);
1577         }
1578 
1579       /* If we're starting a new run of same type size bitfields
1580 	 (or a run of non-bitfields), set up the "first of the run"
1581 	 fields.
1582 
1583 	 That is, if the current field is not a bitfield, or if there
1584 	 was a prior bitfield the type sizes differ, or if there wasn't
1585 	 a prior bitfield the size of the current field is nonzero.
1586 
1587 	 Note: we must be sure to test ONLY the type size if there was
1588 	 a prior bitfield and ONLY for the current field being zero if
1589 	 there wasn't.  */
1590 
1591       if (!DECL_BIT_FIELD_TYPE (field)
1592 	  || (prev_saved != NULL
1593 	      ? !simple_cst_equal (TYPE_SIZE (type), TYPE_SIZE (prev_type))
1594 	      : !integer_zerop (DECL_SIZE (field))))
1595 	{
1596 	  /* Never smaller than a byte for compatibility.  */
1597 	  unsigned int type_align = BITS_PER_UNIT;
1598 
1599 	  /* (When not a bitfield), we could be seeing a flex array (with
1600 	     no DECL_SIZE).  Since we won't be using remaining_in_alignment
1601 	     until we see a bitfield (and come by here again) we just skip
1602 	     calculating it.  */
1603 	  if (DECL_SIZE (field) != NULL
1604 	      && tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (field)))
1605 	      && tree_fits_uhwi_p (DECL_SIZE (field)))
1606 	    {
1607 	      unsigned HOST_WIDE_INT bitsize
1608 		= tree_to_uhwi (DECL_SIZE (field));
1609 	      unsigned HOST_WIDE_INT typesize
1610 		= tree_to_uhwi (TYPE_SIZE (TREE_TYPE (field)));
1611 
1612 	      if (typesize < bitsize)
1613 		rli->remaining_in_alignment = 0;
1614 	      else
1615 		rli->remaining_in_alignment = typesize - bitsize;
1616 	    }
1617 
1618 	  /* Now align (conventionally) for the new type.  */
1619 	  if (! DECL_PACKED (field))
1620 	    type_align = TYPE_ALIGN (TREE_TYPE (field));
1621 
1622 	  if (maximum_field_alignment != 0)
1623 	    type_align = MIN (type_align, maximum_field_alignment);
1624 
1625 	  rli->bitpos = round_up (rli->bitpos, type_align);
1626 
1627           /* If we really aligned, don't allow subsequent bitfields
1628 	     to undo that.  */
1629 	  rli->prev_field = NULL;
1630 	}
1631     }
1632 
1633   /* Offset so far becomes the position of this field after normalizing.  */
1634   normalize_rli (rli);
1635   DECL_FIELD_OFFSET (field) = rli->offset;
1636   DECL_FIELD_BIT_OFFSET (field) = rli->bitpos;
1637   SET_DECL_OFFSET_ALIGN (field, rli->offset_align);
1638   handle_warn_if_not_align (field, rli->record_align);
1639 
1640   /* Evaluate nonconstant offsets only once, either now or as soon as safe.  */
1641   if (TREE_CODE (DECL_FIELD_OFFSET (field)) != INTEGER_CST)
1642     DECL_FIELD_OFFSET (field) = variable_size (DECL_FIELD_OFFSET (field));
1643 
1644   /* If this field ended up more aligned than we thought it would be (we
1645      approximate this by seeing if its position changed), lay out the field
1646      again; perhaps we can use an integral mode for it now.  */
1647   if (! integer_zerop (DECL_FIELD_BIT_OFFSET (field)))
1648     actual_align = least_bit_hwi (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field)));
1649   else if (integer_zerop (DECL_FIELD_OFFSET (field)))
1650     actual_align = MAX (BIGGEST_ALIGNMENT, rli->record_align);
1651   else if (tree_fits_uhwi_p (DECL_FIELD_OFFSET (field)))
1652     actual_align = (BITS_PER_UNIT
1653 		    * least_bit_hwi (tree_to_uhwi (DECL_FIELD_OFFSET (field))));
1654   else
1655     actual_align = DECL_OFFSET_ALIGN (field);
1656   /* ACTUAL_ALIGN is still the actual alignment *within the record* .
1657      store / extract bit field operations will check the alignment of the
1658      record against the mode of bit fields.  */
1659 
1660   if (known_align != actual_align)
1661     layout_decl (field, actual_align);
1662 
1663   if (rli->prev_field == NULL && DECL_BIT_FIELD_TYPE (field))
1664     rli->prev_field = field;
1665 
1666   /* Now add size of this field to the size of the record.  If the size is
1667      not constant, treat the field as being a multiple of bytes and just
1668      adjust the offset, resetting the bit position.  Otherwise, apportion the
1669      size amongst the bit position and offset.  First handle the case of an
1670      unspecified size, which can happen when we have an invalid nested struct
1671      definition, such as struct j { struct j { int i; } }.  The error message
1672      is printed in finish_struct.  */
1673   if (DECL_SIZE (field) == 0)
1674     /* Do nothing.  */;
1675   else if (TREE_CODE (DECL_SIZE (field)) != INTEGER_CST
1676 	   || TREE_OVERFLOW (DECL_SIZE (field)))
1677     {
1678       rli->offset
1679 	= size_binop (PLUS_EXPR, rli->offset,
1680 		      fold_convert (sizetype,
1681 				    size_binop (CEIL_DIV_EXPR, rli->bitpos,
1682 						bitsize_unit_node)));
1683       rli->offset
1684 	= size_binop (PLUS_EXPR, rli->offset, DECL_SIZE_UNIT (field));
1685       rli->bitpos = bitsize_zero_node;
1686       rli->offset_align = MIN (rli->offset_align, desired_align);
1687 
1688       if (!multiple_of_p (bitsizetype, DECL_SIZE (field),
1689 			  bitsize_int (rli->offset_align)))
1690 	{
1691 	  tree type = strip_array_types (TREE_TYPE (field));
1692 	  /* The above adjusts offset_align just based on the start of the
1693 	     field.  The field might not have a size that is a multiple of
1694 	     that offset_align though.  If the field is an array of fixed
1695 	     sized elements, assume there can be any multiple of those
1696 	     sizes.  If it is a variable length aggregate or array of
1697 	     variable length aggregates, assume worst that the end is
1698 	     just BITS_PER_UNIT aligned.  */
1699 	  if (TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST)
1700 	    {
1701 	      if (TREE_INT_CST_LOW (TYPE_SIZE (type)))
1702 		{
1703 		  unsigned HOST_WIDE_INT sz
1704 		    = least_bit_hwi (TREE_INT_CST_LOW (TYPE_SIZE (type)));
1705 		  rli->offset_align = MIN (rli->offset_align, sz);
1706 		}
1707 	    }
1708 	  else
1709 	    rli->offset_align = MIN (rli->offset_align, BITS_PER_UNIT);
1710 	}
1711     }
1712   else if (targetm.ms_bitfield_layout_p (rli->t))
1713     {
1714       rli->bitpos = size_binop (PLUS_EXPR, rli->bitpos, DECL_SIZE (field));
1715 
1716       /* If FIELD is the last field and doesn't end at the full length
1717 	 of the type then pad the struct out to the full length of the
1718 	 last type.  */
1719       if (DECL_BIT_FIELD_TYPE (field)
1720 	  && !integer_zerop (DECL_SIZE (field)))
1721 	{
1722 	  /* We have to scan, because non-field DECLS are also here.  */
1723 	  tree probe = field;
1724 	  while ((probe = DECL_CHAIN (probe)))
1725 	    if (TREE_CODE (probe) == FIELD_DECL)
1726 	      break;
1727 	  if (!probe)
1728 	    rli->bitpos = size_binop (PLUS_EXPR, rli->bitpos,
1729 				      bitsize_int (rli->remaining_in_alignment));
1730 	}
1731 
1732       normalize_rli (rli);
1733     }
1734   else
1735     {
1736       rli->bitpos = size_binop (PLUS_EXPR, rli->bitpos, DECL_SIZE (field));
1737       normalize_rli (rli);
1738     }
1739 }
1740 
1741 /* Assuming that all the fields have been laid out, this function uses
1742    RLI to compute the final TYPE_SIZE, TYPE_ALIGN, etc. for the type
1743    indicated by RLI.  */
1744 
1745 static void
finalize_record_size(record_layout_info rli)1746 finalize_record_size (record_layout_info rli)
1747 {
1748   tree unpadded_size, unpadded_size_unit;
1749 
1750   /* Now we want just byte and bit offsets, so set the offset alignment
1751      to be a byte and then normalize.  */
1752   rli->offset_align = BITS_PER_UNIT;
1753   normalize_rli (rli);
1754 
1755   /* Determine the desired alignment.  */
1756 #ifdef ROUND_TYPE_ALIGN
1757   SET_TYPE_ALIGN (rli->t, ROUND_TYPE_ALIGN (rli->t, TYPE_ALIGN (rli->t),
1758 					    rli->record_align));
1759 #else
1760   SET_TYPE_ALIGN (rli->t, MAX (TYPE_ALIGN (rli->t), rli->record_align));
1761 #endif
1762 
1763   /* Compute the size so far.  Be sure to allow for extra bits in the
1764      size in bytes.  We have guaranteed above that it will be no more
1765      than a single byte.  */
1766   unpadded_size = rli_size_so_far (rli);
1767   unpadded_size_unit = rli_size_unit_so_far (rli);
1768   if (! integer_zerop (rli->bitpos))
1769     unpadded_size_unit
1770       = size_binop (PLUS_EXPR, unpadded_size_unit, size_one_node);
1771 
1772   /* Round the size up to be a multiple of the required alignment.  */
1773   TYPE_SIZE (rli->t) = round_up (unpadded_size, TYPE_ALIGN (rli->t));
1774   TYPE_SIZE_UNIT (rli->t)
1775     = round_up (unpadded_size_unit, TYPE_ALIGN_UNIT (rli->t));
1776 
1777   if (TREE_CONSTANT (unpadded_size)
1778       && simple_cst_equal (unpadded_size, TYPE_SIZE (rli->t)) == 0
1779       && input_location != BUILTINS_LOCATION
1780       && !TYPE_ARTIFICIAL (rli->t))
1781     warning (OPT_Wpadded, "padding struct size to alignment boundary");
1782 
1783   if (warn_packed && TREE_CODE (rli->t) == RECORD_TYPE
1784       && TYPE_PACKED (rli->t) && ! rli->packed_maybe_necessary
1785       && TREE_CONSTANT (unpadded_size))
1786     {
1787       tree unpacked_size;
1788 
1789 #ifdef ROUND_TYPE_ALIGN
1790       rli->unpacked_align
1791 	= ROUND_TYPE_ALIGN (rli->t, TYPE_ALIGN (rli->t), rli->unpacked_align);
1792 #else
1793       rli->unpacked_align = MAX (TYPE_ALIGN (rli->t), rli->unpacked_align);
1794 #endif
1795 
1796       unpacked_size = round_up (TYPE_SIZE (rli->t), rli->unpacked_align);
1797       if (simple_cst_equal (unpacked_size, TYPE_SIZE (rli->t)))
1798 	{
1799 	  if (TYPE_NAME (rli->t))
1800 	    {
1801 	      tree name;
1802 
1803 	      if (TREE_CODE (TYPE_NAME (rli->t)) == IDENTIFIER_NODE)
1804 		name = TYPE_NAME (rli->t);
1805 	      else
1806 		name = DECL_NAME (TYPE_NAME (rli->t));
1807 
1808 	      if (STRICT_ALIGNMENT)
1809 		warning (OPT_Wpacked, "packed attribute causes inefficient "
1810 			 "alignment for %qE", name);
1811 	      else
1812 		warning (OPT_Wpacked,
1813 			 "packed attribute is unnecessary for %qE", name);
1814 	    }
1815 	  else
1816 	    {
1817 	      if (STRICT_ALIGNMENT)
1818 		warning (OPT_Wpacked,
1819 			 "packed attribute causes inefficient alignment");
1820 	      else
1821 		warning (OPT_Wpacked, "packed attribute is unnecessary");
1822 	    }
1823 	}
1824     }
1825 }
1826 
1827 /* Compute the TYPE_MODE for the TYPE (which is a RECORD_TYPE).  */
1828 
1829 void
compute_record_mode(tree type)1830 compute_record_mode (tree type)
1831 {
1832   tree field;
1833   machine_mode mode = VOIDmode;
1834 
1835   /* Most RECORD_TYPEs have BLKmode, so we start off assuming that.
1836      However, if possible, we use a mode that fits in a register
1837      instead, in order to allow for better optimization down the
1838      line.  */
1839   SET_TYPE_MODE (type, BLKmode);
1840 
1841   poly_uint64 type_size;
1842   if (!poly_int_tree_p (TYPE_SIZE (type), &type_size))
1843     return;
1844 
1845   /* A record which has any BLKmode members must itself be
1846      BLKmode; it can't go in a register.  Unless the member is
1847      BLKmode only because it isn't aligned.  */
1848   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1849     {
1850       if (TREE_CODE (field) != FIELD_DECL)
1851 	continue;
1852 
1853       poly_uint64 field_size;
1854       if (TREE_CODE (TREE_TYPE (field)) == ERROR_MARK
1855 	  || (TYPE_MODE (TREE_TYPE (field)) == BLKmode
1856 	      && ! TYPE_NO_FORCE_BLK (TREE_TYPE (field))
1857 	      && !(TYPE_SIZE (TREE_TYPE (field)) != 0
1858 		   && integer_zerop (TYPE_SIZE (TREE_TYPE (field)))))
1859 	  || !tree_fits_poly_uint64_p (bit_position (field))
1860 	  || DECL_SIZE (field) == 0
1861 	  || !poly_int_tree_p (DECL_SIZE (field), &field_size))
1862 	return;
1863 
1864       /* If this field is the whole struct, remember its mode so
1865 	 that, say, we can put a double in a class into a DF
1866 	 register instead of forcing it to live in the stack.  */
1867       if (known_eq (field_size, type_size)
1868 	  /* Partial int types (e.g. __int20) may have TYPE_SIZE equal to
1869 	     wider types (e.g. int32), despite precision being less.  Ensure
1870 	     that the TYPE_MODE of the struct does not get set to the partial
1871 	     int mode if there is a wider type also in the struct.  */
1872 	  && known_gt (GET_MODE_PRECISION (DECL_MODE (field)),
1873 		       GET_MODE_PRECISION (mode)))
1874 	mode = DECL_MODE (field);
1875 
1876       /* With some targets, it is sub-optimal to access an aligned
1877 	 BLKmode structure as a scalar.  */
1878       if (targetm.member_type_forces_blk (field, mode))
1879 	return;
1880     }
1881 
1882   /* If we only have one real field; use its mode if that mode's size
1883      matches the type's size.  This generally only applies to RECORD_TYPE.
1884      For UNION_TYPE, if the widest field is MODE_INT then use that mode.
1885      If the widest field is MODE_PARTIAL_INT, and the union will be passed
1886      by reference, then use that mode.  */
1887   if ((TREE_CODE (type) == RECORD_TYPE
1888        || (TREE_CODE (type) == UNION_TYPE
1889 	   && (GET_MODE_CLASS (mode) == MODE_INT
1890 	       || (GET_MODE_CLASS (mode) == MODE_PARTIAL_INT
1891 		   && (targetm.calls.pass_by_reference
1892 		       (pack_cumulative_args (0),
1893 			function_arg_info (type, mode, /*named=*/false)))))))
1894       && mode != VOIDmode
1895       && known_eq (GET_MODE_BITSIZE (mode), type_size))
1896     ;
1897   else
1898     mode = mode_for_size_tree (TYPE_SIZE (type), MODE_INT, 1).else_blk ();
1899 
1900   /* If structure's known alignment is less than what the scalar
1901      mode would need, and it matters, then stick with BLKmode.  */
1902   if (mode != BLKmode
1903       && STRICT_ALIGNMENT
1904       && ! (TYPE_ALIGN (type) >= BIGGEST_ALIGNMENT
1905 	    || TYPE_ALIGN (type) >= GET_MODE_ALIGNMENT (mode)))
1906     {
1907       /* If this is the only reason this type is BLKmode, then
1908 	 don't force containing types to be BLKmode.  */
1909       TYPE_NO_FORCE_BLK (type) = 1;
1910       mode = BLKmode;
1911     }
1912 
1913   SET_TYPE_MODE (type, mode);
1914 }
1915 
1916 /* Compute TYPE_SIZE and TYPE_ALIGN for TYPE, once it has been laid
1917    out.  */
1918 
1919 static void
finalize_type_size(tree type)1920 finalize_type_size (tree type)
1921 {
1922   /* Normally, use the alignment corresponding to the mode chosen.
1923      However, where strict alignment is not required, avoid
1924      over-aligning structures, since most compilers do not do this
1925      alignment.  */
1926   if (TYPE_MODE (type) != BLKmode
1927       && TYPE_MODE (type) != VOIDmode
1928       && (STRICT_ALIGNMENT || !AGGREGATE_TYPE_P (type)))
1929     {
1930       unsigned mode_align = GET_MODE_ALIGNMENT (TYPE_MODE (type));
1931 
1932       /* Don't override a larger alignment requirement coming from a user
1933 	 alignment of one of the fields.  */
1934       if (mode_align >= TYPE_ALIGN (type))
1935 	{
1936 	  SET_TYPE_ALIGN (type, mode_align);
1937 	  TYPE_USER_ALIGN (type) = 0;
1938 	}
1939     }
1940 
1941   /* Do machine-dependent extra alignment.  */
1942 #ifdef ROUND_TYPE_ALIGN
1943   SET_TYPE_ALIGN (type,
1944                   ROUND_TYPE_ALIGN (type, TYPE_ALIGN (type), BITS_PER_UNIT));
1945 #endif
1946 
1947   /* If we failed to find a simple way to calculate the unit size
1948      of the type, find it by division.  */
1949   if (TYPE_SIZE_UNIT (type) == 0 && TYPE_SIZE (type) != 0)
1950     /* TYPE_SIZE (type) is computed in bitsizetype.  After the division, the
1951        result will fit in sizetype.  We will get more efficient code using
1952        sizetype, so we force a conversion.  */
1953     TYPE_SIZE_UNIT (type)
1954       = fold_convert (sizetype,
1955 		      size_binop (FLOOR_DIV_EXPR, TYPE_SIZE (type),
1956 				  bitsize_unit_node));
1957 
1958   if (TYPE_SIZE (type) != 0)
1959     {
1960       TYPE_SIZE (type) = round_up (TYPE_SIZE (type), TYPE_ALIGN (type));
1961       TYPE_SIZE_UNIT (type)
1962 	= round_up (TYPE_SIZE_UNIT (type), TYPE_ALIGN_UNIT (type));
1963     }
1964 
1965   /* Evaluate nonconstant sizes only once, either now or as soon as safe.  */
1966   if (TYPE_SIZE (type) != 0 && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
1967     TYPE_SIZE (type) = variable_size (TYPE_SIZE (type));
1968   if (TYPE_SIZE_UNIT (type) != 0
1969       && TREE_CODE (TYPE_SIZE_UNIT (type)) != INTEGER_CST)
1970     TYPE_SIZE_UNIT (type) = variable_size (TYPE_SIZE_UNIT (type));
1971 
1972   /* Handle empty records as per the x86-64 psABI.  */
1973   TYPE_EMPTY_P (type) = targetm.calls.empty_record_p (type);
1974 
1975   /* Also layout any other variants of the type.  */
1976   if (TYPE_NEXT_VARIANT (type)
1977       || type != TYPE_MAIN_VARIANT (type))
1978     {
1979       tree variant;
1980       /* Record layout info of this variant.  */
1981       tree size = TYPE_SIZE (type);
1982       tree size_unit = TYPE_SIZE_UNIT (type);
1983       unsigned int align = TYPE_ALIGN (type);
1984       unsigned int precision = TYPE_PRECISION (type);
1985       unsigned int user_align = TYPE_USER_ALIGN (type);
1986       machine_mode mode = TYPE_MODE (type);
1987       bool empty_p = TYPE_EMPTY_P (type);
1988 
1989       /* Copy it into all variants.  */
1990       for (variant = TYPE_MAIN_VARIANT (type);
1991 	   variant != 0;
1992 	   variant = TYPE_NEXT_VARIANT (variant))
1993 	{
1994 	  TYPE_SIZE (variant) = size;
1995 	  TYPE_SIZE_UNIT (variant) = size_unit;
1996 	  unsigned valign = align;
1997 	  if (TYPE_USER_ALIGN (variant))
1998 	    valign = MAX (valign, TYPE_ALIGN (variant));
1999 	  else
2000 	    TYPE_USER_ALIGN (variant) = user_align;
2001 	  SET_TYPE_ALIGN (variant, valign);
2002 	  TYPE_PRECISION (variant) = precision;
2003 	  SET_TYPE_MODE (variant, mode);
2004 	  TYPE_EMPTY_P (variant) = empty_p;
2005 	}
2006     }
2007 }
2008 
2009 /* Return a new underlying object for a bitfield started with FIELD.  */
2010 
2011 static tree
start_bitfield_representative(tree field)2012 start_bitfield_representative (tree field)
2013 {
2014   tree repr = make_node (FIELD_DECL);
2015   DECL_FIELD_OFFSET (repr) = DECL_FIELD_OFFSET (field);
2016   /* Force the representative to begin at a BITS_PER_UNIT aligned
2017      boundary - C++ may use tail-padding of a base object to
2018      continue packing bits so the bitfield region does not start
2019      at bit zero (see g++.dg/abi/bitfield5.C for example).
2020      Unallocated bits may happen for other reasons as well,
2021      for example Ada which allows explicit bit-granular structure layout.  */
2022   DECL_FIELD_BIT_OFFSET (repr)
2023     = size_binop (BIT_AND_EXPR,
2024 		  DECL_FIELD_BIT_OFFSET (field),
2025 		  bitsize_int (~(BITS_PER_UNIT - 1)));
2026   SET_DECL_OFFSET_ALIGN (repr, DECL_OFFSET_ALIGN (field));
2027   DECL_SIZE (repr) = DECL_SIZE (field);
2028   DECL_SIZE_UNIT (repr) = DECL_SIZE_UNIT (field);
2029   DECL_PACKED (repr) = DECL_PACKED (field);
2030   DECL_CONTEXT (repr) = DECL_CONTEXT (field);
2031   /* There are no indirect accesses to this field.  If we introduce
2032      some then they have to use the record alias set.  This makes
2033      sure to properly conflict with [indirect] accesses to addressable
2034      fields of the bitfield group.  */
2035   DECL_NONADDRESSABLE_P (repr) = 1;
2036   return repr;
2037 }
2038 
2039 /* Finish up a bitfield group that was started by creating the underlying
2040    object REPR with the last field in the bitfield group FIELD.  */
2041 
2042 static void
finish_bitfield_representative(tree repr,tree field)2043 finish_bitfield_representative (tree repr, tree field)
2044 {
2045   unsigned HOST_WIDE_INT bitsize, maxbitsize;
2046   tree nextf, size;
2047 
2048   size = size_diffop (DECL_FIELD_OFFSET (field),
2049 		      DECL_FIELD_OFFSET (repr));
2050   while (TREE_CODE (size) == COMPOUND_EXPR)
2051     size = TREE_OPERAND (size, 1);
2052   gcc_assert (tree_fits_uhwi_p (size));
2053   bitsize = (tree_to_uhwi (size) * BITS_PER_UNIT
2054 	     + tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field))
2055 	     - tree_to_uhwi (DECL_FIELD_BIT_OFFSET (repr))
2056 	     + tree_to_uhwi (DECL_SIZE (field)));
2057 
2058   /* Round up bitsize to multiples of BITS_PER_UNIT.  */
2059   bitsize = (bitsize + BITS_PER_UNIT - 1) & ~(BITS_PER_UNIT - 1);
2060 
2061   /* Now nothing tells us how to pad out bitsize ...  */
2062   if (TREE_CODE (DECL_CONTEXT (field)) == RECORD_TYPE)
2063     {
2064       nextf = DECL_CHAIN (field);
2065       while (nextf && TREE_CODE (nextf) != FIELD_DECL)
2066 	nextf = DECL_CHAIN (nextf);
2067     }
2068   else
2069     nextf = NULL_TREE;
2070   if (nextf)
2071     {
2072       tree maxsize;
2073       /* If there was an error, the field may be not laid out
2074          correctly.  Don't bother to do anything.  */
2075       if (TREE_TYPE (nextf) == error_mark_node)
2076 	return;
2077       maxsize = size_diffop (DECL_FIELD_OFFSET (nextf),
2078 			     DECL_FIELD_OFFSET (repr));
2079       if (tree_fits_uhwi_p (maxsize))
2080 	{
2081 	  maxbitsize = (tree_to_uhwi (maxsize) * BITS_PER_UNIT
2082 			+ tree_to_uhwi (DECL_FIELD_BIT_OFFSET (nextf))
2083 			- tree_to_uhwi (DECL_FIELD_BIT_OFFSET (repr)));
2084 	  /* If the group ends within a bitfield nextf does not need to be
2085 	     aligned to BITS_PER_UNIT.  Thus round up.  */
2086 	  maxbitsize = (maxbitsize + BITS_PER_UNIT - 1) & ~(BITS_PER_UNIT - 1);
2087 	}
2088       else
2089 	maxbitsize = bitsize;
2090     }
2091   else
2092     {
2093       /* Note that if the C++ FE sets up tail-padding to be re-used it
2094          creates a as-base variant of the type with TYPE_SIZE adjusted
2095 	 accordingly.  So it is safe to include tail-padding here.  */
2096       tree aggsize = lang_hooks.types.unit_size_without_reusable_padding
2097 							(DECL_CONTEXT (field));
2098       tree maxsize = size_diffop (aggsize, DECL_FIELD_OFFSET (repr));
2099       /* We cannot generally rely on maxsize to fold to an integer constant,
2100 	 so use bitsize as fallback for this case.  */
2101       if (tree_fits_uhwi_p (maxsize))
2102 	maxbitsize = (tree_to_uhwi (maxsize) * BITS_PER_UNIT
2103 		      - tree_to_uhwi (DECL_FIELD_BIT_OFFSET (repr)));
2104       else
2105 	maxbitsize = bitsize;
2106     }
2107 
2108   /* Only if we don't artificially break up the representative in
2109      the middle of a large bitfield with different possibly
2110      overlapping representatives.  And all representatives start
2111      at byte offset.  */
2112   gcc_assert (maxbitsize % BITS_PER_UNIT == 0);
2113 
2114   /* Find the smallest nice mode to use.  */
2115   opt_scalar_int_mode mode_iter;
2116   FOR_EACH_MODE_IN_CLASS (mode_iter, MODE_INT)
2117     if (GET_MODE_BITSIZE (mode_iter.require ()) >= bitsize)
2118       break;
2119 
2120   scalar_int_mode mode;
2121   if (!mode_iter.exists (&mode)
2122       || GET_MODE_BITSIZE (mode) > maxbitsize
2123       || GET_MODE_BITSIZE (mode) > MAX_FIXED_MODE_SIZE)
2124     {
2125       /* We really want a BLKmode representative only as a last resort,
2126          considering the member b in
2127 	   struct { int a : 7; int b : 17; int c; } __attribute__((packed));
2128 	 Otherwise we simply want to split the representative up
2129 	 allowing for overlaps within the bitfield region as required for
2130 	   struct { int a : 7; int b : 7;
2131 		    int c : 10; int d; } __attribute__((packed));
2132 	 [0, 15] HImode for a and b, [8, 23] HImode for c.  */
2133       DECL_SIZE (repr) = bitsize_int (bitsize);
2134       DECL_SIZE_UNIT (repr) = size_int (bitsize / BITS_PER_UNIT);
2135       SET_DECL_MODE (repr, BLKmode);
2136       TREE_TYPE (repr) = build_array_type_nelts (unsigned_char_type_node,
2137 						 bitsize / BITS_PER_UNIT);
2138     }
2139   else
2140     {
2141       unsigned HOST_WIDE_INT modesize = GET_MODE_BITSIZE (mode);
2142       DECL_SIZE (repr) = bitsize_int (modesize);
2143       DECL_SIZE_UNIT (repr) = size_int (modesize / BITS_PER_UNIT);
2144       SET_DECL_MODE (repr, mode);
2145       TREE_TYPE (repr) = lang_hooks.types.type_for_mode (mode, 1);
2146     }
2147 
2148   /* Remember whether the bitfield group is at the end of the
2149      structure or not.  */
2150   DECL_CHAIN (repr) = nextf;
2151 }
2152 
2153 /* Compute and set FIELD_DECLs for the underlying objects we should
2154    use for bitfield access for the structure T.  */
2155 
2156 void
finish_bitfield_layout(tree t)2157 finish_bitfield_layout (tree t)
2158 {
2159   tree field, prev;
2160   tree repr = NULL_TREE;
2161 
2162   if (TREE_CODE (t) == QUAL_UNION_TYPE)
2163     return;
2164 
2165   for (prev = NULL_TREE, field = TYPE_FIELDS (t);
2166        field; field = DECL_CHAIN (field))
2167     {
2168       if (TREE_CODE (field) != FIELD_DECL)
2169 	continue;
2170 
2171       /* In the C++ memory model, consecutive bit fields in a structure are
2172 	 considered one memory location and updating a memory location
2173 	 may not store into adjacent memory locations.  */
2174       if (!repr
2175 	  && DECL_BIT_FIELD_TYPE (field))
2176 	{
2177 	  /* Start new representative.  */
2178 	  repr = start_bitfield_representative (field);
2179 	}
2180       else if (repr
2181 	       && ! DECL_BIT_FIELD_TYPE (field))
2182 	{
2183 	  /* Finish off new representative.  */
2184 	  finish_bitfield_representative (repr, prev);
2185 	  repr = NULL_TREE;
2186 	}
2187       else if (DECL_BIT_FIELD_TYPE (field))
2188 	{
2189 	  gcc_assert (repr != NULL_TREE);
2190 
2191 	  /* Zero-size bitfields finish off a representative and
2192 	     do not have a representative themselves.  This is
2193 	     required by the C++ memory model.  */
2194 	  if (integer_zerop (DECL_SIZE (field)))
2195 	    {
2196 	      finish_bitfield_representative (repr, prev);
2197 	      repr = NULL_TREE;
2198 	    }
2199 
2200 	  /* We assume that either DECL_FIELD_OFFSET of the representative
2201 	     and each bitfield member is a constant or they are equal.
2202 	     This is because we need to be able to compute the bit-offset
2203 	     of each field relative to the representative in get_bit_range
2204 	     during RTL expansion.
2205 	     If these constraints are not met, simply force a new
2206 	     representative to be generated.  That will at most
2207 	     generate worse code but still maintain correctness with
2208 	     respect to the C++ memory model.  */
2209 	  else if (!((tree_fits_uhwi_p (DECL_FIELD_OFFSET (repr))
2210 		      && tree_fits_uhwi_p (DECL_FIELD_OFFSET (field)))
2211 		     || operand_equal_p (DECL_FIELD_OFFSET (repr),
2212 					 DECL_FIELD_OFFSET (field), 0)))
2213 	    {
2214 	      finish_bitfield_representative (repr, prev);
2215 	      repr = start_bitfield_representative (field);
2216 	    }
2217 	}
2218       else
2219 	continue;
2220 
2221       if (repr)
2222 	DECL_BIT_FIELD_REPRESENTATIVE (field) = repr;
2223 
2224       if (TREE_CODE (t) == RECORD_TYPE)
2225 	prev = field;
2226       else if (repr)
2227 	{
2228 	  finish_bitfield_representative (repr, field);
2229 	  repr = NULL_TREE;
2230 	}
2231     }
2232 
2233   if (repr)
2234     finish_bitfield_representative (repr, prev);
2235 }
2236 
2237 /* Do all of the work required to layout the type indicated by RLI,
2238    once the fields have been laid out.  This function will call `free'
2239    for RLI, unless FREE_P is false.  Passing a value other than false
2240    for FREE_P is bad practice; this option only exists to support the
2241    G++ 3.2 ABI.  */
2242 
2243 void
finish_record_layout(record_layout_info rli,int free_p)2244 finish_record_layout (record_layout_info rli, int free_p)
2245 {
2246   tree variant;
2247 
2248   /* Compute the final size.  */
2249   finalize_record_size (rli);
2250 
2251   /* Compute the TYPE_MODE for the record.  */
2252   compute_record_mode (rli->t);
2253 
2254   /* Perform any last tweaks to the TYPE_SIZE, etc.  */
2255   finalize_type_size (rli->t);
2256 
2257   /* Compute bitfield representatives.  */
2258   finish_bitfield_layout (rli->t);
2259 
2260   /* Propagate TYPE_PACKED and TYPE_REVERSE_STORAGE_ORDER to variants.
2261      With C++ templates, it is too early to do this when the attribute
2262      is being parsed.  */
2263   for (variant = TYPE_NEXT_VARIANT (rli->t); variant;
2264        variant = TYPE_NEXT_VARIANT (variant))
2265     {
2266       TYPE_PACKED (variant) = TYPE_PACKED (rli->t);
2267       TYPE_REVERSE_STORAGE_ORDER (variant)
2268 	= TYPE_REVERSE_STORAGE_ORDER (rli->t);
2269     }
2270 
2271   /* Lay out any static members.  This is done now because their type
2272      may use the record's type.  */
2273   while (!vec_safe_is_empty (rli->pending_statics))
2274     layout_decl (rli->pending_statics->pop (), 0);
2275 
2276   /* Clean up.  */
2277   if (free_p)
2278     {
2279       vec_free (rli->pending_statics);
2280       free (rli);
2281     }
2282 }
2283 
2284 
2285 /* Finish processing a builtin RECORD_TYPE type TYPE.  It's name is
2286    NAME, its fields are chained in reverse on FIELDS.
2287 
2288    If ALIGN_TYPE is non-null, it is given the same alignment as
2289    ALIGN_TYPE.  */
2290 
2291 void
finish_builtin_struct(tree type,const char * name,tree fields,tree align_type)2292 finish_builtin_struct (tree type, const char *name, tree fields,
2293 		       tree align_type)
2294 {
2295   tree tail, next;
2296 
2297   for (tail = NULL_TREE; fields; tail = fields, fields = next)
2298     {
2299       DECL_FIELD_CONTEXT (fields) = type;
2300       next = DECL_CHAIN (fields);
2301       DECL_CHAIN (fields) = tail;
2302     }
2303   TYPE_FIELDS (type) = tail;
2304 
2305   if (align_type)
2306     {
2307       SET_TYPE_ALIGN (type, TYPE_ALIGN (align_type));
2308       TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (align_type);
2309       SET_TYPE_WARN_IF_NOT_ALIGN (type,
2310 				  TYPE_WARN_IF_NOT_ALIGN (align_type));
2311     }
2312 
2313   layout_type (type);
2314 #if 0 /* not yet, should get fixed properly later */
2315   TYPE_NAME (type) = make_type_decl (get_identifier (name), type);
2316 #else
2317   TYPE_NAME (type) = build_decl (BUILTINS_LOCATION,
2318 				 TYPE_DECL, get_identifier (name), type);
2319 #endif
2320   TYPE_STUB_DECL (type) = TYPE_NAME (type);
2321   layout_decl (TYPE_NAME (type), 0);
2322 }
2323 
2324 /* Calculate the mode, size, and alignment for TYPE.
2325    For an array type, calculate the element separation as well.
2326    Record TYPE on the chain of permanent or temporary types
2327    so that dbxout will find out about it.
2328 
2329    TYPE_SIZE of a type is nonzero if the type has been laid out already.
2330    layout_type does nothing on such a type.
2331 
2332    If the type is incomplete, its TYPE_SIZE remains zero.  */
2333 
2334 void
layout_type(tree type)2335 layout_type (tree type)
2336 {
2337   gcc_assert (type);
2338 
2339   if (type == error_mark_node)
2340     return;
2341 
2342   /* We don't want finalize_type_size to copy an alignment attribute to
2343      variants that don't have it.  */
2344   type = TYPE_MAIN_VARIANT (type);
2345 
2346   /* Do nothing if type has been laid out before.  */
2347   if (TYPE_SIZE (type))
2348     return;
2349 
2350   switch (TREE_CODE (type))
2351     {
2352     case LANG_TYPE:
2353       /* This kind of type is the responsibility
2354 	 of the language-specific code.  */
2355       gcc_unreachable ();
2356 
2357     case BOOLEAN_TYPE:
2358     case INTEGER_TYPE:
2359     case ENUMERAL_TYPE:
2360       {
2361 	scalar_int_mode mode
2362 	  = smallest_int_mode_for_size (TYPE_PRECISION (type));
2363 	SET_TYPE_MODE (type, mode);
2364 	TYPE_SIZE (type) = bitsize_int (GET_MODE_BITSIZE (mode));
2365 	/* Don't set TYPE_PRECISION here, as it may be set by a bitfield.  */
2366 	TYPE_SIZE_UNIT (type) = size_int (GET_MODE_SIZE (mode));
2367 	break;
2368       }
2369 
2370     case REAL_TYPE:
2371       {
2372 	/* Allow the caller to choose the type mode, which is how decimal
2373 	   floats are distinguished from binary ones.  */
2374 	if (TYPE_MODE (type) == VOIDmode)
2375 	  SET_TYPE_MODE
2376 	    (type, float_mode_for_size (TYPE_PRECISION (type)).require ());
2377 	scalar_float_mode mode = as_a <scalar_float_mode> (TYPE_MODE (type));
2378 	TYPE_SIZE (type) = bitsize_int (GET_MODE_BITSIZE (mode));
2379 	TYPE_SIZE_UNIT (type) = size_int (GET_MODE_SIZE (mode));
2380 	break;
2381       }
2382 
2383    case FIXED_POINT_TYPE:
2384      {
2385        /* TYPE_MODE (type) has been set already.  */
2386        scalar_mode mode = SCALAR_TYPE_MODE (type);
2387        TYPE_SIZE (type) = bitsize_int (GET_MODE_BITSIZE (mode));
2388        TYPE_SIZE_UNIT (type) = size_int (GET_MODE_SIZE (mode));
2389        break;
2390      }
2391 
2392     case COMPLEX_TYPE:
2393       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TREE_TYPE (type));
2394       SET_TYPE_MODE (type,
2395 		     GET_MODE_COMPLEX_MODE (TYPE_MODE (TREE_TYPE (type))));
2396 
2397       TYPE_SIZE (type) = bitsize_int (GET_MODE_BITSIZE (TYPE_MODE (type)));
2398       TYPE_SIZE_UNIT (type) = size_int (GET_MODE_SIZE (TYPE_MODE (type)));
2399       break;
2400 
2401     case VECTOR_TYPE:
2402       {
2403 	poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (type);
2404 	tree innertype = TREE_TYPE (type);
2405 
2406 	/* Find an appropriate mode for the vector type.  */
2407 	if (TYPE_MODE (type) == VOIDmode)
2408 	  SET_TYPE_MODE (type,
2409 			 mode_for_vector (SCALAR_TYPE_MODE (innertype),
2410 					  nunits).else_blk ());
2411 
2412 	TYPE_SATURATING (type) = TYPE_SATURATING (TREE_TYPE (type));
2413         TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TREE_TYPE (type));
2414 	/* Several boolean vector elements may fit in a single unit.  */
2415 	if (VECTOR_BOOLEAN_TYPE_P (type)
2416 	    && type->type_common.mode != BLKmode)
2417 	  TYPE_SIZE_UNIT (type)
2418 	    = size_int (GET_MODE_SIZE (type->type_common.mode));
2419 	else
2420 	  TYPE_SIZE_UNIT (type) = int_const_binop (MULT_EXPR,
2421 						   TYPE_SIZE_UNIT (innertype),
2422 						   size_int (nunits));
2423 	TYPE_SIZE (type) = int_const_binop
2424 	  (MULT_EXPR,
2425 	   bits_from_bytes (TYPE_SIZE_UNIT (type)),
2426 	   bitsize_int (BITS_PER_UNIT));
2427 
2428 	/* For vector types, we do not default to the mode's alignment.
2429 	   Instead, query a target hook, defaulting to natural alignment.
2430 	   This prevents ABI changes depending on whether or not native
2431 	   vector modes are supported.  */
2432 	SET_TYPE_ALIGN (type, targetm.vector_alignment (type));
2433 
2434 	/* However, if the underlying mode requires a bigger alignment than
2435 	   what the target hook provides, we cannot use the mode.  For now,
2436 	   simply reject that case.  */
2437 	gcc_assert (TYPE_ALIGN (type)
2438 		    >= GET_MODE_ALIGNMENT (TYPE_MODE (type)));
2439         break;
2440       }
2441 
2442     case VOID_TYPE:
2443       /* This is an incomplete type and so doesn't have a size.  */
2444       SET_TYPE_ALIGN (type, 1);
2445       TYPE_USER_ALIGN (type) = 0;
2446       SET_TYPE_MODE (type, VOIDmode);
2447       break;
2448 
2449     case OFFSET_TYPE:
2450       TYPE_SIZE (type) = bitsize_int (POINTER_SIZE);
2451       TYPE_SIZE_UNIT (type) = size_int (POINTER_SIZE_UNITS);
2452       /* A pointer might be MODE_PARTIAL_INT, but ptrdiff_t must be
2453 	 integral, which may be an __intN.  */
2454       SET_TYPE_MODE (type, int_mode_for_size (POINTER_SIZE, 0).require ());
2455       TYPE_PRECISION (type) = POINTER_SIZE;
2456       break;
2457 
2458     case FUNCTION_TYPE:
2459     case METHOD_TYPE:
2460       /* It's hard to see what the mode and size of a function ought to
2461 	 be, but we do know the alignment is FUNCTION_BOUNDARY, so
2462 	 make it consistent with that.  */
2463       SET_TYPE_MODE (type,
2464 		     int_mode_for_size (FUNCTION_BOUNDARY, 0).else_blk ());
2465       TYPE_SIZE (type) = bitsize_int (FUNCTION_BOUNDARY);
2466       TYPE_SIZE_UNIT (type) = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
2467       break;
2468 
2469     case POINTER_TYPE:
2470     case REFERENCE_TYPE:
2471       {
2472 	scalar_int_mode mode = SCALAR_INT_TYPE_MODE (type);
2473 	TYPE_SIZE (type) = bitsize_int (GET_MODE_BITSIZE (mode));
2474 	TYPE_SIZE_UNIT (type) = size_int (GET_MODE_SIZE (mode));
2475 	TYPE_UNSIGNED (type) = 1;
2476 	TYPE_PRECISION (type) = GET_MODE_PRECISION (mode);
2477       }
2478       break;
2479 
2480     case ARRAY_TYPE:
2481       {
2482 	tree index = TYPE_DOMAIN (type);
2483 	tree element = TREE_TYPE (type);
2484 
2485 	/* We need to know both bounds in order to compute the size.  */
2486 	if (index && TYPE_MAX_VALUE (index) && TYPE_MIN_VALUE (index)
2487 	    && TYPE_SIZE (element))
2488 	  {
2489 	    tree ub = TYPE_MAX_VALUE (index);
2490 	    tree lb = TYPE_MIN_VALUE (index);
2491 	    tree element_size = TYPE_SIZE (element);
2492 	    tree length;
2493 
2494 	    /* Make sure that an array of zero-sized element is zero-sized
2495 	       regardless of its extent.  */
2496 	    if (integer_zerop (element_size))
2497 	      length = size_zero_node;
2498 
2499 	    /* The computation should happen in the original signedness so
2500 	       that (possible) negative values are handled appropriately
2501 	       when determining overflow.  */
2502 	    else
2503 	      {
2504 		/* ???  When it is obvious that the range is signed
2505 		   represent it using ssizetype.  */
2506 		if (TREE_CODE (lb) == INTEGER_CST
2507 		    && TREE_CODE (ub) == INTEGER_CST
2508 		    && TYPE_UNSIGNED (TREE_TYPE (lb))
2509 		    && tree_int_cst_lt (ub, lb))
2510 		  {
2511 		    lb = wide_int_to_tree (ssizetype,
2512 					   offset_int::from (wi::to_wide (lb),
2513 							     SIGNED));
2514 		    ub = wide_int_to_tree (ssizetype,
2515 					   offset_int::from (wi::to_wide (ub),
2516 							     SIGNED));
2517 		  }
2518 		length
2519 		  = fold_convert (sizetype,
2520 				  size_binop (PLUS_EXPR,
2521 					      build_int_cst (TREE_TYPE (lb), 1),
2522 					      size_binop (MINUS_EXPR, ub, lb)));
2523 	      }
2524 
2525 	    /* ??? We have no way to distinguish a null-sized array from an
2526 	       array spanning the whole sizetype range, so we arbitrarily
2527 	       decide that [0, -1] is the only valid representation.  */
2528 	    if (integer_zerop (length)
2529 	        && TREE_OVERFLOW (length)
2530 		&& integer_zerop (lb))
2531 	      length = size_zero_node;
2532 
2533 	    TYPE_SIZE (type) = size_binop (MULT_EXPR, element_size,
2534 					   bits_from_bytes (length));
2535 
2536 	    /* If we know the size of the element, calculate the total size
2537 	       directly, rather than do some division thing below.  This
2538 	       optimization helps Fortran assumed-size arrays (where the
2539 	       size of the array is determined at runtime) substantially.  */
2540 	    if (TYPE_SIZE_UNIT (element))
2541 	      TYPE_SIZE_UNIT (type)
2542 		= size_binop (MULT_EXPR, TYPE_SIZE_UNIT (element), length);
2543 	  }
2544 
2545 	/* Now round the alignment and size,
2546 	   using machine-dependent criteria if any.  */
2547 
2548 	unsigned align = TYPE_ALIGN (element);
2549 	if (TYPE_USER_ALIGN (type))
2550 	  align = MAX (align, TYPE_ALIGN (type));
2551 	else
2552 	  TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (element);
2553 	if (!TYPE_WARN_IF_NOT_ALIGN (type))
2554 	  SET_TYPE_WARN_IF_NOT_ALIGN (type,
2555 				      TYPE_WARN_IF_NOT_ALIGN (element));
2556 #ifdef ROUND_TYPE_ALIGN
2557 	align = ROUND_TYPE_ALIGN (type, align, BITS_PER_UNIT);
2558 #else
2559 	align = MAX (align, BITS_PER_UNIT);
2560 #endif
2561 	SET_TYPE_ALIGN (type, align);
2562 	SET_TYPE_MODE (type, BLKmode);
2563 	if (TYPE_SIZE (type) != 0
2564 	    && ! targetm.member_type_forces_blk (type, VOIDmode)
2565 	    /* BLKmode elements force BLKmode aggregate;
2566 	       else extract/store fields may lose.  */
2567 	    && (TYPE_MODE (TREE_TYPE (type)) != BLKmode
2568 		|| TYPE_NO_FORCE_BLK (TREE_TYPE (type))))
2569 	  {
2570 	    SET_TYPE_MODE (type, mode_for_array (TREE_TYPE (type),
2571 						 TYPE_SIZE (type)));
2572 	    if (TYPE_MODE (type) != BLKmode
2573 		&& STRICT_ALIGNMENT && TYPE_ALIGN (type) < BIGGEST_ALIGNMENT
2574 		&& TYPE_ALIGN (type) < GET_MODE_ALIGNMENT (TYPE_MODE (type)))
2575 	      {
2576 		TYPE_NO_FORCE_BLK (type) = 1;
2577 		SET_TYPE_MODE (type, BLKmode);
2578 	      }
2579 	  }
2580 	if (AGGREGATE_TYPE_P (element))
2581 	  TYPE_TYPELESS_STORAGE (type) = TYPE_TYPELESS_STORAGE (element);
2582 	/* When the element size is constant, check that it is at least as
2583 	   large as the element alignment.  */
2584 	if (TYPE_SIZE_UNIT (element)
2585 	    && TREE_CODE (TYPE_SIZE_UNIT (element)) == INTEGER_CST
2586 	    /* If TYPE_SIZE_UNIT overflowed, then it is certainly larger than
2587 	       TYPE_ALIGN_UNIT.  */
2588 	    && !TREE_OVERFLOW (TYPE_SIZE_UNIT (element))
2589 	    && !integer_zerop (TYPE_SIZE_UNIT (element))
2590 	    && compare_tree_int (TYPE_SIZE_UNIT (element),
2591 			  	 TYPE_ALIGN_UNIT (element)) < 0)
2592 	  error ("alignment of array elements is greater than element size");
2593 	break;
2594       }
2595 
2596     case RECORD_TYPE:
2597     case UNION_TYPE:
2598     case QUAL_UNION_TYPE:
2599       {
2600 	tree field;
2601 	record_layout_info rli;
2602 
2603 	/* Initialize the layout information.  */
2604 	rli = start_record_layout (type);
2605 
2606 	/* If this is a QUAL_UNION_TYPE, we want to process the fields
2607 	   in the reverse order in building the COND_EXPR that denotes
2608 	   its size.  We reverse them again later.  */
2609 	if (TREE_CODE (type) == QUAL_UNION_TYPE)
2610 	  TYPE_FIELDS (type) = nreverse (TYPE_FIELDS (type));
2611 
2612 	/* Place all the fields.  */
2613 	for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2614 	  place_field (rli, field);
2615 
2616 	if (TREE_CODE (type) == QUAL_UNION_TYPE)
2617 	  TYPE_FIELDS (type) = nreverse (TYPE_FIELDS (type));
2618 
2619 	/* Finish laying out the record.  */
2620 	finish_record_layout (rli, /*free_p=*/true);
2621       }
2622       break;
2623 
2624     default:
2625       gcc_unreachable ();
2626     }
2627 
2628   /* Compute the final TYPE_SIZE, TYPE_ALIGN, etc. for TYPE.  For
2629      records and unions, finish_record_layout already called this
2630      function.  */
2631   if (!RECORD_OR_UNION_TYPE_P (type))
2632     finalize_type_size (type);
2633 
2634   /* We should never see alias sets on incomplete aggregates.  And we
2635      should not call layout_type on not incomplete aggregates.  */
2636   if (AGGREGATE_TYPE_P (type))
2637     gcc_assert (!TYPE_ALIAS_SET_KNOWN_P (type));
2638 }
2639 
2640 /* Return the least alignment required for type TYPE.  */
2641 
2642 unsigned int
min_align_of_type(tree type)2643 min_align_of_type (tree type)
2644 {
2645   unsigned int align = TYPE_ALIGN (type);
2646   if (!TYPE_USER_ALIGN (type))
2647     {
2648       align = MIN (align, BIGGEST_ALIGNMENT);
2649 #ifdef BIGGEST_FIELD_ALIGNMENT
2650       align = MIN (align, BIGGEST_FIELD_ALIGNMENT);
2651 #endif
2652       unsigned int field_align = align;
2653 #ifdef ADJUST_FIELD_ALIGN
2654       field_align = ADJUST_FIELD_ALIGN (NULL_TREE, type, field_align);
2655 #endif
2656       align = MIN (align, field_align);
2657     }
2658   return align / BITS_PER_UNIT;
2659 }
2660 
2661 /* Create and return a type for signed integers of PRECISION bits.  */
2662 
2663 tree
make_signed_type(int precision)2664 make_signed_type (int precision)
2665 {
2666   tree type = make_node (INTEGER_TYPE);
2667 
2668   TYPE_PRECISION (type) = precision;
2669 
2670   fixup_signed_type (type);
2671   return type;
2672 }
2673 
2674 /* Create and return a type for unsigned integers of PRECISION bits.  */
2675 
2676 tree
make_unsigned_type(int precision)2677 make_unsigned_type (int precision)
2678 {
2679   tree type = make_node (INTEGER_TYPE);
2680 
2681   TYPE_PRECISION (type) = precision;
2682 
2683   fixup_unsigned_type (type);
2684   return type;
2685 }
2686 
2687 /* Create and return a type for fract of PRECISION bits, UNSIGNEDP,
2688    and SATP.  */
2689 
2690 tree
make_fract_type(int precision,int unsignedp,int satp)2691 make_fract_type (int precision, int unsignedp, int satp)
2692 {
2693   tree type = make_node (FIXED_POINT_TYPE);
2694 
2695   TYPE_PRECISION (type) = precision;
2696 
2697   if (satp)
2698     TYPE_SATURATING (type) = 1;
2699 
2700   /* Lay out the type: set its alignment, size, etc.  */
2701   TYPE_UNSIGNED (type) = unsignedp;
2702   enum mode_class mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2703   SET_TYPE_MODE (type, mode_for_size (precision, mclass, 0).require ());
2704   layout_type (type);
2705 
2706   return type;
2707 }
2708 
2709 /* Create and return a type for accum of PRECISION bits, UNSIGNEDP,
2710    and SATP.  */
2711 
2712 tree
make_accum_type(int precision,int unsignedp,int satp)2713 make_accum_type (int precision, int unsignedp, int satp)
2714 {
2715   tree type = make_node (FIXED_POINT_TYPE);
2716 
2717   TYPE_PRECISION (type) = precision;
2718 
2719   if (satp)
2720     TYPE_SATURATING (type) = 1;
2721 
2722   /* Lay out the type: set its alignment, size, etc.  */
2723   TYPE_UNSIGNED (type) = unsignedp;
2724   enum mode_class mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2725   SET_TYPE_MODE (type, mode_for_size (precision, mclass, 0).require ());
2726   layout_type (type);
2727 
2728   return type;
2729 }
2730 
2731 /* Initialize sizetypes so layout_type can use them.  */
2732 
2733 void
initialize_sizetypes(void)2734 initialize_sizetypes (void)
2735 {
2736   int precision, bprecision;
2737 
2738   /* Get sizetypes precision from the SIZE_TYPE target macro.  */
2739   if (strcmp (SIZETYPE, "unsigned int") == 0)
2740     precision = INT_TYPE_SIZE;
2741   else if (strcmp (SIZETYPE, "long unsigned int") == 0)
2742     precision = LONG_TYPE_SIZE;
2743   else if (strcmp (SIZETYPE, "long long unsigned int") == 0)
2744     precision = LONG_LONG_TYPE_SIZE;
2745   else if (strcmp (SIZETYPE, "short unsigned int") == 0)
2746     precision = SHORT_TYPE_SIZE;
2747   else
2748     {
2749       int i;
2750 
2751       precision = -1;
2752       for (i = 0; i < NUM_INT_N_ENTS; i++)
2753 	if (int_n_enabled_p[i])
2754 	  {
2755 	    char name[50], altname[50];
2756 	    sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
2757 	    sprintf (altname, "__int%d__ unsigned", int_n_data[i].bitsize);
2758 
2759 	    if (strcmp (name, SIZETYPE) == 0
2760 		|| strcmp (altname, SIZETYPE) == 0)
2761 	      {
2762 		precision = int_n_data[i].bitsize;
2763 	      }
2764 	  }
2765       if (precision == -1)
2766 	gcc_unreachable ();
2767     }
2768 
2769   bprecision
2770     = MIN (precision + LOG2_BITS_PER_UNIT + 1, MAX_FIXED_MODE_SIZE);
2771   bprecision = GET_MODE_PRECISION (smallest_int_mode_for_size (bprecision));
2772   if (bprecision > HOST_BITS_PER_DOUBLE_INT)
2773     bprecision = HOST_BITS_PER_DOUBLE_INT;
2774 
2775   /* Create stubs for sizetype and bitsizetype so we can create constants.  */
2776   sizetype = make_node (INTEGER_TYPE);
2777   TYPE_NAME (sizetype) = get_identifier ("sizetype");
2778   TYPE_PRECISION (sizetype) = precision;
2779   TYPE_UNSIGNED (sizetype) = 1;
2780   bitsizetype = make_node (INTEGER_TYPE);
2781   TYPE_NAME (bitsizetype) = get_identifier ("bitsizetype");
2782   TYPE_PRECISION (bitsizetype) = bprecision;
2783   TYPE_UNSIGNED (bitsizetype) = 1;
2784 
2785   /* Now layout both types manually.  */
2786   scalar_int_mode mode = smallest_int_mode_for_size (precision);
2787   SET_TYPE_MODE (sizetype, mode);
2788   SET_TYPE_ALIGN (sizetype, GET_MODE_ALIGNMENT (TYPE_MODE (sizetype)));
2789   TYPE_SIZE (sizetype) = bitsize_int (precision);
2790   TYPE_SIZE_UNIT (sizetype) = size_int (GET_MODE_SIZE (mode));
2791   set_min_and_max_values_for_integral_type (sizetype, precision, UNSIGNED);
2792 
2793   mode = smallest_int_mode_for_size (bprecision);
2794   SET_TYPE_MODE (bitsizetype, mode);
2795   SET_TYPE_ALIGN (bitsizetype, GET_MODE_ALIGNMENT (TYPE_MODE (bitsizetype)));
2796   TYPE_SIZE (bitsizetype) = bitsize_int (bprecision);
2797   TYPE_SIZE_UNIT (bitsizetype) = size_int (GET_MODE_SIZE (mode));
2798   set_min_and_max_values_for_integral_type (bitsizetype, bprecision, UNSIGNED);
2799 
2800   /* Create the signed variants of *sizetype.  */
2801   ssizetype = make_signed_type (TYPE_PRECISION (sizetype));
2802   TYPE_NAME (ssizetype) = get_identifier ("ssizetype");
2803   sbitsizetype = make_signed_type (TYPE_PRECISION (bitsizetype));
2804   TYPE_NAME (sbitsizetype) = get_identifier ("sbitsizetype");
2805 }
2806 
2807 /* TYPE is an integral type, i.e., an INTEGRAL_TYPE, ENUMERAL_TYPE
2808    or BOOLEAN_TYPE.  Set TYPE_MIN_VALUE and TYPE_MAX_VALUE
2809    for TYPE, based on the PRECISION and whether or not the TYPE
2810    IS_UNSIGNED.  PRECISION need not correspond to a width supported
2811    natively by the hardware; for example, on a machine with 8-bit,
2812    16-bit, and 32-bit register modes, PRECISION might be 7, 23, or
2813    61.  */
2814 
2815 void
set_min_and_max_values_for_integral_type(tree type,int precision,signop sgn)2816 set_min_and_max_values_for_integral_type (tree type,
2817 					  int precision,
2818 					  signop sgn)
2819 {
2820   /* For bitfields with zero width we end up creating integer types
2821      with zero precision.  Don't assign any minimum/maximum values
2822      to those types, they don't have any valid value.  */
2823   if (precision < 1)
2824     return;
2825 
2826   gcc_assert (precision <= WIDE_INT_MAX_PRECISION);
2827 
2828   TYPE_MIN_VALUE (type)
2829     = wide_int_to_tree (type, wi::min_value (precision, sgn));
2830   TYPE_MAX_VALUE (type)
2831     = wide_int_to_tree (type, wi::max_value (precision, sgn));
2832 }
2833 
2834 /* Set the extreme values of TYPE based on its precision in bits,
2835    then lay it out.  Used when make_signed_type won't do
2836    because the tree code is not INTEGER_TYPE.  */
2837 
2838 void
fixup_signed_type(tree type)2839 fixup_signed_type (tree type)
2840 {
2841   int precision = TYPE_PRECISION (type);
2842 
2843   set_min_and_max_values_for_integral_type (type, precision, SIGNED);
2844 
2845   /* Lay out the type: set its alignment, size, etc.  */
2846   layout_type (type);
2847 }
2848 
2849 /* Set the extreme values of TYPE based on its precision in bits,
2850    then lay it out.  This is used both in `make_unsigned_type'
2851    and for enumeral types.  */
2852 
2853 void
fixup_unsigned_type(tree type)2854 fixup_unsigned_type (tree type)
2855 {
2856   int precision = TYPE_PRECISION (type);
2857 
2858   TYPE_UNSIGNED (type) = 1;
2859 
2860   set_min_and_max_values_for_integral_type (type, precision, UNSIGNED);
2861 
2862   /* Lay out the type: set its alignment, size, etc.  */
2863   layout_type (type);
2864 }
2865 
2866 /* Construct an iterator for a bitfield that spans BITSIZE bits,
2867    starting at BITPOS.
2868 
2869    BITREGION_START is the bit position of the first bit in this
2870    sequence of bit fields.  BITREGION_END is the last bit in this
2871    sequence.  If these two fields are non-zero, we should restrict the
2872    memory access to that range.  Otherwise, we are allowed to touch
2873    any adjacent non bit-fields.
2874 
2875    ALIGN is the alignment of the underlying object in bits.
2876    VOLATILEP says whether the bitfield is volatile.  */
2877 
2878 bit_field_mode_iterator
bit_field_mode_iterator(HOST_WIDE_INT bitsize,HOST_WIDE_INT bitpos,poly_int64 bitregion_start,poly_int64 bitregion_end,unsigned int align,bool volatilep)2879 ::bit_field_mode_iterator (HOST_WIDE_INT bitsize, HOST_WIDE_INT bitpos,
2880 			   poly_int64 bitregion_start,
2881 			   poly_int64 bitregion_end,
2882 			   unsigned int align, bool volatilep)
2883 : m_mode (NARROWEST_INT_MODE), m_bitsize (bitsize),
2884   m_bitpos (bitpos), m_bitregion_start (bitregion_start),
2885   m_bitregion_end (bitregion_end), m_align (align),
2886   m_volatilep (volatilep), m_count (0)
2887 {
2888   if (known_eq (m_bitregion_end, 0))
2889     {
2890       /* We can assume that any aligned chunk of ALIGN bits that overlaps
2891 	 the bitfield is mapped and won't trap, provided that ALIGN isn't
2892 	 too large.  The cap is the biggest required alignment for data,
2893 	 or at least the word size.  And force one such chunk at least.  */
2894       unsigned HOST_WIDE_INT units
2895 	= MIN (align, MAX (BIGGEST_ALIGNMENT, BITS_PER_WORD));
2896       if (bitsize <= 0)
2897 	bitsize = 1;
2898       HOST_WIDE_INT end = bitpos + bitsize + units - 1;
2899       m_bitregion_end = end - end % units - 1;
2900     }
2901 }
2902 
2903 /* Calls to this function return successively larger modes that can be used
2904    to represent the bitfield.  Return true if another bitfield mode is
2905    available, storing it in *OUT_MODE if so.  */
2906 
2907 bool
next_mode(scalar_int_mode * out_mode)2908 bit_field_mode_iterator::next_mode (scalar_int_mode *out_mode)
2909 {
2910   scalar_int_mode mode;
2911   for (; m_mode.exists (&mode); m_mode = GET_MODE_WIDER_MODE (mode))
2912     {
2913       unsigned int unit = GET_MODE_BITSIZE (mode);
2914 
2915       /* Skip modes that don't have full precision.  */
2916       if (unit != GET_MODE_PRECISION (mode))
2917 	continue;
2918 
2919       /* Stop if the mode is too wide to handle efficiently.  */
2920       if (unit > MAX_FIXED_MODE_SIZE)
2921 	break;
2922 
2923       /* Don't deliver more than one multiword mode; the smallest one
2924 	 should be used.  */
2925       if (m_count > 0 && unit > BITS_PER_WORD)
2926 	break;
2927 
2928       /* Skip modes that are too small.  */
2929       unsigned HOST_WIDE_INT substart = (unsigned HOST_WIDE_INT) m_bitpos % unit;
2930       unsigned HOST_WIDE_INT subend = substart + m_bitsize;
2931       if (subend > unit)
2932 	continue;
2933 
2934       /* Stop if the mode goes outside the bitregion.  */
2935       HOST_WIDE_INT start = m_bitpos - substart;
2936       if (maybe_ne (m_bitregion_start, 0)
2937 	  && maybe_lt (start, m_bitregion_start))
2938 	break;
2939       HOST_WIDE_INT end = start + unit;
2940       if (maybe_gt (end, m_bitregion_end + 1))
2941 	break;
2942 
2943       /* Stop if the mode requires too much alignment.  */
2944       if (GET_MODE_ALIGNMENT (mode) > m_align
2945 	  && targetm.slow_unaligned_access (mode, m_align))
2946 	break;
2947 
2948       *out_mode = mode;
2949       m_mode = GET_MODE_WIDER_MODE (mode);
2950       m_count++;
2951       return true;
2952     }
2953   return false;
2954 }
2955 
2956 /* Return true if smaller modes are generally preferred for this kind
2957    of bitfield.  */
2958 
2959 bool
prefer_smaller_modes()2960 bit_field_mode_iterator::prefer_smaller_modes ()
2961 {
2962   return (m_volatilep
2963 	  ? targetm.narrow_volatile_bitfield ()
2964 	  : !SLOW_BYTE_ACCESS);
2965 }
2966 
2967 /* Find the best machine mode to use when referencing a bit field of length
2968    BITSIZE bits starting at BITPOS.
2969 
2970    BITREGION_START is the bit position of the first bit in this
2971    sequence of bit fields.  BITREGION_END is the last bit in this
2972    sequence.  If these two fields are non-zero, we should restrict the
2973    memory access to that range.  Otherwise, we are allowed to touch
2974    any adjacent non bit-fields.
2975 
2976    The chosen mode must have no more than LARGEST_MODE_BITSIZE bits.
2977    INT_MAX is a suitable value for LARGEST_MODE_BITSIZE if the caller
2978    doesn't want to apply a specific limit.
2979 
2980    If no mode meets all these conditions, we return VOIDmode.
2981 
2982    The underlying object is known to be aligned to a boundary of ALIGN bits.
2983 
2984    If VOLATILEP is false and SLOW_BYTE_ACCESS is false, we return the
2985    smallest mode meeting these conditions.
2986 
2987    If VOLATILEP is false and SLOW_BYTE_ACCESS is true, we return the
2988    largest mode (but a mode no wider than UNITS_PER_WORD) that meets
2989    all the conditions.
2990 
2991    If VOLATILEP is true the narrow_volatile_bitfields target hook is used to
2992    decide which of the above modes should be used.  */
2993 
2994 bool
get_best_mode(int bitsize,int bitpos,poly_uint64 bitregion_start,poly_uint64 bitregion_end,unsigned int align,unsigned HOST_WIDE_INT largest_mode_bitsize,bool volatilep,scalar_int_mode * best_mode)2995 get_best_mode (int bitsize, int bitpos,
2996 	       poly_uint64 bitregion_start, poly_uint64 bitregion_end,
2997 	       unsigned int align,
2998 	       unsigned HOST_WIDE_INT largest_mode_bitsize, bool volatilep,
2999 	       scalar_int_mode *best_mode)
3000 {
3001   bit_field_mode_iterator iter (bitsize, bitpos, bitregion_start,
3002 				bitregion_end, align, volatilep);
3003   scalar_int_mode mode;
3004   bool found = false;
3005   while (iter.next_mode (&mode)
3006 	 /* ??? For historical reasons, reject modes that would normally
3007 	    receive greater alignment, even if unaligned accesses are
3008 	    acceptable.  This has both advantages and disadvantages.
3009 	    Removing this check means that something like:
3010 
3011 	       struct s { unsigned int x; unsigned int y; };
3012 	       int f (struct s *s) { return s->x == 0 && s->y == 0; }
3013 
3014 	    can be implemented using a single load and compare on
3015 	    64-bit machines that have no alignment restrictions.
3016 	    For example, on powerpc64-linux-gnu, we would generate:
3017 
3018 		    ld 3,0(3)
3019 		    cntlzd 3,3
3020 		    srdi 3,3,6
3021 		    blr
3022 
3023 	    rather than:
3024 
3025 		    lwz 9,0(3)
3026 		    cmpwi 7,9,0
3027 		    bne 7,.L3
3028 		    lwz 3,4(3)
3029 		    cntlzw 3,3
3030 		    srwi 3,3,5
3031 		    extsw 3,3
3032 		    blr
3033 		    .p2align 4,,15
3034 	    .L3:
3035 		    li 3,0
3036 		    blr
3037 
3038 	    However, accessing more than one field can make life harder
3039 	    for the gimple optimizers.  For example, gcc.dg/vect/bb-slp-5.c
3040 	    has a series of unsigned short copies followed by a series of
3041 	    unsigned short comparisons.  With this check, both the copies
3042 	    and comparisons remain 16-bit accesses and FRE is able
3043 	    to eliminate the latter.  Without the check, the comparisons
3044 	    can be done using 2 64-bit operations, which FRE isn't able
3045 	    to handle in the same way.
3046 
3047 	    Either way, it would probably be worth disabling this check
3048 	    during expand.  One particular example where removing the
3049 	    check would help is the get_best_mode call in store_bit_field.
3050 	    If we are given a memory bitregion of 128 bits that is aligned
3051 	    to a 64-bit boundary, and the bitfield we want to modify is
3052 	    in the second half of the bitregion, this check causes
3053 	    store_bitfield to turn the memory into a 64-bit reference
3054 	    to the _first_ half of the region.  We later use
3055 	    adjust_bitfield_address to get a reference to the correct half,
3056 	    but doing so looks to adjust_bitfield_address as though we are
3057 	    moving past the end of the original object, so it drops the
3058 	    associated MEM_EXPR and MEM_OFFSET.  Removing the check
3059 	    causes store_bit_field to keep a 128-bit memory reference,
3060 	    so that the final bitfield reference still has a MEM_EXPR
3061 	    and MEM_OFFSET.  */
3062 	 && GET_MODE_ALIGNMENT (mode) <= align
3063 	 && GET_MODE_BITSIZE (mode) <= largest_mode_bitsize)
3064     {
3065       *best_mode = mode;
3066       found = true;
3067       if (iter.prefer_smaller_modes ())
3068 	break;
3069     }
3070 
3071   return found;
3072 }
3073 
3074 /* Gets minimal and maximal values for MODE (signed or unsigned depending on
3075    SIGN).  The returned constants are made to be usable in TARGET_MODE.  */
3076 
3077 void
get_mode_bounds(scalar_int_mode mode,int sign,scalar_int_mode target_mode,rtx * mmin,rtx * mmax)3078 get_mode_bounds (scalar_int_mode mode, int sign,
3079 		 scalar_int_mode target_mode,
3080 		 rtx *mmin, rtx *mmax)
3081 {
3082   unsigned size = GET_MODE_PRECISION (mode);
3083   unsigned HOST_WIDE_INT min_val, max_val;
3084 
3085   gcc_assert (size <= HOST_BITS_PER_WIDE_INT);
3086 
3087   /* Special case BImode, which has values 0 and STORE_FLAG_VALUE.  */
3088   if (mode == BImode)
3089     {
3090       if (STORE_FLAG_VALUE < 0)
3091 	{
3092 	  min_val = STORE_FLAG_VALUE;
3093 	  max_val = 0;
3094 	}
3095       else
3096 	{
3097 	  min_val = 0;
3098 	  max_val = STORE_FLAG_VALUE;
3099 	}
3100     }
3101   else if (sign)
3102     {
3103       min_val = -(HOST_WIDE_INT_1U << (size - 1));
3104       max_val = (HOST_WIDE_INT_1U << (size - 1)) - 1;
3105     }
3106   else
3107     {
3108       min_val = 0;
3109       max_val = (HOST_WIDE_INT_1U << (size - 1) << 1) - 1;
3110     }
3111 
3112   *mmin = gen_int_mode (min_val, target_mode);
3113   *mmax = gen_int_mode (max_val, target_mode);
3114 }
3115 
3116 #include "gt-stor-layout.h"
3117