1 /* Subroutines shared by all languages that are variants of C.
2    Copyright (C) 1992-2022 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 #define GCC_C_COMMON_C
21 
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "target.h"
26 #include "function.h"
27 #include "tree.h"
28 #include "memmodel.h"
29 #include "c-common.h"
30 #include "gimple-expr.h"
31 #include "tm_p.h"
32 #include "stringpool.h"
33 #include "cgraph.h"
34 #include "diagnostic.h"
35 #include "intl.h"
36 #include "stor-layout.h"
37 #include "calls.h"
38 #include "attribs.h"
39 #include "varasm.h"
40 #include "trans-mem.h"
41 #include "c-objc.h"
42 #include "common/common-target.h"
43 #include "langhooks.h"
44 #include "tree-inline.h"
45 #include "toplev.h"
46 #include "tree-iterator.h"
47 #include "opts.h"
48 #include "gimplify.h"
49 #include "substring-locations.h"
50 #include "spellcheck.h"
51 #include "c-spellcheck.h"
52 #include "selftest.h"
53 #include "debug.h"
54 #include "tree-vector-builder.h"
55 #include "vec-perm-indices.h"
56 
57 cpp_reader *parse_in;		/* Declared in c-pragma.h.  */
58 
59 /* Mode used to build pointers (VOIDmode means ptr_mode).  */
60 
61 machine_mode c_default_pointer_mode = VOIDmode;
62 
63 /* The following symbols are subsumed in the c_global_trees array, and
64    listed here individually for documentation purposes.
65 
66    INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
67 
68 	tree short_integer_type_node;
69 	tree long_integer_type_node;
70 	tree long_long_integer_type_node;
71 
72 	tree short_unsigned_type_node;
73 	tree long_unsigned_type_node;
74 	tree long_long_unsigned_type_node;
75 
76 	tree truthvalue_type_node;
77 	tree truthvalue_false_node;
78 	tree truthvalue_true_node;
79 
80 	tree ptrdiff_type_node;
81 
82 	tree unsigned_char_type_node;
83 	tree signed_char_type_node;
84 	tree wchar_type_node;
85 
86 	tree char8_type_node;
87 	tree char16_type_node;
88 	tree char32_type_node;
89 
90 	tree float_type_node;
91 	tree double_type_node;
92 	tree long_double_type_node;
93 
94 	tree complex_integer_type_node;
95 	tree complex_float_type_node;
96 	tree complex_double_type_node;
97 	tree complex_long_double_type_node;
98 
99 	tree dfloat32_type_node;
100 	tree dfloat64_type_node;
101 	tree_dfloat128_type_node;
102 
103 	tree intQI_type_node;
104 	tree intHI_type_node;
105 	tree intSI_type_node;
106 	tree intDI_type_node;
107 	tree intTI_type_node;
108 
109 	tree unsigned_intQI_type_node;
110 	tree unsigned_intHI_type_node;
111 	tree unsigned_intSI_type_node;
112 	tree unsigned_intDI_type_node;
113 	tree unsigned_intTI_type_node;
114 
115 	tree widest_integer_literal_type_node;
116 	tree widest_unsigned_literal_type_node;
117 
118    Nodes for types `void *' and `const void *'.
119 
120 	tree ptr_type_node, const_ptr_type_node;
121 
122    Nodes for types `char *' and `const char *'.
123 
124 	tree string_type_node, const_string_type_node;
125 
126    Type `char[SOMENUMBER]'.
127    Used when an array of char is needed and the size is irrelevant.
128 
129 	tree char_array_type_node;
130 
131    Type `wchar_t[SOMENUMBER]' or something like it.
132    Used when a wide string literal is created.
133 
134 	tree wchar_array_type_node;
135 
136    Type `char8_t[SOMENUMBER]' or something like it.
137    Used when a UTF-8 string literal is created.
138 
139 	tree char8_array_type_node;
140 
141    Type `char16_t[SOMENUMBER]' or something like it.
142    Used when a UTF-16 string literal is created.
143 
144 	tree char16_array_type_node;
145 
146    Type `char32_t[SOMENUMBER]' or something like it.
147    Used when a UTF-32 string literal is created.
148 
149 	tree char32_array_type_node;
150 
151    Type `int ()' -- used for implicit declaration of functions.
152 
153 	tree default_function_type;
154 
155    A VOID_TYPE node, packaged in a TREE_LIST.
156 
157 	tree void_list_node;
158 
159   The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
160   and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
161   VAR_DECLS, but C++ does.)
162 
163 	tree function_name_decl_node;
164 	tree pretty_function_name_decl_node;
165 	tree c99_function_name_decl_node;
166 
167   Stack of nested function name VAR_DECLs.
168 
169 	tree saved_function_name_decls;
170 
171 */
172 
173 tree c_global_trees[CTI_MAX];
174 
175 /* Switches common to the C front ends.  */
176 
177 /* Nonzero means don't output line number information.  */
178 
179 char flag_no_line_commands;
180 
181 /* Nonzero causes -E output not to be done, but directives such as
182    #define that have side effects are still obeyed.  */
183 
184 char flag_no_output;
185 
186 /* Nonzero means dump macros in some fashion.  */
187 
188 char flag_dump_macros;
189 
190 /* Nonzero means pass #include lines through to the output.  */
191 
192 char flag_dump_includes;
193 
194 /* Nonzero means process PCH files while preprocessing.  */
195 
196 bool flag_pch_preprocess;
197 
198 /* The file name to which we should write a precompiled header, or
199    NULL if no header will be written in this compile.  */
200 
201 const char *pch_file;
202 
203 /* Nonzero if an ISO standard was selected.  It rejects macros in the
204    user's namespace.  */
205 int flag_iso;
206 
207 /* C/ObjC language option variables.  */
208 
209 
210 /* Nonzero means allow type mismatches in conditional expressions;
211    just make their values `void'.  */
212 
213 int flag_cond_mismatch;
214 
215 /* Nonzero means enable C89 Amendment 1 features.  */
216 
217 int flag_isoc94;
218 
219 /* Nonzero means use the ISO C99 (or C11) dialect of C.  */
220 
221 int flag_isoc99;
222 
223 /* Nonzero means use the ISO C11 dialect of C.  */
224 
225 int flag_isoc11;
226 
227 /* Nonzero means use the ISO C2X dialect of C.  */
228 
229 int flag_isoc2x;
230 
231 /* Nonzero means that we have builtin functions, and main is an int.  */
232 
233 int flag_hosted = 1;
234 
235 
236 /* ObjC language option variables.  */
237 
238 
239 /* Tells the compiler that this is a special run.  Do not perform any
240    compiling, instead we are to test some platform dependent features
241    and output a C header file with appropriate definitions.  */
242 
243 int print_struct_values;
244 
245 /* Tells the compiler what is the constant string class for ObjC.  */
246 
247 const char *constant_string_class_name;
248 
249 
250 /* C++ language option variables.  */
251 
252 /* The reference version of the ABI for -Wabi.  */
253 
254 int warn_abi_version = -1;
255 
256 /* The C++ dialect being used.  Default set in c_common_post_options.  */
257 
258 enum cxx_dialect cxx_dialect = cxx_unset;
259 
260 /* Maximum template instantiation depth.  This limit exists to limit the
261    time it takes to notice excessively recursive template instantiations.
262 
263    The default is lower than the 1024 recommended by the C++0x standard
264    because G++ runs out of stack before 1024 with highly recursive template
265    argument deduction substitution (g++.dg/cpp0x/enum11.C).  */
266 
267 int max_tinst_depth = 900;
268 
269 /* The elements of `ridpointers' are identifier nodes for the reserved
270    type names and storage classes.  It is indexed by a RID_... value.  */
271 tree *ridpointers;
272 
273 tree (*make_fname_decl) (location_t, tree, int);
274 
275 /* Nonzero means don't warn about problems that occur when the code is
276    executed.  */
277 int c_inhibit_evaluation_warnings;
278 
279 /* Whether we are building a boolean conversion inside
280    convert_for_assignment, or some other late binary operation.  If
281    build_binary_op is called for C (from code shared by C and C++) in
282    this case, then the operands have already been folded and the
283    result will not be folded again, so C_MAYBE_CONST_EXPR should not
284    be generated.  */
285 bool in_late_binary_op;
286 
287 /* Whether lexing has been completed, so subsequent preprocessor
288    errors should use the compiler's input_location.  */
289 bool done_lexing = false;
290 
291 /* Information about how a function name is generated.  */
292 struct fname_var_t
293 {
294   tree *const decl;	/* pointer to the VAR_DECL.  */
295   const unsigned rid;	/* RID number for the identifier.  */
296   const int pretty;	/* How pretty is it? */
297 };
298 
299 /* The three ways of getting then name of the current function.  */
300 
301 const struct fname_var_t fname_vars[] =
302 {
303   /* C99 compliant __func__, must be first.  */
304   {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
305   /* GCC __FUNCTION__ compliant.  */
306   {&function_name_decl_node, RID_FUNCTION_NAME, 0},
307   /* GCC __PRETTY_FUNCTION__ compliant.  */
308   {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
309   {NULL, 0, 0},
310 };
311 
312 /* Global visibility options.  */
313 struct visibility_flags visibility_options;
314 
315 static tree check_case_value (location_t, tree);
316 
317 
318 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
319 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
320 
321 /* Reserved words.  The third field is a mask: keywords are disabled
322    if they match the mask.
323 
324    Masks for languages:
325    C --std=c89: D_C99 | D_CXXONLY | D_OBJC | D_CXX_OBJC
326    C --std=c99: D_CXXONLY | D_OBJC
327    ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
328    C++ --std=c++98: D_CONLY | D_CXX11 | D_CXX20 | D_OBJC
329    C++ --std=c++11: D_CONLY | D_CXX20 | D_OBJC
330    C++ --std=c++20: D_CONLY | D_OBJC
331    ObjC++ is like C++ except that D_OBJC is not set
332 
333    If -fno-asm is used, D_ASM is added to the mask.  If
334    -fno-gnu-keywords is used, D_EXT is added.  If -fno-asm and C in
335    C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
336    In C with -Wc++-compat, we warn if D_CXXWARN is set.
337 
338    Note the complication of the D_CXX_OBJC keywords.  These are
339    reserved words such as 'class'.  In C++, 'class' is a reserved
340    word.  In Objective-C++ it is too.  In Objective-C, it is a
341    reserved word too, but only if it follows an '@' sign.
342 */
343 const struct c_common_resword c_common_reswords[] =
344 {
345   { "_Alignas",		RID_ALIGNAS,   D_CONLY },
346   { "_Alignof",		RID_ALIGNOF,   D_CONLY },
347   { "_Atomic",		RID_ATOMIC,    D_CONLY },
348   { "_Bool",		RID_BOOL,      D_CONLY },
349   { "_Complex",		RID_COMPLEX,	0 },
350   { "_Imaginary",	RID_IMAGINARY, D_CONLY },
351   { "_Float16",         RID_FLOAT16,   D_CONLY },
352   { "_Float32",         RID_FLOAT32,   D_CONLY },
353   { "_Float64",         RID_FLOAT64,   D_CONLY },
354   { "_Float128",        RID_FLOAT128,  D_CONLY },
355   { "_Float32x",        RID_FLOAT32X,  D_CONLY },
356   { "_Float64x",        RID_FLOAT64X,  D_CONLY },
357   { "_Float128x",       RID_FLOAT128X, D_CONLY },
358   { "_Decimal32",       RID_DFLOAT32,  D_CONLY },
359   { "_Decimal64",       RID_DFLOAT64,  D_CONLY },
360   { "_Decimal128",      RID_DFLOAT128, D_CONLY },
361   { "_Fract",           RID_FRACT,     D_CONLY | D_EXT },
362   { "_Accum",           RID_ACCUM,     D_CONLY | D_EXT },
363   { "_Sat",             RID_SAT,       D_CONLY | D_EXT },
364   { "_Static_assert",   RID_STATIC_ASSERT, D_CONLY },
365   { "_Noreturn",        RID_NORETURN,  D_CONLY },
366   { "_Generic",         RID_GENERIC,   D_CONLY },
367   { "_Thread_local",    RID_THREAD,    D_CONLY },
368   { "__FUNCTION__",	RID_FUNCTION_NAME, 0 },
369   { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
370   { "__alignof",	RID_ALIGNOF,	0 },
371   { "__alignof__",	RID_ALIGNOF,	0 },
372   { "__asm",		RID_ASM,	0 },
373   { "__asm__",		RID_ASM,	0 },
374   { "__attribute",	RID_ATTRIBUTE,	0 },
375   { "__attribute__",	RID_ATTRIBUTE,	0 },
376   { "__auto_type",	RID_AUTO_TYPE,	D_CONLY },
377   { "__bases",          RID_BASES, D_CXXONLY },
378   { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
379   { "__builtin_bit_cast", RID_BUILTIN_BIT_CAST, D_CXXONLY },
380   { "__builtin_call_with_static_chain",
381     RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
382   { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
383   { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
384   { "__builtin_convertvector", RID_BUILTIN_CONVERTVECTOR, 0 },
385   { "__builtin_has_attribute", RID_BUILTIN_HAS_ATTRIBUTE, 0 },
386   { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
387   { "__builtin_assoc_barrier", RID_BUILTIN_ASSOC_BARRIER, 0 },
388   { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
389   { "__builtin_shufflevector", RID_BUILTIN_SHUFFLEVECTOR, 0 },
390   { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
391   { "__builtin_offsetof", RID_OFFSETOF, 0 },
392   { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
393   { "__builtin_va_arg",	RID_VA_ARG,	0 },
394   { "__complex",	RID_COMPLEX,	0 },
395   { "__complex__",	RID_COMPLEX,	0 },
396   { "__const",		RID_CONST,	0 },
397   { "__const__",	RID_CONST,	0 },
398   { "__constinit",	RID_CONSTINIT,	D_CXXONLY },
399   { "__decltype",       RID_DECLTYPE,   D_CXXONLY },
400   { "__direct_bases",   RID_DIRECT_BASES, D_CXXONLY },
401   { "__extension__",	RID_EXTENSION,	0 },
402   { "__func__",		RID_C99_FUNCTION_NAME, 0 },
403   { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
404   { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
405   { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
406   { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
407   { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
408   { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
409   { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
410   { "__has_unique_object_representations", RID_HAS_UNIQUE_OBJ_REPRESENTATIONS,
411 					D_CXXONLY },
412   { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
413   { "__imag",		RID_IMAGPART,	0 },
414   { "__imag__",		RID_IMAGPART,	0 },
415   { "__inline",		RID_INLINE,	0 },
416   { "__inline__",	RID_INLINE,	0 },
417   { "__is_abstract",	RID_IS_ABSTRACT, D_CXXONLY },
418   { "__is_aggregate",	RID_IS_AGGREGATE, D_CXXONLY },
419   { "__is_base_of",	RID_IS_BASE_OF, D_CXXONLY },
420   { "__is_class",	RID_IS_CLASS,	D_CXXONLY },
421   { "__is_empty",	RID_IS_EMPTY,	D_CXXONLY },
422   { "__is_enum",	RID_IS_ENUM,	D_CXXONLY },
423   { "__is_final",	RID_IS_FINAL,	D_CXXONLY },
424   { "__is_layout_compatible", RID_IS_LAYOUT_COMPATIBLE, D_CXXONLY },
425   { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
426   { "__is_pointer_interconvertible_base_of",
427 			RID_IS_POINTER_INTERCONVERTIBLE_BASE_OF, D_CXXONLY },
428   { "__is_pod",		RID_IS_POD,	D_CXXONLY },
429   { "__is_polymorphic",	RID_IS_POLYMORPHIC, D_CXXONLY },
430   { "__is_same",     RID_IS_SAME_AS, D_CXXONLY },
431   { "__is_same_as",     RID_IS_SAME_AS, D_CXXONLY },
432   { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
433   { "__is_trivial",     RID_IS_TRIVIAL, D_CXXONLY },
434   { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
435   { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
436   { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
437   { "__is_union",	RID_IS_UNION,	D_CXXONLY },
438   { "__label__",	RID_LABEL,	0 },
439   { "__null",		RID_NULL,	0 },
440   { "__real",		RID_REALPART,	0 },
441   { "__real__",		RID_REALPART,	0 },
442   { "__restrict",	RID_RESTRICT,	0 },
443   { "__restrict__",	RID_RESTRICT,	0 },
444   { "__signed",		RID_SIGNED,	0 },
445   { "__signed__",	RID_SIGNED,	0 },
446   { "__thread",		RID_THREAD,	0 },
447   { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
448   { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
449   { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
450   { "__typeof",		RID_TYPEOF,	0 },
451   { "__typeof__",	RID_TYPEOF,	0 },
452   { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
453   { "__volatile",	RID_VOLATILE,	0 },
454   { "__volatile__",	RID_VOLATILE,	0 },
455   { "__GIMPLE",		RID_GIMPLE,	D_CONLY },
456   { "__PHI",		RID_PHI,	D_CONLY },
457   { "__RTL",		RID_RTL,	D_CONLY },
458   { "alignas",		RID_ALIGNAS,	D_CXXONLY | D_CXX11 | D_CXXWARN },
459   { "alignof",		RID_ALIGNOF,	D_CXXONLY | D_CXX11 | D_CXXWARN },
460   { "asm",		RID_ASM,	D_ASM },
461   { "auto",		RID_AUTO,	0 },
462   { "bool",		RID_BOOL,	D_CXXONLY | D_CXXWARN },
463   { "break",		RID_BREAK,	0 },
464   { "case",		RID_CASE,	0 },
465   { "catch",		RID_CATCH,	D_CXX_OBJC | D_CXXWARN },
466   { "char",		RID_CHAR,	0 },
467   { "char8_t",		RID_CHAR8,	D_CXX_CHAR8_T_FLAGS | D_CXXWARN },
468   { "char16_t",		RID_CHAR16,	D_CXXONLY | D_CXX11 | D_CXXWARN },
469   { "char32_t",		RID_CHAR32,	D_CXXONLY | D_CXX11 | D_CXXWARN },
470   { "class",		RID_CLASS,	D_CXX_OBJC | D_CXXWARN },
471   { "const",		RID_CONST,	0 },
472   { "consteval",	RID_CONSTEVAL,	D_CXXONLY | D_CXX20 | D_CXXWARN },
473   { "constexpr",	RID_CONSTEXPR,	D_CXXONLY | D_CXX11 | D_CXXWARN },
474   { "constinit",	RID_CONSTINIT,	D_CXXONLY | D_CXX20 | D_CXXWARN },
475   { "const_cast",	RID_CONSTCAST,	D_CXXONLY | D_CXXWARN },
476   { "continue",		RID_CONTINUE,	0 },
477   { "decltype",         RID_DECLTYPE,   D_CXXONLY | D_CXX11 | D_CXXWARN },
478   { "default",		RID_DEFAULT,	0 },
479   { "delete",		RID_DELETE,	D_CXXONLY | D_CXXWARN },
480   { "do",		RID_DO,		0 },
481   { "double",		RID_DOUBLE,	0 },
482   { "dynamic_cast",	RID_DYNCAST,	D_CXXONLY | D_CXXWARN },
483   { "else",		RID_ELSE,	0 },
484   { "enum",		RID_ENUM,	0 },
485   { "explicit",		RID_EXPLICIT,	D_CXXONLY | D_CXXWARN },
486   { "export",		RID_EXPORT,	D_CXXONLY | D_CXXWARN },
487   { "extern",		RID_EXTERN,	0 },
488   { "false",		RID_FALSE,	D_CXXONLY | D_CXXWARN },
489   { "float",		RID_FLOAT,	0 },
490   { "for",		RID_FOR,	0 },
491   { "friend",		RID_FRIEND,	D_CXXONLY | D_CXXWARN },
492   { "goto",		RID_GOTO,	0 },
493   { "if",		RID_IF,		0 },
494   { "inline",		RID_INLINE,	D_EXT89 },
495   { "int",		RID_INT,	0 },
496   { "long",		RID_LONG,	0 },
497   { "mutable",		RID_MUTABLE,	D_CXXONLY | D_CXXWARN },
498   { "namespace",	RID_NAMESPACE,	D_CXXONLY | D_CXXWARN },
499   { "new",		RID_NEW,	D_CXXONLY | D_CXXWARN },
500   { "noexcept",		RID_NOEXCEPT,	D_CXXONLY | D_CXX11 | D_CXXWARN },
501   { "nullptr",		RID_NULLPTR,	D_CXXONLY | D_CXX11 | D_CXXWARN },
502   { "operator",		RID_OPERATOR,	D_CXXONLY | D_CXXWARN },
503   { "private",		RID_PRIVATE,	D_CXX_OBJC | D_CXXWARN },
504   { "protected",	RID_PROTECTED,	D_CXX_OBJC | D_CXXWARN },
505   { "public",		RID_PUBLIC,	D_CXX_OBJC | D_CXXWARN },
506   { "register",		RID_REGISTER,	0 },
507   { "reinterpret_cast",	RID_REINTCAST,	D_CXXONLY | D_CXXWARN },
508   { "restrict",		RID_RESTRICT,	D_CONLY | D_C99 },
509   { "return",		RID_RETURN,	0 },
510   { "short",		RID_SHORT,	0 },
511   { "signed",		RID_SIGNED,	0 },
512   { "sizeof",		RID_SIZEOF,	0 },
513   { "static",		RID_STATIC,	0 },
514   { "static_assert",    RID_STATIC_ASSERT, D_CXXONLY | D_CXX11 | D_CXXWARN },
515   { "static_cast",	RID_STATCAST,	D_CXXONLY | D_CXXWARN },
516   { "struct",		RID_STRUCT,	0 },
517   { "switch",		RID_SWITCH,	0 },
518   { "template",		RID_TEMPLATE,	D_CXXONLY | D_CXXWARN },
519   { "this",		RID_THIS,	D_CXXONLY | D_CXXWARN },
520   { "thread_local",	RID_THREAD,	D_CXXONLY | D_CXX11 | D_CXXWARN },
521   { "throw",		RID_THROW,	D_CXX_OBJC | D_CXXWARN },
522   { "true",		RID_TRUE,	D_CXXONLY | D_CXXWARN },
523   { "try",		RID_TRY,	D_CXX_OBJC | D_CXXWARN },
524   { "typedef",		RID_TYPEDEF,	0 },
525   { "typename",		RID_TYPENAME,	D_CXXONLY | D_CXXWARN },
526   { "typeid",		RID_TYPEID,	D_CXXONLY | D_CXXWARN },
527   { "typeof",		RID_TYPEOF,	D_ASM | D_EXT },
528   { "union",		RID_UNION,	0 },
529   { "unsigned",		RID_UNSIGNED,	0 },
530   { "using",		RID_USING,	D_CXXONLY | D_CXXWARN },
531   { "virtual",		RID_VIRTUAL,	D_CXXONLY | D_CXXWARN },
532   { "void",		RID_VOID,	0 },
533   { "volatile",		RID_VOLATILE,	0 },
534   { "wchar_t",		RID_WCHAR,	D_CXXONLY },
535   { "while",		RID_WHILE,	0 },
536   { "__is_assignable", RID_IS_ASSIGNABLE, D_CXXONLY },
537   { "__is_constructible", RID_IS_CONSTRUCTIBLE, D_CXXONLY },
538   { "__is_nothrow_assignable", RID_IS_NOTHROW_ASSIGNABLE, D_CXXONLY },
539   { "__is_nothrow_constructible", RID_IS_NOTHROW_CONSTRUCTIBLE, D_CXXONLY },
540 
541   /* C++ transactional memory.  */
542   { "synchronized",	RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
543   { "atomic_noexcept",	RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
544   { "atomic_cancel",	RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
545   { "atomic_commit",	RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
546 
547   /* Concepts-related keywords */
548   { "concept",		RID_CONCEPT,	D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
549   { "requires", 	RID_REQUIRES,	D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
550 
551   /* Modules-related keywords, these are internal unspellable tokens,
552      created by the preprocessor.  */
553   { "module ",		RID__MODULE,	D_CXX_MODULES_FLAGS | D_CXXWARN },
554   { "import ",		RID__IMPORT,	D_CXX_MODULES_FLAGS | D_CXXWARN },
555   { "export ",		RID__EXPORT,	D_CXX_MODULES_FLAGS | D_CXXWARN },
556 
557   /* Coroutines-related keywords */
558   { "co_await",		RID_CO_AWAIT,	D_CXX_COROUTINES_FLAGS | D_CXXWARN },
559   { "co_yield",		RID_CO_YIELD,	D_CXX_COROUTINES_FLAGS | D_CXXWARN },
560   { "co_return", 	RID_CO_RETURN,	D_CXX_COROUTINES_FLAGS | D_CXXWARN },
561 
562   /* These Objective-C keywords are recognized only immediately after
563      an '@'.  */
564   { "compatibility_alias", RID_AT_ALIAS,	D_OBJC },
565   { "defs",		RID_AT_DEFS,		D_OBJC },
566   { "encode",		RID_AT_ENCODE,		D_OBJC },
567   { "end",		RID_AT_END,		D_OBJC },
568   { "implementation",	RID_AT_IMPLEMENTATION,	D_OBJC },
569   { "interface",	RID_AT_INTERFACE,	D_OBJC },
570   { "protocol",		RID_AT_PROTOCOL,	D_OBJC },
571   { "selector",		RID_AT_SELECTOR,	D_OBJC },
572   { "finally",		RID_AT_FINALLY,		D_OBJC },
573   { "optional",		RID_AT_OPTIONAL,	D_OBJC },
574   { "required",		RID_AT_REQUIRED,	D_OBJC },
575   { "property",		RID_AT_PROPERTY,	D_OBJC },
576   { "package",		RID_AT_PACKAGE,		D_OBJC },
577   { "synthesize",	RID_AT_SYNTHESIZE,	D_OBJC },
578   { "dynamic",		RID_AT_DYNAMIC,		D_OBJC },
579   /* These are recognized only in protocol-qualifier context
580      (see above) */
581   { "bycopy",		RID_BYCOPY,		D_OBJC },
582   { "byref",		RID_BYREF,		D_OBJC },
583   { "in",		RID_IN,			D_OBJC },
584   { "inout",		RID_INOUT,		D_OBJC },
585   { "oneway",		RID_ONEWAY,		D_OBJC },
586   { "out",		RID_OUT,		D_OBJC },
587   /* These are recognized inside a property attribute list */
588   { "assign",		RID_ASSIGN,		D_OBJC },
589   { "atomic",		RID_PROPATOMIC,		D_OBJC },
590   { "copy",		RID_COPY,		D_OBJC },
591   { "getter",		RID_GETTER,		D_OBJC },
592   { "nonatomic",	RID_NONATOMIC,		D_OBJC },
593   { "readonly",		RID_READONLY,		D_OBJC },
594   { "readwrite",	RID_READWRITE,		D_OBJC },
595   { "retain",		RID_RETAIN,		D_OBJC },
596   { "setter",		RID_SETTER,		D_OBJC },
597   /* These are Objective C implementation of nullability, accepted only in
598      specific contexts.  */
599   { "null_unspecified", RID_NULL_UNSPECIFIED,	D_OBJC },
600   { "nullable",		RID_NULLABLE,		D_OBJC },
601   { "nonnull",		RID_NONNULL,		D_OBJC },
602   { "null_resettable",	RID_NULL_RESETTABLE,	D_OBJC },
603 };
604 
605 const unsigned int num_c_common_reswords =
606   sizeof c_common_reswords / sizeof (struct c_common_resword);
607 
608 /* Return identifier for address space AS.  */
609 
610 const char *
c_addr_space_name(addr_space_t as)611 c_addr_space_name (addr_space_t as)
612 {
613   int rid = RID_FIRST_ADDR_SPACE + as;
614   gcc_assert (ridpointers [rid]);
615   return IDENTIFIER_POINTER (ridpointers [rid]);
616 }
617 
618 /* Push current bindings for the function name VAR_DECLS.  */
619 
620 void
start_fname_decls(void)621 start_fname_decls (void)
622 {
623   unsigned ix;
624   tree saved = NULL_TREE;
625 
626   for (ix = 0; fname_vars[ix].decl; ix++)
627     {
628       tree decl = *fname_vars[ix].decl;
629 
630       if (decl)
631 	{
632 	  saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
633 			     saved);
634 	  *fname_vars[ix].decl = NULL_TREE;
635 	}
636     }
637   if (saved || saved_function_name_decls)
638     /* Normally they'll have been NULL, so only push if we've got a
639        stack, or they are non-NULL.  */
640     saved_function_name_decls = tree_cons (saved, NULL_TREE,
641 					   saved_function_name_decls);
642 }
643 
644 /* Finish up the current bindings, adding them into the current function's
645    statement tree.  This must be done _before_ finish_stmt_tree is called.
646    If there is no current function, we must be at file scope and no statements
647    are involved. Pop the previous bindings.  */
648 
649 void
finish_fname_decls(void)650 finish_fname_decls (void)
651 {
652   unsigned ix;
653   tree stmts = NULL_TREE;
654   tree stack = saved_function_name_decls;
655 
656   for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
657     append_to_statement_list (TREE_VALUE (stack), &stmts);
658 
659   if (stmts)
660     {
661       tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
662 
663       if (TREE_CODE (*bodyp) == BIND_EXPR)
664 	bodyp = &BIND_EXPR_BODY (*bodyp);
665 
666       append_to_statement_list_force (*bodyp, &stmts);
667       *bodyp = stmts;
668     }
669 
670   for (ix = 0; fname_vars[ix].decl; ix++)
671     *fname_vars[ix].decl = NULL_TREE;
672 
673   if (stack)
674     {
675       /* We had saved values, restore them.  */
676       tree saved;
677 
678       for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
679 	{
680 	  tree decl = TREE_PURPOSE (saved);
681 	  unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
682 
683 	  *fname_vars[ix].decl = decl;
684 	}
685       stack = TREE_CHAIN (stack);
686     }
687   saved_function_name_decls = stack;
688 }
689 
690 /* Return the text name of the current function, suitably prettified
691    by PRETTY_P.  Return string must be freed by caller.  */
692 
693 const char *
fname_as_string(int pretty_p)694 fname_as_string (int pretty_p)
695 {
696   const char *name = "top level";
697   char *namep;
698   int vrb = 2, len;
699   cpp_string cstr = { 0, 0 }, strname;
700 
701   if (!pretty_p)
702     {
703       name = "";
704       vrb = 0;
705     }
706 
707   if (current_function_decl)
708     name = lang_hooks.decl_printable_name (current_function_decl, vrb);
709 
710   len = strlen (name) + 3; /* Two for '"'s.  One for NULL.  */
711 
712   namep = XNEWVEC (char, len);
713   snprintf (namep, len, "\"%s\"", name);
714   strname.text = (unsigned char *) namep;
715   strname.len = len - 1;
716 
717   if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
718     {
719       XDELETEVEC (namep);
720       return (const char *) cstr.text;
721     }
722 
723   return namep;
724 }
725 
726 /* Return the VAR_DECL for a const char array naming the current
727    function. If the VAR_DECL has not yet been created, create it
728    now. RID indicates how it should be formatted and IDENTIFIER_NODE
729    ID is its name (unfortunately C and C++ hold the RID values of
730    keywords in different places, so we can't derive RID from ID in
731    this language independent code. LOC is the location of the
732    function.  */
733 
734 tree
fname_decl(location_t loc,unsigned int rid,tree id)735 fname_decl (location_t loc, unsigned int rid, tree id)
736 {
737   unsigned ix;
738   tree decl = NULL_TREE;
739 
740   for (ix = 0; fname_vars[ix].decl; ix++)
741     if (fname_vars[ix].rid == rid)
742       break;
743 
744   decl = *fname_vars[ix].decl;
745   if (!decl)
746     {
747       /* If a tree is built here, it would normally have the lineno of
748 	 the current statement.  Later this tree will be moved to the
749 	 beginning of the function and this line number will be wrong.
750 	 To avoid this problem set the lineno to 0 here; that prevents
751 	 it from appearing in the RTL.  */
752       tree stmts;
753       location_t saved_location = input_location;
754       input_location = UNKNOWN_LOCATION;
755 
756       stmts = push_stmt_list ();
757       decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
758       stmts = pop_stmt_list (stmts);
759       if (!IS_EMPTY_STMT (stmts))
760 	saved_function_name_decls
761 	  = tree_cons (decl, stmts, saved_function_name_decls);
762       *fname_vars[ix].decl = decl;
763       input_location = saved_location;
764     }
765   if (!ix && !current_function_decl)
766     pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
767 
768   return decl;
769 }
770 
771 /* Given a STRING_CST, give it a suitable array-of-chars data type.  */
772 
773 tree
fix_string_type(tree value)774 fix_string_type (tree value)
775 {
776   int length = TREE_STRING_LENGTH (value);
777   int nchars, charsz;
778   tree e_type, i_type, a_type;
779 
780   /* Compute the number of elements, for the array type.  */
781   if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
782     {
783       charsz = 1;
784       e_type = char_type_node;
785     }
786   else if (flag_char8_t && TREE_TYPE (value) == char8_array_type_node)
787     {
788       charsz = TYPE_PRECISION (char8_type_node) / BITS_PER_UNIT;
789       e_type = char8_type_node;
790     }
791   else if (TREE_TYPE (value) == char16_array_type_node)
792     {
793       charsz = TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT;
794       e_type = char16_type_node;
795     }
796   else if (TREE_TYPE (value) == char32_array_type_node)
797     {
798       charsz = TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT;
799       e_type = char32_type_node;
800     }
801   else
802     {
803       charsz = TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT;
804       e_type = wchar_type_node;
805     }
806 
807   /* This matters only for targets where ssizetype has smaller precision
808      than 32 bits.  */
809   if (wi::lts_p (wi::to_wide (TYPE_MAX_VALUE (ssizetype)), length))
810     {
811       error ("size of string literal is too large");
812       length = tree_to_shwi (TYPE_MAX_VALUE (ssizetype)) / charsz * charsz;
813       char *str = CONST_CAST (char *, TREE_STRING_POINTER (value));
814       memset (str + length, '\0',
815 	      MIN (TREE_STRING_LENGTH (value) - length, charsz));
816       TREE_STRING_LENGTH (value) = length;
817     }
818   nchars = length / charsz;
819 
820   /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits).  The analogous
821      limit in C++98 Annex B is very large (65536) and is not normative,
822      so we do not diagnose it (warn_overlength_strings is forced off
823      in c_common_post_options).  */
824   if (warn_overlength_strings)
825     {
826       const int nchars_max = flag_isoc99 ? 4095 : 509;
827       const int relevant_std = flag_isoc99 ? 99 : 90;
828       if (nchars - 1 > nchars_max)
829 	/* Translators: The %d after 'ISO C' will be 90 or 99.  Do not
830 	   separate the %d from the 'C'.  'ISO' should not be
831 	   translated, but it may be moved after 'C%d' in languages
832 	   where modifiers follow nouns.  */
833 	pedwarn (input_location, OPT_Woverlength_strings,
834 		 "string length %qd is greater than the length %qd "
835 		 "ISO C%d compilers are required to support",
836 		 nchars - 1, nchars_max, relevant_std);
837     }
838 
839   /* Create the array type for the string constant.  The ISO C++
840      standard says that a string literal has type `const char[N]' or
841      `const wchar_t[N]'.  We use the same logic when invoked as a C
842      front-end with -Wwrite-strings.
843      ??? We should change the type of an expression depending on the
844      state of a warning flag.  We should just be warning -- see how
845      this is handled in the C++ front-end for the deprecated implicit
846      conversion from string literals to `char*' or `wchar_t*'.
847 
848      The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
849      array type being the unqualified version of that type.
850      Therefore, if we are constructing an array of const char, we must
851      construct the matching unqualified array type first.  The C front
852      end does not require this, but it does no harm, so we do it
853      unconditionally.  */
854   i_type = build_index_type (size_int (nchars - 1));
855   a_type = build_array_type (e_type, i_type);
856   if (c_dialect_cxx() || warn_write_strings)
857     a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
858 
859   TREE_TYPE (value) = a_type;
860   TREE_CONSTANT (value) = 1;
861   TREE_READONLY (value) = 1;
862   TREE_STATIC (value) = 1;
863   return value;
864 }
865 
866 /* Given a string of type STRING_TYPE, determine what kind of string
867    token would give an equivalent execution encoding: CPP_STRING,
868    CPP_STRING16, or CPP_STRING32.  Return CPP_OTHER in case of error.
869    This may not be exactly the string token type that initially created
870    the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
871    string type, and CPP_UTF8STRING is indistinguishable from CPP_STRING
872    at this point.
873 
874    This effectively reverses part of the logic in lex_string and
875    fix_string_type.  */
876 
877 static enum cpp_ttype
get_cpp_ttype_from_string_type(tree string_type)878 get_cpp_ttype_from_string_type (tree string_type)
879 {
880   gcc_assert (string_type);
881   if (TREE_CODE (string_type) == POINTER_TYPE)
882     string_type = TREE_TYPE (string_type);
883 
884   if (TREE_CODE (string_type) != ARRAY_TYPE)
885     return CPP_OTHER;
886 
887   tree element_type = TREE_TYPE (string_type);
888   if (TREE_CODE (element_type) != INTEGER_TYPE)
889     return CPP_OTHER;
890 
891   int bits_per_character = TYPE_PRECISION (element_type);
892   switch (bits_per_character)
893     {
894     case 8:
895       return CPP_STRING;  /* It could have also been CPP_UTF8STRING.  */
896     case 16:
897       return CPP_STRING16;
898     case 32:
899       return CPP_STRING32;
900     }
901 
902   return CPP_OTHER;
903 }
904 
905 /* The global record of string concatentations, for use in
906    extracting locations within string literals.  */
907 
908 GTY(()) string_concat_db *g_string_concat_db;
909 
910 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION.  */
911 
912 const char *
c_get_substring_location(const substring_loc & substr_loc,location_t * out_loc)913 c_get_substring_location (const substring_loc &substr_loc,
914 			  location_t *out_loc)
915 {
916   enum cpp_ttype tok_type
917     = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
918   if (tok_type == CPP_OTHER)
919     return "unrecognized string type";
920 
921   return get_location_within_string (parse_in, g_string_concat_db,
922 				     substr_loc.get_fmt_string_loc (),
923 				     tok_type,
924 				     substr_loc.get_caret_idx (),
925 				     substr_loc.get_start_idx (),
926 				     substr_loc.get_end_idx (),
927 				     out_loc);
928 }
929 
930 
931 /* Return true iff T is a boolean promoted to int.  */
932 
933 bool
bool_promoted_to_int_p(tree t)934 bool_promoted_to_int_p (tree t)
935 {
936   return (CONVERT_EXPR_P (t)
937 	  && TREE_TYPE (t) == integer_type_node
938 	  && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
939 }
940 
941 /* vector_targets_convertible_p is used for vector pointer types.  The
942    callers perform various checks that the qualifiers are satisfactory,
943    while OTOH vector_targets_convertible_p ignores the number of elements
944    in the vectors.  That's fine with vector pointers as we can consider,
945    say, a vector of 8 elements as two consecutive vectors of 4 elements,
946    and that does not require and conversion of the pointer values.
947    In contrast, vector_types_convertible_p and
948    vector_types_compatible_elements_p are used for vector value types.  */
949 /* True if pointers to distinct types T1 and T2 can be converted to
950    each other without an explicit cast.  Only returns true for opaque
951    vector types.  */
952 bool
vector_targets_convertible_p(const_tree t1,const_tree t2)953 vector_targets_convertible_p (const_tree t1, const_tree t2)
954 {
955   if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
956       && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
957       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
958     return true;
959 
960   return false;
961 }
962 
963 /* vector_types_convertible_p is used for vector value types.
964    It could in principle call vector_targets_convertible_p as a subroutine,
965    but then the check for vector type would be duplicated with its callers,
966    and also the purpose of vector_targets_convertible_p would become
967    muddled.
968    Where vector_types_convertible_p returns true, a conversion might still be
969    needed to make the types match.
970    In contrast, vector_targets_convertible_p is used for vector pointer
971    values, and vector_types_compatible_elements_p is used specifically
972    in the context for binary operators, as a check if use is possible without
973    conversion.  */
974 /* True if vector types T1 and T2 can be converted to each other
975    without an explicit cast.  If EMIT_LAX_NOTE is true, and T1 and T2
976    can only be converted with -flax-vector-conversions yet that is not
977    in effect, emit a note telling the user about that option if such
978    a note has not previously been emitted.  */
979 bool
vector_types_convertible_p(const_tree t1,const_tree t2,bool emit_lax_note)980 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
981 {
982   static bool emitted_lax_note = false;
983   bool convertible_lax;
984 
985   if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
986       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
987     return true;
988 
989   convertible_lax =
990     (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
991      && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
992 	 || known_eq (TYPE_VECTOR_SUBPARTS (t1),
993 		      TYPE_VECTOR_SUBPARTS (t2)))
994      && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
995 	 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
996 
997   if (!convertible_lax || flag_lax_vector_conversions)
998     return convertible_lax;
999 
1000   if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
1001       && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
1002     return true;
1003 
1004   if (emit_lax_note && !emitted_lax_note)
1005     {
1006       emitted_lax_note = true;
1007       inform (input_location, "use %<-flax-vector-conversions%> to permit "
1008               "conversions between vectors with differing "
1009               "element types or numbers of subparts");
1010     }
1011 
1012   return false;
1013 }
1014 
1015 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
1016    and have vector types, V0 has the same type as V1, and the number of
1017    elements of V0, V1, MASK is the same.
1018 
1019    In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
1020    called with two arguments.  In this case implementation passes the
1021    first argument twice in order to share the same tree code.  This fact
1022    could enable the mask-values being twice the vector length.  This is
1023    an implementation accident and this semantics is not guaranteed to
1024    the user.  */
1025 tree
c_build_vec_perm_expr(location_t loc,tree v0,tree v1,tree mask,bool complain)1026 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
1027 		       bool complain)
1028 {
1029   tree ret;
1030   bool wrap = true;
1031   bool maybe_const = false;
1032   bool two_arguments = false;
1033 
1034   if (v1 == NULL_TREE)
1035     {
1036       two_arguments = true;
1037       v1 = v0;
1038     }
1039 
1040   if (v0 == error_mark_node || v1 == error_mark_node
1041       || mask == error_mark_node)
1042     return error_mark_node;
1043 
1044   if (!gnu_vector_type_p (TREE_TYPE (mask))
1045       || !VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
1046     {
1047       if (complain)
1048 	error_at (loc, "%<__builtin_shuffle%> last argument must "
1049 		       "be an integer vector");
1050       return error_mark_node;
1051     }
1052 
1053   if (!gnu_vector_type_p (TREE_TYPE (v0))
1054       || !gnu_vector_type_p (TREE_TYPE (v1)))
1055     {
1056       if (complain)
1057 	error_at (loc, "%<__builtin_shuffle%> arguments must be vectors");
1058       return error_mark_node;
1059     }
1060 
1061   if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1062     {
1063       if (complain)
1064 	error_at (loc, "%<__builtin_shuffle%> argument vectors must be of "
1065 		       "the same type");
1066       return error_mark_node;
1067     }
1068 
1069   if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1070 		TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1071       && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1072 		   TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1073     {
1074       if (complain)
1075 	error_at (loc, "%<__builtin_shuffle%> number of elements of the "
1076 		       "argument vector(s) and the mask vector should "
1077 		       "be the same");
1078       return error_mark_node;
1079     }
1080 
1081   if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1082       != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1083     {
1084       if (complain)
1085 	error_at (loc, "%<__builtin_shuffle%> argument vector(s) inner type "
1086 		       "must have the same size as inner type of the mask");
1087       return error_mark_node;
1088     }
1089 
1090   if (!c_dialect_cxx ())
1091     {
1092       /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR.  */
1093       v0 = c_fully_fold (v0, false, &maybe_const);
1094       wrap &= maybe_const;
1095 
1096       if (two_arguments)
1097         v1 = v0 = save_expr (v0);
1098       else
1099         {
1100           v1 = c_fully_fold (v1, false, &maybe_const);
1101           wrap &= maybe_const;
1102         }
1103 
1104       mask = c_fully_fold (mask, false, &maybe_const);
1105       wrap &= maybe_const;
1106     }
1107   else if (two_arguments)
1108     v1 = v0 = save_expr (v0);
1109 
1110   ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1111 
1112   if (!c_dialect_cxx () && !wrap)
1113     ret = c_wrap_maybe_const (ret, true);
1114 
1115   return ret;
1116 }
1117 
1118 /* Build a VEC_PERM_EXPR if V0, V1 are not error_mark_nodes
1119    and have vector types, V0 has the same element type as V1, and the
1120    number of elements the result is that of MASK.  */
1121 tree
c_build_shufflevector(location_t loc,tree v0,tree v1,const vec<tree> & mask,bool complain)1122 c_build_shufflevector (location_t loc, tree v0, tree v1,
1123 		       const vec<tree> &mask, bool complain)
1124 {
1125   tree ret;
1126   bool wrap = true;
1127   bool maybe_const = false;
1128 
1129   if (v0 == error_mark_node || v1 == error_mark_node)
1130     return error_mark_node;
1131 
1132   if (!gnu_vector_type_p (TREE_TYPE (v0))
1133       || !gnu_vector_type_p (TREE_TYPE (v1)))
1134     {
1135       if (complain)
1136 	error_at (loc, "%<__builtin_shufflevector%> arguments must be vectors");
1137       return error_mark_node;
1138     }
1139 
1140   /* ???  In principle one could select a constant part of a variable size
1141      vector but things get a bit awkward with trying to support this here.  */
1142   unsigned HOST_WIDE_INT v0n, v1n;
1143   if (!TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)).is_constant (&v0n)
1144       || !TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)).is_constant (&v1n))
1145     {
1146       if (complain)
1147 	error_at (loc, "%<__builtin_shufflevector%> arguments must be constant"
1148 		  " size vectors");
1149       return error_mark_node;
1150     }
1151 
1152   if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v0)))
1153       != TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v1))))
1154     {
1155       if (complain)
1156 	error_at (loc, "%<__builtin_shufflevector%> argument vectors must "
1157 		  "have the same element type");
1158       return error_mark_node;
1159     }
1160 
1161   if (!pow2p_hwi (mask.length ()))
1162     {
1163       if (complain)
1164 	error_at (loc, "%<__builtin_shufflevector%> must specify a result "
1165 		  "with a power of two number of elements");
1166       return error_mark_node;
1167     }
1168 
1169   if (!c_dialect_cxx ())
1170     {
1171       /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR.  */
1172       v0 = c_fully_fold (v0, false, &maybe_const);
1173       wrap &= maybe_const;
1174 
1175       v1 = c_fully_fold (v1, false, &maybe_const);
1176       wrap &= maybe_const;
1177     }
1178 
1179   unsigned HOST_WIDE_INT maskl = MAX (mask.length (), MAX (v0n, v1n));
1180   unsigned HOST_WIDE_INT pad = (v0n < maskl ? maskl - v0n : 0);
1181   vec_perm_builder sel (maskl, maskl, 1);
1182   unsigned i;
1183   for (i = 0; i < mask.length (); ++i)
1184     {
1185       tree idx = mask[i];
1186       if (!tree_fits_shwi_p (idx))
1187 	{
1188 	  if (complain)
1189 	    error_at (loc, "invalid element index %qE to "
1190 		      "%<__builtin_shufflevector%>", idx);
1191 	  return error_mark_node;
1192 	}
1193       HOST_WIDE_INT iidx = tree_to_shwi (idx);
1194       if (iidx < -1
1195 	  || (iidx != -1
1196 	      && (unsigned HOST_WIDE_INT) iidx >= v0n + v1n))
1197 	{
1198 	  if (complain)
1199 	    error_at (loc, "invalid element index %qE to "
1200 		      "%<__builtin_shufflevector%>", idx);
1201 	  return error_mark_node;
1202 	}
1203       /* ???  Our VEC_PERM_EXPR does not allow for -1 yet.  */
1204       if (iidx == -1)
1205 	iidx = i;
1206       /* ???  Our VEC_PERM_EXPR does not allow different sized inputs,
1207 	 so pad out a smaller v0.  */
1208       else if ((unsigned HOST_WIDE_INT) iidx >= v0n)
1209 	iidx += pad;
1210       sel.quick_push (iidx);
1211     }
1212   /* ???  VEC_PERM_EXPR does not support a result that is smaller than
1213      the inputs, so we have to pad id out.  */
1214   for (; i < maskl; ++i)
1215     sel.quick_push (i);
1216 
1217   vec_perm_indices indices (sel, 2, maskl);
1218 
1219   tree ret_type = build_vector_type (TREE_TYPE (TREE_TYPE (v0)), maskl);
1220   tree mask_type = build_vector_type (build_nonstandard_integer_type
1221 		(TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (ret_type))), 1),
1222 		maskl);
1223   /* Pad out arguments to the common vector size.  */
1224   if (v0n < maskl)
1225     {
1226       constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v0)) };
1227       v0 = build_constructor_single (ret_type, NULL_TREE, v0);
1228       for (i = 1; i < maskl / v0n; ++i)
1229 	vec_safe_push (CONSTRUCTOR_ELTS (v0), elt);
1230     }
1231   if (v1n < maskl)
1232     {
1233       constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v1)) };
1234       v1 = build_constructor_single (ret_type, NULL_TREE, v1);
1235       for (i = 1; i < maskl / v1n; ++i)
1236 	vec_safe_push (CONSTRUCTOR_ELTS (v1), elt);
1237     }
1238   ret = build3_loc (loc, VEC_PERM_EXPR, ret_type, v0, v1,
1239 		    vec_perm_indices_to_tree (mask_type, indices));
1240   /* Get the lowpart we are interested in.  */
1241   if (mask.length () < maskl)
1242     {
1243       tree lpartt = build_vector_type (TREE_TYPE (ret_type), mask.length ());
1244       ret = build3_loc (loc, BIT_FIELD_REF,
1245 			lpartt, ret, TYPE_SIZE (lpartt), bitsize_zero_node);
1246       /* Wrap the lowpart operation in a TARGET_EXPR so it gets a separate
1247 	 temporary during gimplification.  See PR101530 for cases where
1248 	 we'd otherwise end up with non-toplevel BIT_FIELD_REFs.  */
1249       tree tem = create_tmp_var_raw (lpartt);
1250       DECL_CONTEXT (tem) = current_function_decl;
1251       ret = build4 (TARGET_EXPR, lpartt, tem, ret, NULL_TREE, NULL_TREE);
1252       TREE_SIDE_EFFECTS (ret) = 1;
1253     }
1254 
1255   if (!c_dialect_cxx () && !wrap)
1256     ret = c_wrap_maybe_const (ret, true);
1257 
1258   return ret;
1259 }
1260 
1261 /* Build a VEC_CONVERT ifn for __builtin_convertvector builtin.  */
1262 
1263 tree
c_build_vec_convert(location_t loc1,tree expr,location_t loc2,tree type,bool complain)1264 c_build_vec_convert (location_t loc1, tree expr, location_t loc2, tree type,
1265 		     bool complain)
1266 {
1267   if (error_operand_p (type))
1268     return error_mark_node;
1269   if (error_operand_p (expr))
1270     return error_mark_node;
1271 
1272   if (!gnu_vector_type_p (TREE_TYPE (expr))
1273       || (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1274 	  && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (expr))))
1275     {
1276       if (complain)
1277 	error_at (loc1, "%<__builtin_convertvector%> first argument must "
1278 			"be an integer or floating vector");
1279       return error_mark_node;
1280     }
1281 
1282   if (!gnu_vector_type_p (type)
1283       || (!VECTOR_INTEGER_TYPE_P (type) && !VECTOR_FLOAT_TYPE_P (type)))
1284     {
1285       if (complain)
1286 	error_at (loc2, "%<__builtin_convertvector%> second argument must "
1287 			"be an integer or floating vector type");
1288       return error_mark_node;
1289     }
1290 
1291   if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (expr)),
1292 		TYPE_VECTOR_SUBPARTS (type)))
1293     {
1294       if (complain)
1295 	error_at (loc1, "%<__builtin_convertvector%> number of elements "
1296 			"of the first argument vector and the second argument "
1297 			"vector type should be the same");
1298       return error_mark_node;
1299     }
1300 
1301   if ((TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (expr)))
1302        == TYPE_MAIN_VARIANT (TREE_TYPE (type)))
1303       || (VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1304 	  && VECTOR_INTEGER_TYPE_P (type)
1305 	  && (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (expr)))
1306 	      == TYPE_PRECISION (TREE_TYPE (type)))))
1307     return build1_loc (loc1, VIEW_CONVERT_EXPR, type, expr);
1308 
1309   bool wrap = true;
1310   bool maybe_const = false;
1311   tree ret;
1312   if (!c_dialect_cxx ())
1313     {
1314       /* Avoid C_MAYBE_CONST_EXPRs inside of VEC_CONVERT argument.  */
1315       expr = c_fully_fold (expr, false, &maybe_const);
1316       wrap &= maybe_const;
1317     }
1318 
1319   ret = build_call_expr_internal_loc (loc1, IFN_VEC_CONVERT, type, 1, expr);
1320 
1321   if (!wrap)
1322     ret = c_wrap_maybe_const (ret, true);
1323 
1324   return ret;
1325 }
1326 
1327 /* Like tree.cc:get_narrower, but retain conversion from C++0x scoped enum
1328    to integral type.  */
1329 
1330 tree
c_common_get_narrower(tree op,int * unsignedp_ptr)1331 c_common_get_narrower (tree op, int *unsignedp_ptr)
1332 {
1333   op = get_narrower (op, unsignedp_ptr);
1334 
1335   if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1336       && ENUM_IS_SCOPED (TREE_TYPE (op)))
1337     {
1338       /* C++0x scoped enumerations don't implicitly convert to integral
1339 	 type; if we stripped an explicit conversion to a larger type we
1340 	 need to replace it so common_type will still work.  */
1341       tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1342 					  TYPE_UNSIGNED (TREE_TYPE (op)));
1343       op = fold_convert (type, op);
1344     }
1345   return op;
1346 }
1347 
1348 /* This is a helper function of build_binary_op.
1349 
1350    For certain operations if both args were extended from the same
1351    smaller type, do the arithmetic in that type and then extend.
1352 
1353    BITWISE indicates a bitwise operation.
1354    For them, this optimization is safe only if
1355    both args are zero-extended or both are sign-extended.
1356    Otherwise, we might change the result.
1357    Eg, (short)-1 | (unsigned short)-1 is (int)-1
1358    but calculated in (unsigned short) it would be (unsigned short)-1.
1359 */
1360 tree
shorten_binary_op(tree result_type,tree op0,tree op1,bool bitwise)1361 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1362 {
1363   int unsigned0, unsigned1;
1364   tree arg0, arg1;
1365   int uns;
1366   tree type;
1367 
1368   /* Cast OP0 and OP1 to RESULT_TYPE.  Doing so prevents
1369      excessive narrowing when we call get_narrower below.  For
1370      example, suppose that OP0 is of unsigned int extended
1371      from signed char and that RESULT_TYPE is long long int.
1372      If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1373      like
1374 
1375      (long long int) (unsigned int) signed_char
1376 
1377      which get_narrower would narrow down to
1378 
1379      (unsigned int) signed char
1380 
1381      If we do not cast OP0 first, get_narrower would return
1382      signed_char, which is inconsistent with the case of the
1383      explicit cast.  */
1384   op0 = convert (result_type, op0);
1385   op1 = convert (result_type, op1);
1386 
1387   arg0 = c_common_get_narrower (op0, &unsigned0);
1388   arg1 = c_common_get_narrower (op1, &unsigned1);
1389 
1390   /* UNS is 1 if the operation to be done is an unsigned one.  */
1391   uns = TYPE_UNSIGNED (result_type);
1392 
1393   /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1394      but it *requires* conversion to FINAL_TYPE.  */
1395 
1396   if ((TYPE_PRECISION (TREE_TYPE (op0))
1397        == TYPE_PRECISION (TREE_TYPE (arg0)))
1398       && TREE_TYPE (op0) != result_type)
1399     unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1400   if ((TYPE_PRECISION (TREE_TYPE (op1))
1401        == TYPE_PRECISION (TREE_TYPE (arg1)))
1402       && TREE_TYPE (op1) != result_type)
1403     unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1404 
1405   /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE.  */
1406 
1407   /* For bitwise operations, signedness of nominal type
1408      does not matter.  Consider only how operands were extended.  */
1409   if (bitwise)
1410     uns = unsigned0;
1411 
1412   /* Note that in all three cases below we refrain from optimizing
1413      an unsigned operation on sign-extended args.
1414      That would not be valid.  */
1415 
1416   /* Both args variable: if both extended in same way
1417      from same width, do it in that width.
1418      Do it unsigned if args were zero-extended.  */
1419   if ((TYPE_PRECISION (TREE_TYPE (arg0))
1420        < TYPE_PRECISION (result_type))
1421       && (TYPE_PRECISION (TREE_TYPE (arg1))
1422 	  == TYPE_PRECISION (TREE_TYPE (arg0)))
1423       && unsigned0 == unsigned1
1424       && (unsigned0 || !uns))
1425     return c_common_signed_or_unsigned_type
1426       (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
1427 
1428   else if (TREE_CODE (arg0) == INTEGER_CST
1429 	   && (unsigned1 || !uns)
1430 	   && (TYPE_PRECISION (TREE_TYPE (arg1))
1431 	       < TYPE_PRECISION (result_type))
1432 	   && (type
1433 	       = c_common_signed_or_unsigned_type (unsigned1,
1434 						   TREE_TYPE (arg1)))
1435 	   && !POINTER_TYPE_P (type)
1436 	   && int_fits_type_p (arg0, type))
1437     return type;
1438 
1439   else if (TREE_CODE (arg1) == INTEGER_CST
1440 	   && (unsigned0 || !uns)
1441 	   && (TYPE_PRECISION (TREE_TYPE (arg0))
1442 	       < TYPE_PRECISION (result_type))
1443 	   && (type
1444 	       = c_common_signed_or_unsigned_type (unsigned0,
1445 						   TREE_TYPE (arg0)))
1446 	   && !POINTER_TYPE_P (type)
1447 	   && int_fits_type_p (arg1, type))
1448     return type;
1449 
1450   return result_type;
1451 }
1452 
1453 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1454    real of type TO_TYPE.  This is a helper function for unsafe_conversion_p.  */
1455 
1456 static bool
int_safely_convertible_to_real_p(const_tree from_type,const_tree to_type)1457 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1458 {
1459   tree type_low_bound = TYPE_MIN_VALUE (from_type);
1460   tree type_high_bound = TYPE_MAX_VALUE (from_type);
1461   REAL_VALUE_TYPE real_low_bound =
1462 	  real_value_from_int_cst (0, type_low_bound);
1463   REAL_VALUE_TYPE real_high_bound =
1464 	  real_value_from_int_cst (0, type_high_bound);
1465 
1466   return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1467 	 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1468 }
1469 
1470 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1471    to the complex/real/integer type TYPE.  Function returns non-zero when:
1472 	* EXPR is a constant which cannot be exactly converted to TYPE.
1473 	* EXPR is not a constant and size of EXPR's type > than size of TYPE,
1474 	  for EXPR type and TYPE being both integers or both real, or both
1475 	  complex.
1476 	* EXPR is not a constant of complex type and TYPE is a real or
1477 	  an integer.
1478 	* EXPR is not a constant of real type and TYPE is an integer.
1479 	* EXPR is not a constant of integer type which cannot be
1480 	  exactly converted to real type.
1481 
1482    Function allows conversions between types of different signedness if
1483    CHECK_SIGN is false and can return SAFE_CONVERSION (zero) in that
1484    case.  Function can return UNSAFE_SIGN if CHECK_SIGN is true.
1485 
1486    RESULT, when non-null is the result of the conversion.  When constant
1487    it is included in the text of diagnostics.
1488 
1489    Function allows conversions from complex constants to non-complex types,
1490    provided that imaginary part is zero and real part can be safely converted
1491    to TYPE.  */
1492 
1493 enum conversion_safety
unsafe_conversion_p(tree type,tree expr,tree result,bool check_sign)1494 unsafe_conversion_p (tree type, tree expr, tree result, bool check_sign)
1495 {
1496   enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1497   tree expr_type = TREE_TYPE (expr);
1498 
1499   expr = fold_for_warn (expr);
1500 
1501   if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1502     {
1503       /* If type is complex, we are interested in compatibility with
1504 	 underlying type.  */
1505       if (TREE_CODE (type) == COMPLEX_TYPE)
1506 	  type = TREE_TYPE (type);
1507 
1508       /* Warn for real constant that is not an exact integer converted
1509 	 to integer type.  */
1510       if (TREE_CODE (expr_type) == REAL_TYPE
1511 	  && TREE_CODE (type) == INTEGER_TYPE)
1512 	{
1513 	  if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1514 	    give_warning = UNSAFE_REAL;
1515 	}
1516       /* Warn for an integer constant that does not fit into integer type.  */
1517       else if (TREE_CODE (expr_type) == INTEGER_TYPE
1518 	       && TREE_CODE (type) == INTEGER_TYPE
1519 	       && !int_fits_type_p (expr, type))
1520 	{
1521 	  if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1522 	      && tree_int_cst_sgn (expr) < 0)
1523 	    {
1524 	      if (check_sign)
1525 		give_warning = UNSAFE_SIGN;
1526 	    }
1527 	  else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1528 	    {
1529 	      if (check_sign)
1530 		give_warning = UNSAFE_SIGN;
1531 	    }
1532 	  else
1533 	    give_warning = UNSAFE_OTHER;
1534 	}
1535       else if (TREE_CODE (type) == REAL_TYPE)
1536 	{
1537 	  /* Warn for an integer constant that does not fit into real type.  */
1538 	  if (TREE_CODE (expr_type) == INTEGER_TYPE)
1539 	    {
1540 	      REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1541 	      if (!exact_real_truncate (TYPE_MODE (type), &a))
1542 		give_warning = UNSAFE_REAL;
1543 	    }
1544 	  /* Warn for a real constant that does not fit into a smaller
1545 	     real type.  */
1546 	  else if (TREE_CODE (expr_type) == REAL_TYPE
1547 		   && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1548 	    {
1549 	      REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1550 	      if (!exact_real_truncate (TYPE_MODE (type), &a))
1551 		give_warning = UNSAFE_REAL;
1552 	    }
1553 	}
1554     }
1555 
1556   else if (TREE_CODE (expr) == COMPLEX_CST)
1557     {
1558       tree imag_part = TREE_IMAGPART (expr);
1559       /* Conversion from complex constant with zero imaginary part,
1560 	 perform check for conversion of real part.  */
1561       if ((TREE_CODE (imag_part) == REAL_CST
1562 	   && real_zerop (imag_part))
1563 	  || (TREE_CODE (imag_part) == INTEGER_CST
1564 	      && integer_zerop (imag_part)))
1565 	/* Note: in this branch we use recursive call to unsafe_conversion_p
1566 	   with different type of EXPR, but it is still safe, because when EXPR
1567 	   is a constant, it's type is not used in text of generated warnings
1568 	   (otherwise they could sound misleading).  */
1569 	return unsafe_conversion_p (type, TREE_REALPART (expr), result,
1570 				    check_sign);
1571       /* Conversion from complex constant with non-zero imaginary part.  */
1572       else
1573 	{
1574 	  /* Conversion to complex type.
1575 	     Perform checks for both real and imaginary parts.  */
1576 	  if (TREE_CODE (type) == COMPLEX_TYPE)
1577 	    {
1578 	      enum conversion_safety re_safety =
1579 		unsafe_conversion_p (type, TREE_REALPART (expr),
1580 				     result, check_sign);
1581 	      enum conversion_safety im_safety =
1582 		unsafe_conversion_p (type, imag_part, result, check_sign);
1583 
1584 	      /* Merge the results into appropriate single warning.  */
1585 
1586 	      /* Note: this case includes SAFE_CONVERSION, i.e. success.  */
1587 	      if (re_safety == im_safety)
1588 		give_warning = re_safety;
1589 	      else if (!re_safety && im_safety)
1590 		give_warning = im_safety;
1591 	      else if (re_safety && !im_safety)
1592 		give_warning = re_safety;
1593 	      else
1594 		give_warning = UNSAFE_OTHER;
1595 	    }
1596 	  /* Warn about conversion from complex to real or integer type.  */
1597 	  else
1598 	    give_warning = UNSAFE_IMAGINARY;
1599 	}
1600     }
1601 
1602   /* Checks for remaining case: EXPR is not constant.  */
1603   else
1604     {
1605       /* Warn for real types converted to integer types.  */
1606       if (TREE_CODE (expr_type) == REAL_TYPE
1607 	  && TREE_CODE (type) == INTEGER_TYPE)
1608 	give_warning = UNSAFE_REAL;
1609 
1610       else if (TREE_CODE (expr_type) == INTEGER_TYPE
1611 	       && TREE_CODE (type) == INTEGER_TYPE)
1612 	{
1613 	  /* Don't warn about unsigned char y = 0xff, x = (int) y;  */
1614 	  expr = get_unwidened (expr, 0);
1615 	  expr_type = TREE_TYPE (expr);
1616 
1617 	  /* Don't warn for short y; short x = ((int)y & 0xff);  */
1618 	  if (TREE_CODE (expr) == BIT_AND_EXPR
1619 	      || TREE_CODE (expr) == BIT_IOR_EXPR
1620 	      || TREE_CODE (expr) == BIT_XOR_EXPR)
1621 	    {
1622 	      /* If both args were extended from a shortest type,
1623 		 use that type if that is safe.  */
1624 	      expr_type = shorten_binary_op (expr_type,
1625 					     TREE_OPERAND (expr, 0),
1626 					     TREE_OPERAND (expr, 1),
1627 					     /* bitwise */1);
1628 
1629 	      if (TREE_CODE (expr) == BIT_AND_EXPR)
1630 		{
1631 		  tree op0 = TREE_OPERAND (expr, 0);
1632 		  tree op1 = TREE_OPERAND (expr, 1);
1633 		  bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1634 		  bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1635 
1636 		  /* If one of the operands is a non-negative constant
1637 		     that fits in the target type, then the type of the
1638 		     other operand does not matter. */
1639 		  if ((TREE_CODE (op0) == INTEGER_CST
1640 		       && int_fits_type_p (op0, c_common_signed_type (type))
1641 		       && int_fits_type_p (op0, c_common_unsigned_type (type)))
1642 		      || (TREE_CODE (op1) == INTEGER_CST
1643 			  && int_fits_type_p (op1, c_common_signed_type (type))
1644 			  && int_fits_type_p (op1,
1645 					      c_common_unsigned_type (type))))
1646 		    return SAFE_CONVERSION;
1647 		  /* If constant is unsigned and fits in the target
1648 		     type, then the result will also fit.  */
1649 		  else if ((TREE_CODE (op0) == INTEGER_CST
1650 			    && unsigned0
1651 			    && int_fits_type_p (op0, type))
1652 			   || (TREE_CODE (op1) == INTEGER_CST
1653 			       && unsigned1
1654 			       && int_fits_type_p (op1, type)))
1655 		    return SAFE_CONVERSION;
1656 		}
1657 	    }
1658 	  /* Warn for integer types converted to smaller integer types.  */
1659 	  if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1660 	    give_warning = UNSAFE_OTHER;
1661 
1662 	  /* When they are the same width but different signedness,
1663 	     then the value may change.  */
1664 	  else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1665 		     && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1666 		    /* Even when converted to a bigger type, if the type is
1667 		       unsigned but expr is signed, then negative values
1668 		       will be changed.  */
1669 		    || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1670 		   && check_sign)
1671 	    give_warning = UNSAFE_SIGN;
1672 	}
1673 
1674       /* Warn for integer types converted to real types if and only if
1675 	 all the range of values of the integer type cannot be
1676 	 represented by the real type.  */
1677       else if (TREE_CODE (expr_type) == INTEGER_TYPE
1678 	       && TREE_CODE (type) == REAL_TYPE)
1679 	{
1680 	  /* Don't warn about char y = 0xff; float x = (int) y;  */
1681 	  expr = get_unwidened (expr, 0);
1682 	  expr_type = TREE_TYPE (expr);
1683 
1684 	  if (!int_safely_convertible_to_real_p (expr_type, type))
1685 	    give_warning = UNSAFE_OTHER;
1686 	}
1687 
1688       /* Warn for real types converted to smaller real types.  */
1689       else if (TREE_CODE (expr_type) == REAL_TYPE
1690 	       && TREE_CODE (type) == REAL_TYPE
1691 	       && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1692 	give_warning = UNSAFE_REAL;
1693 
1694       /* Check conversion between two complex types.  */
1695       else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1696 	       && TREE_CODE (type) == COMPLEX_TYPE)
1697 	{
1698 	  /* Extract underlying types (i.e., type of real and imaginary
1699 	     parts) of expr_type and type.  */
1700 	  tree from_type = TREE_TYPE (expr_type);
1701 	  tree to_type = TREE_TYPE (type);
1702 
1703 	  /* Warn for real types converted to integer types.  */
1704 	  if (TREE_CODE (from_type) == REAL_TYPE
1705 	      && TREE_CODE (to_type) == INTEGER_TYPE)
1706 	    give_warning = UNSAFE_REAL;
1707 
1708 	  /* Warn for real types converted to smaller real types.  */
1709 	  else if (TREE_CODE (from_type) == REAL_TYPE
1710 		   && TREE_CODE (to_type) == REAL_TYPE
1711 		   && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1712 	    give_warning = UNSAFE_REAL;
1713 
1714 	  /* Check conversion for complex integer types.  Here implementation
1715 	     is simpler than for real-domain integers because it does not
1716 	     involve sophisticated cases, such as bitmasks, casts, etc.  */
1717 	  else if (TREE_CODE (from_type) == INTEGER_TYPE
1718 		   && TREE_CODE (to_type) == INTEGER_TYPE)
1719 	    {
1720 	      /* Warn for integer types converted to smaller integer types.  */
1721 	      if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1722 		give_warning = UNSAFE_OTHER;
1723 
1724 	      /* Check for different signedness, see case for real-domain
1725 		 integers (above) for a more detailed comment.  */
1726 	      else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1727 			 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1728 			|| (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1729 		       && check_sign)
1730 		give_warning = UNSAFE_SIGN;
1731 	    }
1732 	  else if (TREE_CODE (from_type) == INTEGER_TYPE
1733 		   && TREE_CODE (to_type) == REAL_TYPE
1734 		   && !int_safely_convertible_to_real_p (from_type, to_type))
1735 	    give_warning = UNSAFE_OTHER;
1736 	}
1737 
1738       /* Warn for complex types converted to real or integer types.  */
1739       else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1740 	       && TREE_CODE (type) != COMPLEX_TYPE)
1741 	give_warning = UNSAFE_IMAGINARY;
1742     }
1743 
1744   return give_warning;
1745 }
1746 
1747 
1748 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1749    Invoke this function on every expression that is converted implicitly,
1750    i.e. because of language rules and not because of an explicit cast.
1751    INIT_CONST is true if the conversion is for arithmetic types for a static
1752    initializer and folding must apply accordingly (discarding floating-point
1753    exceptions and assuming the default rounding mode is in effect).  */
1754 
1755 tree
convert_and_check(location_t loc,tree type,tree expr,bool init_const)1756 convert_and_check (location_t loc, tree type, tree expr, bool init_const)
1757 {
1758   tree result;
1759   tree expr_for_warning;
1760 
1761   /* Convert from a value with possible excess precision rather than
1762      via the semantic type, but do not warn about values not fitting
1763      exactly in the semantic type.  */
1764   if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1765     {
1766       tree orig_type = TREE_TYPE (expr);
1767       expr = TREE_OPERAND (expr, 0);
1768       expr_for_warning = (init_const
1769 			  ? convert_init (orig_type, expr)
1770 			  : convert (orig_type, expr));
1771       if (orig_type == type)
1772 	return expr_for_warning;
1773     }
1774   else
1775     expr_for_warning = expr;
1776 
1777   if (TREE_TYPE (expr) == type)
1778     return expr;
1779 
1780   result = init_const ? convert_init (type, expr) : convert (type, expr);
1781 
1782   if (c_inhibit_evaluation_warnings == 0
1783       && !TREE_OVERFLOW_P (expr)
1784       && result != error_mark_node)
1785     warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1786 
1787   return result;
1788 }
1789 
1790 /* A node in a list that describes references to variables (EXPR), which are
1791    either read accesses if WRITER is zero, or write accesses, in which case
1792    WRITER is the parent of EXPR.  */
1793 struct tlist
1794 {
1795   struct tlist *next;
1796   tree expr, writer;
1797 };
1798 
1799 /* Used to implement a cache the results of a call to verify_tree.  We only
1800    use this for SAVE_EXPRs.  */
1801 struct tlist_cache
1802 {
1803   struct tlist_cache *next;
1804   struct tlist *cache_before_sp;
1805   struct tlist *cache_after_sp;
1806   tree expr;
1807 };
1808 
1809 /* Obstack to use when allocating tlist structures, and corresponding
1810    firstobj.  */
1811 static struct obstack tlist_obstack;
1812 static char *tlist_firstobj = 0;
1813 
1814 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1815    warnings.  */
1816 static struct tlist *warned_ids;
1817 /* SAVE_EXPRs need special treatment.  We process them only once and then
1818    cache the results.  */
1819 static struct tlist_cache *save_expr_cache;
1820 
1821 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1822 static void merge_tlist (struct tlist **, struct tlist *, int);
1823 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1824 static bool warning_candidate_p (tree);
1825 static bool candidate_equal_p (const_tree, const_tree);
1826 static void warn_for_collisions (struct tlist *);
1827 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1828 static struct tlist *new_tlist (struct tlist *, tree, tree);
1829 
1830 /* Create a new struct tlist and fill in its fields.  */
1831 static struct tlist *
new_tlist(struct tlist * next,tree t,tree writer)1832 new_tlist (struct tlist *next, tree t, tree writer)
1833 {
1834   struct tlist *l;
1835   l = XOBNEW (&tlist_obstack, struct tlist);
1836   l->next = next;
1837   l->expr = t;
1838   l->writer = writer;
1839   return l;
1840 }
1841 
1842 /* Add duplicates of the nodes found in ADD to the list *TO.  If EXCLUDE_WRITER
1843    is nonnull, we ignore any node we find which has a writer equal to it.  */
1844 
1845 static void
add_tlist(struct tlist ** to,struct tlist * add,tree exclude_writer,int copy)1846 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1847 {
1848   while (add)
1849     {
1850       struct tlist *next = add->next;
1851       if (!copy)
1852 	add->next = *to;
1853       if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1854 	*to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1855       add = next;
1856     }
1857 }
1858 
1859 /* Merge the nodes of ADD into TO.  This merging process is done so that for
1860    each variable that already exists in TO, no new node is added; however if
1861    there is a write access recorded in ADD, and an occurrence on TO is only
1862    a read access, then the occurrence in TO will be modified to record the
1863    write.  */
1864 
1865 static void
merge_tlist(struct tlist ** to,struct tlist * add,int copy)1866 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1867 {
1868   struct tlist **end = to;
1869 
1870   while (*end)
1871     end = &(*end)->next;
1872 
1873   while (add)
1874     {
1875       int found = 0;
1876       struct tlist *tmp2;
1877       struct tlist *next = add->next;
1878 
1879       for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1880 	if (candidate_equal_p (tmp2->expr, add->expr))
1881 	  {
1882 	    found = 1;
1883 	    if (!tmp2->writer)
1884 	      tmp2->writer = add->writer;
1885 	  }
1886       if (!found)
1887 	{
1888 	  *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1889 	  end = &(*end)->next;
1890 	  *end = 0;
1891 	}
1892       add = next;
1893     }
1894 }
1895 
1896 /* WRITTEN is a variable, WRITER is its parent.  Warn if any of the variable
1897    references in list LIST conflict with it, excluding reads if ONLY writers
1898    is nonzero.  */
1899 
1900 static void
warn_for_collisions_1(tree written,tree writer,struct tlist * list,int only_writes)1901 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1902 		       int only_writes)
1903 {
1904   struct tlist *tmp;
1905 
1906   /* Avoid duplicate warnings.  */
1907   for (tmp = warned_ids; tmp; tmp = tmp->next)
1908     if (candidate_equal_p (tmp->expr, written))
1909       return;
1910 
1911   while (list)
1912     {
1913       if (candidate_equal_p (list->expr, written)
1914 	  && !candidate_equal_p (list->writer, writer)
1915 	  && (!only_writes || list->writer))
1916 	{
1917 	  warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1918 	  warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1919 		      OPT_Wsequence_point, "operation on %qE may be undefined",
1920 		      list->expr);
1921 	}
1922       list = list->next;
1923     }
1924 }
1925 
1926 /* Given a list LIST of references to variables, find whether any of these
1927    can cause conflicts due to missing sequence points.  */
1928 
1929 static void
warn_for_collisions(struct tlist * list)1930 warn_for_collisions (struct tlist *list)
1931 {
1932   struct tlist *tmp;
1933 
1934   for (tmp = list; tmp; tmp = tmp->next)
1935     {
1936       if (tmp->writer)
1937 	warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1938     }
1939 }
1940 
1941 /* Return nonzero if X is a tree that can be verified by the sequence point
1942    warnings.  */
1943 
1944 static bool
warning_candidate_p(tree x)1945 warning_candidate_p (tree x)
1946 {
1947   if (DECL_P (x) && DECL_ARTIFICIAL (x))
1948     return false;
1949 
1950   if (TREE_CODE (x) == BLOCK)
1951     return false;
1952 
1953   /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.cc
1954      (lvalue_p) crash on TRY/CATCH. */
1955   if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1956     return false;
1957 
1958   if (!lvalue_p (x))
1959     return false;
1960 
1961   /* No point to track non-const calls, they will never satisfy
1962      operand_equal_p.  */
1963   if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1964     return false;
1965 
1966   if (TREE_CODE (x) == STRING_CST)
1967     return false;
1968 
1969   return true;
1970 }
1971 
1972 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1973 static bool
candidate_equal_p(const_tree x,const_tree y)1974 candidate_equal_p (const_tree x, const_tree y)
1975 {
1976   return (x == y) || (x && y && operand_equal_p (x, y, 0));
1977 }
1978 
1979 /* Walk the tree X, and record accesses to variables.  If X is written by the
1980    parent tree, WRITER is the parent.
1981    We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP.  If this
1982    expression or its only operand forces a sequence point, then everything up
1983    to the sequence point is stored in PBEFORE_SP.  Everything else gets stored
1984    in PNO_SP.
1985    Once we return, we will have emitted warnings if any subexpression before
1986    such a sequence point could be undefined.  On a higher level, however, the
1987    sequence point may not be relevant, and we'll merge the two lists.
1988 
1989    Example: (b++, a) + b;
1990    The call that processes the COMPOUND_EXPR will store the increment of B
1991    in PBEFORE_SP, and the use of A in PNO_SP.  The higher-level call that
1992    processes the PLUS_EXPR will need to merge the two lists so that
1993    eventually, all accesses end up on the same list (and we'll warn about the
1994    unordered subexpressions b++ and b.
1995 
1996    A note on merging.  If we modify the former example so that our expression
1997    becomes
1998      (b++, b) + a
1999    care must be taken not simply to add all three expressions into the final
2000    PNO_SP list.  The function merge_tlist takes care of that by merging the
2001    before-SP list of the COMPOUND_EXPR into its after-SP list in a special
2002    way, so that no more than one access to B is recorded.  */
2003 
2004 static void
verify_tree(tree x,struct tlist ** pbefore_sp,struct tlist ** pno_sp,tree writer)2005 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
2006 	     tree writer)
2007 {
2008   struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
2009   enum tree_code code;
2010   enum tree_code_class cl;
2011 
2012  restart:
2013   /* X may be NULL if it is the operand of an empty statement expression
2014      ({ }).  */
2015   if (x == NULL)
2016     return;
2017 
2018   code = TREE_CODE (x);
2019   cl = TREE_CODE_CLASS (code);
2020 
2021   if (warning_candidate_p (x))
2022     *pno_sp = new_tlist (*pno_sp, x, writer);
2023 
2024   switch (code)
2025     {
2026     case CONSTRUCTOR:
2027     case SIZEOF_EXPR:
2028     case PAREN_SIZEOF_EXPR:
2029       return;
2030 
2031     case COMPOUND_EXPR:
2032     case TRUTH_ANDIF_EXPR:
2033     case TRUTH_ORIF_EXPR:
2034     sequenced_binary:
2035       tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
2036       verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2037       warn_for_collisions (tmp_nosp);
2038       merge_tlist (pbefore_sp, tmp_before, 0);
2039       merge_tlist (pbefore_sp, tmp_nosp, 0);
2040       verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
2041       warn_for_collisions (tmp_list2);
2042       merge_tlist (pbefore_sp, tmp_list3, 0);
2043       merge_tlist (pno_sp, tmp_list2, 0);
2044       return;
2045 
2046     case COND_EXPR:
2047       tmp_before = tmp_list2 = 0;
2048       verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
2049       warn_for_collisions (tmp_list2);
2050       merge_tlist (pbefore_sp, tmp_before, 0);
2051       merge_tlist (pbefore_sp, tmp_list2, 0);
2052 
2053       tmp_list3 = tmp_nosp = 0;
2054       verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
2055       warn_for_collisions (tmp_nosp);
2056       merge_tlist (pbefore_sp, tmp_list3, 0);
2057 
2058       tmp_list3 = tmp_list2 = 0;
2059       verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
2060       warn_for_collisions (tmp_list2);
2061       merge_tlist (pbefore_sp, tmp_list3, 0);
2062       /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
2063 	 two first, to avoid warning for (a ? b++ : b++).  */
2064       merge_tlist (&tmp_nosp, tmp_list2, 0);
2065       add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2066       return;
2067 
2068     case PREDECREMENT_EXPR:
2069     case PREINCREMENT_EXPR:
2070     case POSTDECREMENT_EXPR:
2071     case POSTINCREMENT_EXPR:
2072       verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
2073       return;
2074 
2075     case MODIFY_EXPR:
2076       tmp_before = tmp_nosp = tmp_list3 = 0;
2077       verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
2078       verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
2079       /* Expressions inside the LHS are not ordered wrt. the sequence points
2080 	 in the RHS.  Example:
2081 	   *a = (a++, 2)
2082 	 Despite the fact that the modification of "a" is in the before_sp
2083 	 list (tmp_before), it conflicts with the use of "a" in the LHS.
2084 	 We can handle this by adding the contents of tmp_list3
2085 	 to those of tmp_before, and redoing the collision warnings for that
2086 	 list.  */
2087       add_tlist (&tmp_before, tmp_list3, x, 1);
2088       warn_for_collisions (tmp_before);
2089       /* Exclude the LHS itself here; we first have to merge it into the
2090 	 tmp_nosp list.  This is done to avoid warning for "a = a"; if we
2091 	 didn't exclude the LHS, we'd get it twice, once as a read and once
2092 	 as a write.  */
2093       add_tlist (pno_sp, tmp_list3, x, 0);
2094       warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
2095 
2096       merge_tlist (pbefore_sp, tmp_before, 0);
2097       if (warning_candidate_p (TREE_OPERAND (x, 0)))
2098 	merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
2099       add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
2100       return;
2101 
2102     case CALL_EXPR:
2103       /* We need to warn about conflicts among arguments and conflicts between
2104 	 args and the function address.  Side effects of the function address,
2105 	 however, are not ordered by the sequence point of the call.  */
2106       {
2107 	call_expr_arg_iterator iter;
2108 	tree arg;
2109 	tmp_before = tmp_nosp = 0;
2110 	verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
2111 	FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
2112 	  {
2113 	    tmp_list2 = tmp_list3 = 0;
2114 	    verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
2115 	    merge_tlist (&tmp_list3, tmp_list2, 0);
2116 	    add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
2117 	  }
2118 	add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
2119 	warn_for_collisions (tmp_before);
2120 	add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
2121 	return;
2122       }
2123 
2124     case TREE_LIST:
2125       /* Scan all the list, e.g. indices of multi dimensional array.  */
2126       while (x)
2127 	{
2128 	  tmp_before = tmp_nosp = 0;
2129 	  verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
2130 	  merge_tlist (&tmp_nosp, tmp_before, 0);
2131 	  add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2132 	  x = TREE_CHAIN (x);
2133 	}
2134       return;
2135 
2136     case SAVE_EXPR:
2137       {
2138 	struct tlist_cache *t;
2139 	for (t = save_expr_cache; t; t = t->next)
2140 	  if (candidate_equal_p (t->expr, x))
2141 	    break;
2142 
2143 	if (!t)
2144 	  {
2145 	    t = XOBNEW (&tlist_obstack, struct tlist_cache);
2146 	    t->next = save_expr_cache;
2147 	    t->expr = x;
2148 	    save_expr_cache = t;
2149 
2150 	    tmp_before = tmp_nosp = 0;
2151 	    verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2152 	    warn_for_collisions (tmp_nosp);
2153 
2154 	    tmp_list3 = 0;
2155 	    merge_tlist (&tmp_list3, tmp_nosp, 0);
2156 	    t->cache_before_sp = tmp_before;
2157 	    t->cache_after_sp = tmp_list3;
2158 	  }
2159 	merge_tlist (pbefore_sp, t->cache_before_sp, 1);
2160 	add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
2161 	return;
2162       }
2163 
2164     case ADDR_EXPR:
2165       x = TREE_OPERAND (x, 0);
2166       if (DECL_P (x))
2167 	return;
2168       writer = 0;
2169       goto restart;
2170 
2171     case VIEW_CONVERT_EXPR:
2172       if (location_wrapper_p (x))
2173 	{
2174 	  x = TREE_OPERAND (x, 0);
2175 	  goto restart;
2176 	}
2177       goto do_default;
2178 
2179     case LSHIFT_EXPR:
2180     case RSHIFT_EXPR:
2181     case ARRAY_REF:
2182       if (cxx_dialect >= cxx17)
2183 	goto sequenced_binary;
2184       goto do_default;
2185 
2186     case COMPONENT_REF:
2187       /* Treat as unary, the other operands aren't evaluated.  */
2188       x = TREE_OPERAND (x, 0);
2189       writer = 0;
2190       goto restart;
2191 
2192     default:
2193     do_default:
2194       /* For other expressions, simply recurse on their operands.
2195 	 Manual tail recursion for unary expressions.
2196 	 Other non-expressions need not be processed.  */
2197       if (cl == tcc_unary)
2198 	{
2199 	  x = TREE_OPERAND (x, 0);
2200 	  writer = 0;
2201 	  goto restart;
2202 	}
2203       else if (IS_EXPR_CODE_CLASS (cl))
2204 	{
2205 	  int lp;
2206 	  int max = TREE_OPERAND_LENGTH (x);
2207 	  for (lp = 0; lp < max; lp++)
2208 	    {
2209 	      tmp_before = tmp_nosp = 0;
2210 	      verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
2211 	      merge_tlist (&tmp_nosp, tmp_before, 0);
2212 	      add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2213 	    }
2214 	}
2215       return;
2216     }
2217 }
2218 
2219 static constexpr size_t verify_sequence_points_limit = 1024;
2220 
2221 /* Called from verify_sequence_points via walk_tree.  */
2222 
2223 static tree
verify_tree_lim_r(tree * tp,int * walk_subtrees,void * data)2224 verify_tree_lim_r (tree *tp, int *walk_subtrees, void *data)
2225 {
2226   if (++*((size_t *) data) > verify_sequence_points_limit)
2227     return integer_zero_node;
2228 
2229   if (TYPE_P (*tp))
2230     *walk_subtrees = 0;
2231 
2232   return NULL_TREE;
2233 }
2234 
2235 /* Try to warn for undefined behavior in EXPR due to missing sequence
2236    points.  */
2237 
2238 void
verify_sequence_points(tree expr)2239 verify_sequence_points (tree expr)
2240 {
2241   tlist *before_sp = nullptr, *after_sp = nullptr;
2242 
2243   /* verify_tree is highly recursive, and merge_tlist is O(n^2),
2244      so we return early if the expression is too big.  */
2245   size_t n = 0;
2246   if (walk_tree (&expr, verify_tree_lim_r, &n, nullptr))
2247     return;
2248 
2249   warned_ids = nullptr;
2250   save_expr_cache = nullptr;
2251   if (!tlist_firstobj)
2252     {
2253       gcc_obstack_init (&tlist_obstack);
2254       tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
2255     }
2256 
2257   verify_tree (expr, &before_sp, &after_sp, NULL_TREE);
2258   warn_for_collisions (after_sp);
2259   obstack_free (&tlist_obstack, tlist_firstobj);
2260 }
2261 
2262 /* Validate the expression after `case' and apply default promotions.  */
2263 
2264 static tree
check_case_value(location_t loc,tree value)2265 check_case_value (location_t loc, tree value)
2266 {
2267   if (value == NULL_TREE)
2268     return value;
2269 
2270   if (TREE_CODE (value) == INTEGER_CST)
2271     /* Promote char or short to int.  */
2272     value = perform_integral_promotions (value);
2273   else if (value != error_mark_node)
2274     {
2275       error_at (loc, "case label does not reduce to an integer constant");
2276       value = error_mark_node;
2277     }
2278 
2279   constant_expression_warning (value);
2280 
2281   return value;
2282 }
2283 
2284 /* Return an integer type with BITS bits of precision,
2285    that is unsigned if UNSIGNEDP is nonzero, otherwise signed.  */
2286 
2287 tree
c_common_type_for_size(unsigned int bits,int unsignedp)2288 c_common_type_for_size (unsigned int bits, int unsignedp)
2289 {
2290   int i;
2291 
2292   if (bits == TYPE_PRECISION (integer_type_node))
2293     return unsignedp ? unsigned_type_node : integer_type_node;
2294 
2295   if (bits == TYPE_PRECISION (signed_char_type_node))
2296     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2297 
2298   if (bits == TYPE_PRECISION (short_integer_type_node))
2299     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2300 
2301   if (bits == TYPE_PRECISION (long_integer_type_node))
2302     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2303 
2304   if (bits == TYPE_PRECISION (long_long_integer_type_node))
2305     return (unsignedp ? long_long_unsigned_type_node
2306 	    : long_long_integer_type_node);
2307 
2308   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2309     if (int_n_enabled_p[i]
2310 	&& bits == int_n_data[i].bitsize)
2311       return (unsignedp ? int_n_trees[i].unsigned_type
2312 	      : int_n_trees[i].signed_type);
2313 
2314   if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2315     return (unsignedp ? widest_unsigned_literal_type_node
2316 	    : widest_integer_literal_type_node);
2317 
2318   if (bits <= TYPE_PRECISION (intQI_type_node))
2319     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2320 
2321   if (bits <= TYPE_PRECISION (intHI_type_node))
2322     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2323 
2324   if (bits <= TYPE_PRECISION (intSI_type_node))
2325     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2326 
2327   if (bits <= TYPE_PRECISION (intDI_type_node))
2328     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2329 
2330   return NULL_TREE;
2331 }
2332 
2333 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2334    that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2335    and saturating if SATP is nonzero, otherwise not saturating.  */
2336 
2337 tree
c_common_fixed_point_type_for_size(unsigned int ibit,unsigned int fbit,int unsignedp,int satp)2338 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2339 				    int unsignedp, int satp)
2340 {
2341   enum mode_class mclass;
2342   if (ibit == 0)
2343     mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2344   else
2345     mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2346 
2347   opt_scalar_mode opt_mode;
2348   scalar_mode mode;
2349   FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2350     {
2351       mode = opt_mode.require ();
2352       if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2353 	break;
2354     }
2355 
2356   if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2357     {
2358       sorry ("GCC cannot support operators with integer types and "
2359 	     "fixed-point types that have too many integral and "
2360 	     "fractional bits together");
2361       return NULL_TREE;
2362     }
2363 
2364   return c_common_type_for_mode (mode, satp);
2365 }
2366 
2367 /* Used for communication between c_common_type_for_mode and
2368    c_register_builtin_type.  */
2369 tree registered_builtin_types;
2370 
2371 /* Return a data type that has machine mode MODE.
2372    If the mode is an integer,
2373    then UNSIGNEDP selects between signed and unsigned types.
2374    If the mode is a fixed-point mode,
2375    then UNSIGNEDP selects between saturating and nonsaturating types.  */
2376 
2377 tree
c_common_type_for_mode(machine_mode mode,int unsignedp)2378 c_common_type_for_mode (machine_mode mode, int unsignedp)
2379 {
2380   tree t;
2381   int i;
2382 
2383   if (mode == TYPE_MODE (integer_type_node))
2384     return unsignedp ? unsigned_type_node : integer_type_node;
2385 
2386   if (mode == TYPE_MODE (signed_char_type_node))
2387     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2388 
2389   if (mode == TYPE_MODE (short_integer_type_node))
2390     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2391 
2392   if (mode == TYPE_MODE (long_integer_type_node))
2393     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2394 
2395   if (mode == TYPE_MODE (long_long_integer_type_node))
2396     return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2397 
2398   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2399     if (int_n_enabled_p[i]
2400 	&& mode == int_n_data[i].m)
2401       return (unsignedp ? int_n_trees[i].unsigned_type
2402 	      : int_n_trees[i].signed_type);
2403 
2404   if (mode == QImode)
2405     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2406 
2407   if (mode == HImode)
2408     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2409 
2410   if (mode == SImode)
2411     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2412 
2413   if (mode == DImode)
2414     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2415 
2416 #if HOST_BITS_PER_WIDE_INT >= 64
2417   if (mode == TYPE_MODE (intTI_type_node))
2418     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2419 #endif
2420 
2421   if (mode == TYPE_MODE (float_type_node))
2422     return float_type_node;
2423 
2424   if (mode == TYPE_MODE (double_type_node))
2425     return double_type_node;
2426 
2427   if (mode == TYPE_MODE (long_double_type_node))
2428     return long_double_type_node;
2429 
2430   for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2431     if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2432 	&& mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2433       return FLOATN_NX_TYPE_NODE (i);
2434 
2435   if (mode == TYPE_MODE (void_type_node))
2436     return void_type_node;
2437 
2438   if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2439       || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2440     {
2441       unsigned int precision
2442 	= GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2443       return (unsignedp
2444 	      ? make_unsigned_type (precision)
2445 	      : make_signed_type (precision));
2446     }
2447 
2448   if (COMPLEX_MODE_P (mode))
2449     {
2450       machine_mode inner_mode;
2451       tree inner_type;
2452 
2453       if (mode == TYPE_MODE (complex_float_type_node))
2454 	return complex_float_type_node;
2455       if (mode == TYPE_MODE (complex_double_type_node))
2456 	return complex_double_type_node;
2457       if (mode == TYPE_MODE (complex_long_double_type_node))
2458 	return complex_long_double_type_node;
2459 
2460       for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2461 	if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2462 	    && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2463 	  return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2464 
2465       if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2466 	return complex_integer_type_node;
2467 
2468       inner_mode = GET_MODE_INNER (mode);
2469       inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2470       if (inner_type != NULL_TREE)
2471 	return build_complex_type (inner_type);
2472     }
2473   else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
2474 	   && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2475     {
2476       unsigned int elem_bits = vector_element_size (GET_MODE_BITSIZE (mode),
2477 						    GET_MODE_NUNITS (mode));
2478       tree bool_type = build_nonstandard_boolean_type (elem_bits);
2479       return build_vector_type_for_mode (bool_type, mode);
2480     }
2481   else if (VECTOR_MODE_P (mode)
2482 	   && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2483     {
2484       machine_mode inner_mode = GET_MODE_INNER (mode);
2485       tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2486       if (inner_type != NULL_TREE)
2487 	return build_vector_type_for_mode (inner_type, mode);
2488     }
2489 
2490   if (dfloat32_type_node != NULL_TREE
2491       && mode == TYPE_MODE (dfloat32_type_node))
2492     return dfloat32_type_node;
2493   if (dfloat64_type_node != NULL_TREE
2494       && mode == TYPE_MODE (dfloat64_type_node))
2495     return dfloat64_type_node;
2496   if (dfloat128_type_node != NULL_TREE
2497       && mode == TYPE_MODE (dfloat128_type_node))
2498     return dfloat128_type_node;
2499 
2500   if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2501     {
2502       if (mode == TYPE_MODE (short_fract_type_node))
2503 	return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2504       if (mode == TYPE_MODE (fract_type_node))
2505 	return unsignedp ? sat_fract_type_node : fract_type_node;
2506       if (mode == TYPE_MODE (long_fract_type_node))
2507 	return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2508       if (mode == TYPE_MODE (long_long_fract_type_node))
2509 	return unsignedp ? sat_long_long_fract_type_node
2510 			 : long_long_fract_type_node;
2511 
2512       if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2513 	return unsignedp ? sat_unsigned_short_fract_type_node
2514 			 : unsigned_short_fract_type_node;
2515       if (mode == TYPE_MODE (unsigned_fract_type_node))
2516 	return unsignedp ? sat_unsigned_fract_type_node
2517 			 : unsigned_fract_type_node;
2518       if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2519 	return unsignedp ? sat_unsigned_long_fract_type_node
2520 			 : unsigned_long_fract_type_node;
2521       if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2522 	return unsignedp ? sat_unsigned_long_long_fract_type_node
2523 			 : unsigned_long_long_fract_type_node;
2524 
2525       if (mode == TYPE_MODE (short_accum_type_node))
2526 	return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2527       if (mode == TYPE_MODE (accum_type_node))
2528 	return unsignedp ? sat_accum_type_node : accum_type_node;
2529       if (mode == TYPE_MODE (long_accum_type_node))
2530 	return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2531       if (mode == TYPE_MODE (long_long_accum_type_node))
2532 	return unsignedp ? sat_long_long_accum_type_node
2533 			 : long_long_accum_type_node;
2534 
2535       if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2536 	return unsignedp ? sat_unsigned_short_accum_type_node
2537 			 : unsigned_short_accum_type_node;
2538       if (mode == TYPE_MODE (unsigned_accum_type_node))
2539 	return unsignedp ? sat_unsigned_accum_type_node
2540 			 : unsigned_accum_type_node;
2541       if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2542 	return unsignedp ? sat_unsigned_long_accum_type_node
2543 			 : unsigned_long_accum_type_node;
2544       if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2545 	return unsignedp ? sat_unsigned_long_long_accum_type_node
2546 			 : unsigned_long_long_accum_type_node;
2547 
2548       if (mode == QQmode)
2549 	return unsignedp ? sat_qq_type_node : qq_type_node;
2550       if (mode == HQmode)
2551 	return unsignedp ? sat_hq_type_node : hq_type_node;
2552       if (mode == SQmode)
2553 	return unsignedp ? sat_sq_type_node : sq_type_node;
2554       if (mode == DQmode)
2555 	return unsignedp ? sat_dq_type_node : dq_type_node;
2556       if (mode == TQmode)
2557 	return unsignedp ? sat_tq_type_node : tq_type_node;
2558 
2559       if (mode == UQQmode)
2560 	return unsignedp ? sat_uqq_type_node : uqq_type_node;
2561       if (mode == UHQmode)
2562 	return unsignedp ? sat_uhq_type_node : uhq_type_node;
2563       if (mode == USQmode)
2564 	return unsignedp ? sat_usq_type_node : usq_type_node;
2565       if (mode == UDQmode)
2566 	return unsignedp ? sat_udq_type_node : udq_type_node;
2567       if (mode == UTQmode)
2568 	return unsignedp ? sat_utq_type_node : utq_type_node;
2569 
2570       if (mode == HAmode)
2571 	return unsignedp ? sat_ha_type_node : ha_type_node;
2572       if (mode == SAmode)
2573 	return unsignedp ? sat_sa_type_node : sa_type_node;
2574       if (mode == DAmode)
2575 	return unsignedp ? sat_da_type_node : da_type_node;
2576       if (mode == TAmode)
2577 	return unsignedp ? sat_ta_type_node : ta_type_node;
2578 
2579       if (mode == UHAmode)
2580 	return unsignedp ? sat_uha_type_node : uha_type_node;
2581       if (mode == USAmode)
2582 	return unsignedp ? sat_usa_type_node : usa_type_node;
2583       if (mode == UDAmode)
2584 	return unsignedp ? sat_uda_type_node : uda_type_node;
2585       if (mode == UTAmode)
2586 	return unsignedp ? sat_uta_type_node : uta_type_node;
2587     }
2588 
2589   for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2590     {
2591       tree type = TREE_VALUE (t);
2592       if (TYPE_MODE (type) == mode
2593 	  && VECTOR_TYPE_P (type) == VECTOR_MODE_P (mode)
2594 	  && !!unsignedp == !!TYPE_UNSIGNED (type))
2595 	return type;
2596     }
2597   return NULL_TREE;
2598 }
2599 
2600 tree
c_common_unsigned_type(tree type)2601 c_common_unsigned_type (tree type)
2602 {
2603   return c_common_signed_or_unsigned_type (1, type);
2604 }
2605 
2606 /* Return a signed type the same as TYPE in other respects.  */
2607 
2608 tree
c_common_signed_type(tree type)2609 c_common_signed_type (tree type)
2610 {
2611   return c_common_signed_or_unsigned_type (0, type);
2612 }
2613 
2614 /* Return a type the same as TYPE except unsigned or
2615    signed according to UNSIGNEDP.  */
2616 
2617 tree
c_common_signed_or_unsigned_type(int unsignedp,tree type)2618 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2619 {
2620   tree type1;
2621   int i;
2622 
2623   /* This block of code emulates the behavior of the old
2624      c_common_unsigned_type. In particular, it returns
2625      long_unsigned_type_node if passed a long, even when a int would
2626      have the same size. This is necessary for warnings to work
2627      correctly in archs where sizeof(int) == sizeof(long) */
2628 
2629   type1 = TYPE_MAIN_VARIANT (type);
2630   if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2631     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2632   if (type1 == integer_type_node || type1 == unsigned_type_node)
2633     return unsignedp ? unsigned_type_node : integer_type_node;
2634   if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2635     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2636   if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2637     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2638   if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2639     return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2640 
2641   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2642     if (int_n_enabled_p[i]
2643 	&& (type1 == int_n_trees[i].unsigned_type
2644 	    || type1 == int_n_trees[i].signed_type))
2645       return (unsignedp ? int_n_trees[i].unsigned_type
2646 	      : int_n_trees[i].signed_type);
2647 
2648 #if HOST_BITS_PER_WIDE_INT >= 64
2649   if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2650     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2651 #endif
2652   if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2653     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2654   if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2655     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2656   if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2657     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2658   if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2659     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2660 
2661 #define C_COMMON_FIXED_TYPES(NAME)	    \
2662   if (type1 == short_ ## NAME ## _type_node \
2663       || type1 == unsigned_short_ ## NAME ## _type_node) \
2664     return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2665 		     : short_ ## NAME ## _type_node; \
2666   if (type1 == NAME ## _type_node \
2667       || type1 == unsigned_ ## NAME ## _type_node) \
2668     return unsignedp ? unsigned_ ## NAME ## _type_node \
2669 		     : NAME ## _type_node; \
2670   if (type1 == long_ ## NAME ## _type_node \
2671       || type1 == unsigned_long_ ## NAME ## _type_node) \
2672     return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2673 		     : long_ ## NAME ## _type_node; \
2674   if (type1 == long_long_ ## NAME ## _type_node \
2675       || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2676     return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2677 		     : long_long_ ## NAME ## _type_node;
2678 
2679 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2680   if (type1 == NAME ## _type_node \
2681       || type1 == u ## NAME ## _type_node) \
2682     return unsignedp ? u ## NAME ## _type_node \
2683 		     : NAME ## _type_node;
2684 
2685 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2686   if (type1 == sat_ ## short_ ## NAME ## _type_node \
2687       || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2688     return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2689 		     : sat_ ## short_ ## NAME ## _type_node; \
2690   if (type1 == sat_ ## NAME ## _type_node \
2691       || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2692     return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2693 		     : sat_ ## NAME ## _type_node; \
2694   if (type1 == sat_ ## long_ ## NAME ## _type_node \
2695       || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2696     return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2697 		     : sat_ ## long_ ## NAME ## _type_node; \
2698   if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2699       || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2700     return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2701 		     : sat_ ## long_long_ ## NAME ## _type_node;
2702 
2703 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME)	\
2704   if (type1 == sat_ ## NAME ## _type_node \
2705       || type1 == sat_ ## u ## NAME ## _type_node) \
2706     return unsignedp ? sat_ ## u ## NAME ## _type_node \
2707 		     : sat_ ## NAME ## _type_node;
2708 
2709   C_COMMON_FIXED_TYPES (fract);
2710   C_COMMON_FIXED_TYPES_SAT (fract);
2711   C_COMMON_FIXED_TYPES (accum);
2712   C_COMMON_FIXED_TYPES_SAT (accum);
2713 
2714   C_COMMON_FIXED_MODE_TYPES (qq);
2715   C_COMMON_FIXED_MODE_TYPES (hq);
2716   C_COMMON_FIXED_MODE_TYPES (sq);
2717   C_COMMON_FIXED_MODE_TYPES (dq);
2718   C_COMMON_FIXED_MODE_TYPES (tq);
2719   C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2720   C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2721   C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2722   C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2723   C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2724   C_COMMON_FIXED_MODE_TYPES (ha);
2725   C_COMMON_FIXED_MODE_TYPES (sa);
2726   C_COMMON_FIXED_MODE_TYPES (da);
2727   C_COMMON_FIXED_MODE_TYPES (ta);
2728   C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2729   C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2730   C_COMMON_FIXED_MODE_TYPES_SAT (da);
2731   C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2732 
2733   /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2734      the precision; they have precision set to match their range, but
2735      may use a wider mode to match an ABI.  If we change modes, we may
2736      wind up with bad conversions.  For INTEGER_TYPEs in C, must check
2737      the precision as well, so as to yield correct results for
2738      bit-field types.  C++ does not have these separate bit-field
2739      types, and producing a signed or unsigned variant of an
2740      ENUMERAL_TYPE may cause other problems as well.  */
2741 
2742   if (!INTEGRAL_TYPE_P (type)
2743       || TYPE_UNSIGNED (type) == unsignedp)
2744     return type;
2745 
2746 #define TYPE_OK(node)							    \
2747   (TYPE_MODE (type) == TYPE_MODE (node)					    \
2748    && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2749   if (TYPE_OK (signed_char_type_node))
2750     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2751   if (TYPE_OK (integer_type_node))
2752     return unsignedp ? unsigned_type_node : integer_type_node;
2753   if (TYPE_OK (short_integer_type_node))
2754     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2755   if (TYPE_OK (long_integer_type_node))
2756     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2757   if (TYPE_OK (long_long_integer_type_node))
2758     return (unsignedp ? long_long_unsigned_type_node
2759 	    : long_long_integer_type_node);
2760 
2761   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2762     if (int_n_enabled_p[i]
2763 	&& TYPE_MODE (type) == int_n_data[i].m
2764 	&& TYPE_PRECISION (type) == int_n_data[i].bitsize)
2765       return (unsignedp ? int_n_trees[i].unsigned_type
2766 	      : int_n_trees[i].signed_type);
2767 
2768 #if HOST_BITS_PER_WIDE_INT >= 64
2769   if (TYPE_OK (intTI_type_node))
2770     return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2771 #endif
2772   if (TYPE_OK (intDI_type_node))
2773     return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2774   if (TYPE_OK (intSI_type_node))
2775     return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2776   if (TYPE_OK (intHI_type_node))
2777     return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2778   if (TYPE_OK (intQI_type_node))
2779     return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2780 #undef TYPE_OK
2781 
2782   return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2783 }
2784 
2785 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP.  */
2786 
2787 tree
c_build_bitfield_integer_type(unsigned HOST_WIDE_INT width,int unsignedp)2788 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2789 {
2790   int i;
2791 
2792   /* Extended integer types of the same width as a standard type have
2793      lesser rank, so those of the same width as int promote to int or
2794      unsigned int and are valid for printf formats expecting int or
2795      unsigned int.  To avoid such special cases, avoid creating
2796      extended integer types for bit-fields if a standard integer type
2797      is available.  */
2798   if (width == TYPE_PRECISION (integer_type_node))
2799     return unsignedp ? unsigned_type_node : integer_type_node;
2800   if (width == TYPE_PRECISION (signed_char_type_node))
2801     return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2802   if (width == TYPE_PRECISION (short_integer_type_node))
2803     return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2804   if (width == TYPE_PRECISION (long_integer_type_node))
2805     return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2806   if (width == TYPE_PRECISION (long_long_integer_type_node))
2807     return (unsignedp ? long_long_unsigned_type_node
2808 	    : long_long_integer_type_node);
2809   for (i = 0; i < NUM_INT_N_ENTS; i ++)
2810     if (int_n_enabled_p[i]
2811 	&& width == int_n_data[i].bitsize)
2812       return (unsignedp ? int_n_trees[i].unsigned_type
2813 	      : int_n_trees[i].signed_type);
2814   return build_nonstandard_integer_type (width, unsignedp);
2815 }
2816 
2817 /* The C version of the register_builtin_type langhook.  */
2818 
2819 void
c_register_builtin_type(tree type,const char * name)2820 c_register_builtin_type (tree type, const char* name)
2821 {
2822   tree decl;
2823 
2824   decl = build_decl (UNKNOWN_LOCATION,
2825 		     TYPE_DECL, get_identifier (name), type);
2826   DECL_ARTIFICIAL (decl) = 1;
2827   if (!TYPE_NAME (type))
2828     TYPE_NAME (type) = decl;
2829   lang_hooks.decls.pushdecl (decl);
2830 
2831   registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2832 }
2833 
2834 /* Print an error message for invalid operands to arith operation
2835    CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2836    RICHLOC is a rich location for the message, containing either
2837    three separate locations for each of the operator and operands
2838 
2839       lhs op rhs
2840       ~~~ ^~ ~~~
2841 
2842    (C FE), or one location ranging over all over them
2843 
2844       lhs op rhs
2845       ~~~~^~~~~~
2846 
2847    (C++ FE).  */
2848 
2849 void
binary_op_error(rich_location * richloc,enum tree_code code,tree type0,tree type1)2850 binary_op_error (rich_location *richloc, enum tree_code code,
2851 		 tree type0, tree type1)
2852 {
2853   const char *opname;
2854 
2855   switch (code)
2856     {
2857     case PLUS_EXPR:
2858       opname = "+"; break;
2859     case MINUS_EXPR:
2860       opname = "-"; break;
2861     case MULT_EXPR:
2862       opname = "*"; break;
2863     case MAX_EXPR:
2864       opname = "max"; break;
2865     case MIN_EXPR:
2866       opname = "min"; break;
2867     case EQ_EXPR:
2868       opname = "=="; break;
2869     case NE_EXPR:
2870       opname = "!="; break;
2871     case LE_EXPR:
2872       opname = "<="; break;
2873     case GE_EXPR:
2874       opname = ">="; break;
2875     case LT_EXPR:
2876       opname = "<"; break;
2877     case GT_EXPR:
2878       opname = ">"; break;
2879     case LSHIFT_EXPR:
2880       opname = "<<"; break;
2881     case RSHIFT_EXPR:
2882       opname = ">>"; break;
2883     case TRUNC_MOD_EXPR:
2884     case FLOOR_MOD_EXPR:
2885       opname = "%"; break;
2886     case TRUNC_DIV_EXPR:
2887     case FLOOR_DIV_EXPR:
2888       opname = "/"; break;
2889     case BIT_AND_EXPR:
2890       opname = "&"; break;
2891     case BIT_IOR_EXPR:
2892       opname = "|"; break;
2893     case TRUTH_ANDIF_EXPR:
2894       opname = "&&"; break;
2895     case TRUTH_ORIF_EXPR:
2896       opname = "||"; break;
2897     case BIT_XOR_EXPR:
2898       opname = "^"; break;
2899     default:
2900       gcc_unreachable ();
2901     }
2902   error_at (richloc,
2903 	    "invalid operands to binary %s (have %qT and %qT)",
2904 	    opname, type0, type1);
2905 }
2906 
2907 /* Given an expression as a tree, return its original type.  Do this
2908    by stripping any conversion that preserves the sign and precision.  */
2909 static tree
expr_original_type(tree expr)2910 expr_original_type (tree expr)
2911 {
2912   STRIP_SIGN_NOPS (expr);
2913   return TREE_TYPE (expr);
2914 }
2915 
2916 /* Subroutine of build_binary_op, used for comparison operations.
2917    See if the operands have both been converted from subword integer types
2918    and, if so, perhaps change them both back to their original type.
2919    This function is also responsible for converting the two operands
2920    to the proper common type for comparison.
2921 
2922    The arguments of this function are all pointers to local variables
2923    of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2924    RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2925 
2926    LOC is the location of the comparison.
2927 
2928    If this function returns non-NULL_TREE, it means that the comparison has
2929    a constant value.  What this function returns is an expression for
2930    that value.  */
2931 
2932 tree
shorten_compare(location_t loc,tree * op0_ptr,tree * op1_ptr,tree * restype_ptr,enum tree_code * rescode_ptr)2933 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2934 		 tree *restype_ptr, enum tree_code *rescode_ptr)
2935 {
2936   tree type;
2937   tree op0 = *op0_ptr;
2938   tree op1 = *op1_ptr;
2939   int unsignedp0, unsignedp1;
2940   int real1, real2;
2941   tree primop0, primop1;
2942   enum tree_code code = *rescode_ptr;
2943 
2944   /* Throw away any conversions to wider types
2945      already present in the operands.  */
2946 
2947   primop0 = c_common_get_narrower (op0, &unsignedp0);
2948   primop1 = c_common_get_narrower (op1, &unsignedp1);
2949 
2950   /* If primopN is first sign-extended from primopN's precision to opN's
2951      precision, then zero-extended from opN's precision to
2952      *restype_ptr precision, shortenings might be invalid.  */
2953   if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2954       && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2955       && !unsignedp0
2956       && TYPE_UNSIGNED (TREE_TYPE (op0)))
2957     primop0 = op0;
2958   if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2959       && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2960       && !unsignedp1
2961       && TYPE_UNSIGNED (TREE_TYPE (op1)))
2962     primop1 = op1;
2963 
2964   /* Handle the case that OP0 does not *contain* a conversion
2965      but it *requires* conversion to FINAL_TYPE.  */
2966 
2967   if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2968     unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2969   if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2970     unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2971 
2972   /* If one of the operands must be floated, we cannot optimize.  */
2973   real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
2974   real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
2975 
2976   /* If first arg is constant, swap the args (changing operation
2977      so value is preserved), for canonicalization.  Don't do this if
2978      the second arg is 0.  */
2979 
2980   if (TREE_CONSTANT (primop0)
2981       && !integer_zerop (primop1) && !real_zerop (primop1)
2982       && !fixed_zerop (primop1))
2983     {
2984       std::swap (primop0, primop1);
2985       std::swap (op0, op1);
2986       *op0_ptr = op0;
2987       *op1_ptr = op1;
2988       std::swap (unsignedp0, unsignedp1);
2989       std::swap (real1, real2);
2990 
2991       switch (code)
2992 	{
2993 	case LT_EXPR:
2994 	  code = GT_EXPR;
2995 	  break;
2996 	case GT_EXPR:
2997 	  code = LT_EXPR;
2998 	  break;
2999 	case LE_EXPR:
3000 	  code = GE_EXPR;
3001 	  break;
3002 	case GE_EXPR:
3003 	  code = LE_EXPR;
3004 	  break;
3005 	default:
3006 	  break;
3007 	}
3008       *rescode_ptr = code;
3009     }
3010 
3011   /* If comparing an integer against a constant more bits wide,
3012      maybe we can deduce a value of 1 or 0 independent of the data.
3013      Or else truncate the constant now
3014      rather than extend the variable at run time.
3015 
3016      This is only interesting if the constant is the wider arg.
3017      Also, it is not safe if the constant is unsigned and the
3018      variable arg is signed, since in this case the variable
3019      would be sign-extended and then regarded as unsigned.
3020      Our technique fails in this case because the lowest/highest
3021      possible unsigned results don't follow naturally from the
3022      lowest/highest possible values of the variable operand.
3023      For just EQ_EXPR and NE_EXPR there is another technique that
3024      could be used: see if the constant can be faithfully represented
3025      in the other operand's type, by truncating it and reextending it
3026      and see if that preserves the constant's value.  */
3027 
3028   if (!real1 && !real2
3029       && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
3030       && TREE_CODE (primop1) == INTEGER_CST
3031       && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
3032     {
3033       int min_gt, max_gt, min_lt, max_lt;
3034       tree maxval, minval;
3035       /* 1 if comparison is nominally unsigned.  */
3036       int unsignedp = TYPE_UNSIGNED (*restype_ptr);
3037       tree val;
3038 
3039       type = c_common_signed_or_unsigned_type (unsignedp0,
3040 					       TREE_TYPE (primop0));
3041 
3042       maxval = TYPE_MAX_VALUE (type);
3043       minval = TYPE_MIN_VALUE (type);
3044 
3045       if (unsignedp && !unsignedp0)
3046 	*restype_ptr = c_common_signed_type (*restype_ptr);
3047 
3048       if (TREE_TYPE (primop1) != *restype_ptr)
3049 	{
3050 	  /* Convert primop1 to target type, but do not introduce
3051 	     additional overflow.  We know primop1 is an int_cst.  */
3052 	  primop1 = force_fit_type (*restype_ptr,
3053 				    wi::to_wide
3054 				     (primop1,
3055 				      TYPE_PRECISION (*restype_ptr)),
3056 				    0, TREE_OVERFLOW (primop1));
3057 	}
3058       if (type != *restype_ptr)
3059 	{
3060 	  minval = convert (*restype_ptr, minval);
3061 	  maxval = convert (*restype_ptr, maxval);
3062 	}
3063 
3064       min_gt = tree_int_cst_lt (primop1, minval);
3065       max_gt = tree_int_cst_lt (primop1, maxval);
3066       min_lt = tree_int_cst_lt (minval, primop1);
3067       max_lt = tree_int_cst_lt (maxval, primop1);
3068 
3069       val = 0;
3070       /* This used to be a switch, but Genix compiler can't handle that.  */
3071       if (code == NE_EXPR)
3072 	{
3073 	  if (max_lt || min_gt)
3074 	    val = truthvalue_true_node;
3075 	}
3076       else if (code == EQ_EXPR)
3077 	{
3078 	  if (max_lt || min_gt)
3079 	    val = truthvalue_false_node;
3080 	}
3081       else if (code == LT_EXPR)
3082 	{
3083 	  if (max_lt)
3084 	    val = truthvalue_true_node;
3085 	  if (!min_lt)
3086 	    val = truthvalue_false_node;
3087 	}
3088       else if (code == GT_EXPR)
3089 	{
3090 	  if (min_gt)
3091 	    val = truthvalue_true_node;
3092 	  if (!max_gt)
3093 	    val = truthvalue_false_node;
3094 	}
3095       else if (code == LE_EXPR)
3096 	{
3097 	  if (!max_gt)
3098 	    val = truthvalue_true_node;
3099 	  if (min_gt)
3100 	    val = truthvalue_false_node;
3101 	}
3102       else if (code == GE_EXPR)
3103 	{
3104 	  if (!min_lt)
3105 	    val = truthvalue_true_node;
3106 	  if (max_lt)
3107 	    val = truthvalue_false_node;
3108 	}
3109 
3110       /* If primop0 was sign-extended and unsigned comparison specd,
3111 	 we did a signed comparison above using the signed type bounds.
3112 	 But the comparison we output must be unsigned.
3113 
3114 	 Also, for inequalities, VAL is no good; but if the signed
3115 	 comparison had *any* fixed result, it follows that the
3116 	 unsigned comparison just tests the sign in reverse
3117 	 (positive values are LE, negative ones GE).
3118 	 So we can generate an unsigned comparison
3119 	 against an extreme value of the signed type.  */
3120 
3121       if (unsignedp && !unsignedp0)
3122 	{
3123 	  if (val != 0)
3124 	    switch (code)
3125 	      {
3126 	      case LT_EXPR:
3127 	      case GE_EXPR:
3128 		primop1 = TYPE_MIN_VALUE (type);
3129 		val = 0;
3130 		break;
3131 
3132 	      case LE_EXPR:
3133 	      case GT_EXPR:
3134 		primop1 = TYPE_MAX_VALUE (type);
3135 		val = 0;
3136 		break;
3137 
3138 	      default:
3139 		break;
3140 	      }
3141 	  type = c_common_unsigned_type (type);
3142 	}
3143 
3144       if (TREE_CODE (primop0) != INTEGER_CST
3145 	  /* Don't warn if it's from a (non-system) macro.  */
3146 	  && !(from_macro_expansion_at
3147 	       (expansion_point_location_if_in_system_header
3148 		(EXPR_LOCATION (primop0)))))
3149 	{
3150 	  if (val == truthvalue_false_node)
3151 	    warning_at (loc, OPT_Wtype_limits,
3152 			"comparison is always false due to limited range of data type");
3153 	  if (val == truthvalue_true_node)
3154 	    warning_at (loc, OPT_Wtype_limits,
3155 			"comparison is always true due to limited range of data type");
3156 	}
3157 
3158       if (val != 0)
3159 	{
3160 	  /* Don't forget to evaluate PRIMOP0 if it has side effects.  */
3161 	  if (TREE_SIDE_EFFECTS (primop0))
3162 	    return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
3163 	  return val;
3164 	}
3165 
3166       /* Value is not predetermined, but do the comparison
3167 	 in the type of the operand that is not constant.
3168 	 TYPE is already properly set.  */
3169     }
3170 
3171   /* If either arg is decimal float and the other is float, find the
3172      proper common type to use for comparison.  */
3173   else if (real1 && real2
3174 	   && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3175 	   && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
3176     type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3177 
3178   /* If either arg is decimal float and the other is float, fail.  */
3179   else if (real1 && real2
3180 	   && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3181 	       || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
3182     {
3183       type = *restype_ptr;
3184       primop0 = op0;
3185       primop1 = op1;
3186     }
3187 
3188   else if (real1 && real2
3189 	   && (TYPE_PRECISION (TREE_TYPE (primop0))
3190 	       == TYPE_PRECISION (TREE_TYPE (primop1))))
3191     type = TREE_TYPE (primop0);
3192 
3193   /* If args' natural types are both narrower than nominal type
3194      and both extend in the same manner, compare them
3195      in the type of the wider arg.
3196      Otherwise must actually extend both to the nominal
3197      common type lest different ways of extending
3198      alter the result.
3199      (eg, (short)-1 == (unsigned short)-1  should be 0.)  */
3200 
3201   else if (unsignedp0 == unsignedp1 && real1 == real2
3202 	   && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
3203 	   && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
3204     {
3205       type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3206       type = c_common_signed_or_unsigned_type (unsignedp0
3207 					       || TYPE_UNSIGNED (*restype_ptr),
3208 					       type);
3209       /* Make sure shorter operand is extended the right way
3210 	 to match the longer operand.  */
3211       primop0
3212 	= convert (c_common_signed_or_unsigned_type (unsignedp0,
3213 						     TREE_TYPE (primop0)),
3214 		   primop0);
3215       primop1
3216 	= convert (c_common_signed_or_unsigned_type (unsignedp1,
3217 						     TREE_TYPE (primop1)),
3218 		   primop1);
3219     }
3220   else
3221     {
3222       /* Here we must do the comparison on the nominal type
3223 	 using the args exactly as we received them.  */
3224       type = *restype_ptr;
3225       primop0 = op0;
3226       primop1 = op1;
3227 
3228       /* We want to fold unsigned comparisons of >= and < against zero.
3229 	 For these, we may also issue a warning if we have a non-constant
3230 	 compared against zero, where the zero was spelled as "0" (rather
3231 	 than merely folding to it).
3232 	 If we have at least one constant, then op1 is constant
3233 	 and we may have a non-constant expression as op0.  */
3234       if (!real1 && !real2 && integer_zerop (primop1)
3235 	  && TYPE_UNSIGNED (*restype_ptr))
3236 	{
3237 	  tree value = NULL_TREE;
3238 	  /* All unsigned values are >= 0, so we warn.  However,
3239 	     if OP0 is a constant that is >= 0, the signedness of
3240 	     the comparison isn't an issue, so suppress the
3241 	     warning.  */
3242 	  tree folded_op0 = fold_for_warn (op0);
3243 	  bool warn =
3244 	    warn_type_limits && !in_system_header_at (loc)
3245 	    && !(TREE_CODE (folded_op0) == INTEGER_CST
3246 		 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3247 					     folded_op0)))
3248 	    /* Do not warn for enumeration types.  */
3249 	    && (TREE_CODE (expr_original_type (folded_op0)) != ENUMERAL_TYPE);
3250 
3251 	  switch (code)
3252 	    {
3253 	    case GE_EXPR:
3254 	      if (warn)
3255 		warning_at (loc, OPT_Wtype_limits,
3256 			    "comparison of unsigned expression in %<>= 0%> "
3257 			    "is always true");
3258 	      value = truthvalue_true_node;
3259 	      break;
3260 
3261 	    case LT_EXPR:
3262 	      if (warn)
3263 		warning_at (loc, OPT_Wtype_limits,
3264 			    "comparison of unsigned expression in %<< 0%> "
3265 			    "is always false");
3266 	      value = truthvalue_false_node;
3267 	      break;
3268 
3269 	    default:
3270 	      break;
3271 	    }
3272 
3273 	  if (value != NULL_TREE)
3274 	    {
3275 	      /* Don't forget to evaluate PRIMOP0 if it has side effects.  */
3276 	      if (TREE_SIDE_EFFECTS (primop0))
3277 		return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3278 			       primop0, value);
3279 	      return value;
3280 	    }
3281 	}
3282     }
3283 
3284   *op0_ptr = convert (type, primop0);
3285   *op1_ptr = convert (type, primop1);
3286 
3287   *restype_ptr = truthvalue_type_node;
3288 
3289   return NULL_TREE;
3290 }
3291 
3292 /* Return a tree for the sum or difference (RESULTCODE says which)
3293    of pointer PTROP and integer INTOP.  */
3294 
3295 tree
pointer_int_sum(location_t loc,enum tree_code resultcode,tree ptrop,tree intop,bool complain)3296 pointer_int_sum (location_t loc, enum tree_code resultcode,
3297 		 tree ptrop, tree intop, bool complain)
3298 {
3299   tree size_exp, ret;
3300 
3301   /* The result is a pointer of the same type that is being added.  */
3302   tree result_type = TREE_TYPE (ptrop);
3303 
3304   if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
3305     {
3306       if (complain && warn_pointer_arith)
3307 	pedwarn (loc, OPT_Wpointer_arith,
3308 		 "pointer of type %<void *%> used in arithmetic");
3309       else if (!complain)
3310 	return error_mark_node;
3311       size_exp = integer_one_node;
3312     }
3313   else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3314     {
3315       if (complain && warn_pointer_arith)
3316 	pedwarn (loc, OPT_Wpointer_arith,
3317 		 "pointer to a function used in arithmetic");
3318       else if (!complain)
3319 	return error_mark_node;
3320       size_exp = integer_one_node;
3321     }
3322   else if (!verify_type_context (loc, TCTX_POINTER_ARITH,
3323 				 TREE_TYPE (result_type)))
3324     size_exp = integer_one_node;
3325   else
3326     {
3327       if (!complain && !COMPLETE_TYPE_P (TREE_TYPE (result_type)))
3328 	return error_mark_node;
3329       size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3330       /* Wrap the pointer expression in a SAVE_EXPR to make sure it
3331 	 is evaluated first when the size expression may depend
3332 	 on it for VM types.  */
3333       if (TREE_SIDE_EFFECTS (size_exp)
3334 	  && TREE_SIDE_EFFECTS (ptrop)
3335 	  && variably_modified_type_p (TREE_TYPE (ptrop), NULL))
3336 	{
3337 	  ptrop = save_expr (ptrop);
3338 	  size_exp = build2 (COMPOUND_EXPR, TREE_TYPE (intop), ptrop, size_exp);
3339 	}
3340     }
3341 
3342   /* We are manipulating pointer values, so we don't need to warn
3343      about relying on undefined signed overflow.  We disable the
3344      warning here because we use integer types so fold won't know that
3345      they are really pointers.  */
3346   fold_defer_overflow_warnings ();
3347 
3348   /* If what we are about to multiply by the size of the elements
3349      contains a constant term, apply distributive law
3350      and multiply that constant term separately.
3351      This helps produce common subexpressions.  */
3352   if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3353       && !TREE_CONSTANT (intop)
3354       && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3355       && TREE_CONSTANT (size_exp)
3356       /* If the constant comes from pointer subtraction,
3357 	 skip this optimization--it would cause an error.  */
3358       && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3359       /* If the constant is unsigned, and smaller than the pointer size,
3360 	 then we must skip this optimization.  This is because it could cause
3361 	 an overflow error if the constant is negative but INTOP is not.  */
3362       && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (intop))
3363 	  || (TYPE_PRECISION (TREE_TYPE (intop))
3364 	      == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3365     {
3366       enum tree_code subcode = resultcode;
3367       tree int_type = TREE_TYPE (intop);
3368       if (TREE_CODE (intop) == MINUS_EXPR)
3369 	subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3370       /* Convert both subexpression types to the type of intop,
3371 	 because weird cases involving pointer arithmetic
3372 	 can result in a sum or difference with different type args.  */
3373       ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3374 			       subcode, ptrop,
3375 			       convert (int_type, TREE_OPERAND (intop, 1)),
3376 			       true);
3377       intop = convert (int_type, TREE_OPERAND (intop, 0));
3378     }
3379 
3380   /* Convert the integer argument to a type the same size as sizetype
3381      so the multiply won't overflow spuriously.  */
3382   if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3383       || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3384     intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3385 					     TYPE_UNSIGNED (sizetype)), intop);
3386 
3387   /* Replace the integer argument with a suitable product by the object size.
3388      Do this multiplication as signed, then convert to the appropriate type
3389      for the pointer operation and disregard an overflow that occurred only
3390      because of the sign-extension change in the latter conversion.  */
3391   {
3392     tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3393 			      convert (TREE_TYPE (intop), size_exp));
3394     intop = convert (sizetype, t);
3395     if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3396       intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3397   }
3398 
3399   /* Create the sum or difference.  */
3400   if (resultcode == MINUS_EXPR)
3401     intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3402 
3403   ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3404 
3405   fold_undefer_and_ignore_overflow_warnings ();
3406 
3407   return ret;
3408 }
3409 
3410 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3411    and if NON_CONST is known not to be permitted in an evaluated part
3412    of a constant expression.  */
3413 
3414 tree
c_wrap_maybe_const(tree expr,bool non_const)3415 c_wrap_maybe_const (tree expr, bool non_const)
3416 {
3417   location_t loc = EXPR_LOCATION (expr);
3418 
3419   /* This should never be called for C++.  */
3420   if (c_dialect_cxx ())
3421     gcc_unreachable ();
3422 
3423   /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING.  */
3424   STRIP_TYPE_NOPS (expr);
3425   expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3426   C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3427   protected_set_expr_location (expr, loc);
3428 
3429   return expr;
3430 }
3431 
3432 /* Return whether EXPR is a declaration whose address can never be NULL.
3433    The address of the first struct member could be NULL only if it were
3434    accessed through a NULL pointer, and such an access would be invalid.
3435    The address of a weak symbol may be null unless it has a definition.  */
3436 
3437 bool
decl_with_nonnull_addr_p(const_tree expr)3438 decl_with_nonnull_addr_p (const_tree expr)
3439 {
3440   if (!DECL_P (expr))
3441     return false;
3442 
3443   if (TREE_CODE (expr) == FIELD_DECL
3444       || TREE_CODE (expr) == PARM_DECL
3445       || TREE_CODE (expr) == LABEL_DECL)
3446     return true;
3447 
3448   if (!VAR_OR_FUNCTION_DECL_P (expr))
3449     return false;
3450 
3451   if (!DECL_WEAK (expr))
3452     /* Ordinary (non-weak) symbols have nonnull addresses.  */
3453     return true;
3454 
3455   if (DECL_INITIAL (expr) && DECL_INITIAL (expr) != error_mark_node)
3456     /* Initialized weak symbols have nonnull addresses.  */
3457     return true;
3458 
3459   if (DECL_EXTERNAL (expr) || !TREE_STATIC (expr))
3460     /* Uninitialized extern weak symbols and weak symbols with no
3461        allocated storage might have a null address.  */
3462     return false;
3463 
3464   tree attribs = DECL_ATTRIBUTES (expr);
3465   if (lookup_attribute ("weakref", attribs))
3466     /* Weakref symbols might have a null address unless their referent
3467        is known not to.  Don't bother following weakref targets here.  */
3468     return false;
3469 
3470   return true;
3471 }
3472 
3473 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3474    or for an `if' or `while' statement or ?..: exp.  It should already
3475    have been validated to be of suitable type; otherwise, a bad
3476    diagnostic may result.
3477 
3478    The EXPR is located at LOCATION.
3479 
3480    This preparation consists of taking the ordinary
3481    representation of an expression expr and producing a valid tree
3482    boolean expression describing whether expr is nonzero.  We could
3483    simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3484    but we optimize comparisons, &&, ||, and !.
3485 
3486    The resulting type should always be `truthvalue_type_node'.  */
3487 
3488 tree
c_common_truthvalue_conversion(location_t location,tree expr)3489 c_common_truthvalue_conversion (location_t location, tree expr)
3490 {
3491   STRIP_ANY_LOCATION_WRAPPER (expr);
3492   switch (TREE_CODE (expr))
3493     {
3494     case EQ_EXPR:   case NE_EXPR:   case UNEQ_EXPR: case LTGT_EXPR:
3495     case LE_EXPR:   case GE_EXPR:   case LT_EXPR:   case GT_EXPR:
3496     case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3497     case ORDERED_EXPR: case UNORDERED_EXPR:
3498       if (TREE_TYPE (expr) == truthvalue_type_node)
3499 	return expr;
3500       expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3501 		     TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3502       goto ret;
3503 
3504     case TRUTH_ANDIF_EXPR:
3505     case TRUTH_ORIF_EXPR:
3506     case TRUTH_AND_EXPR:
3507     case TRUTH_OR_EXPR:
3508     case TRUTH_XOR_EXPR:
3509       if (TREE_TYPE (expr) == truthvalue_type_node)
3510 	return expr;
3511       expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3512 		     c_common_truthvalue_conversion (location,
3513 						     TREE_OPERAND (expr, 0)),
3514 		     c_common_truthvalue_conversion (location,
3515 						     TREE_OPERAND (expr, 1)));
3516       goto ret;
3517 
3518     case TRUTH_NOT_EXPR:
3519       if (TREE_TYPE (expr) == truthvalue_type_node)
3520 	return expr;
3521       expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3522 		     c_common_truthvalue_conversion (location,
3523 						     TREE_OPERAND (expr, 0)));
3524       goto ret;
3525 
3526     case ERROR_MARK:
3527       return expr;
3528 
3529     case INTEGER_CST:
3530       if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3531 	  && !integer_zerop (expr)
3532 	  && !integer_onep (expr))
3533 	warning_at (location, OPT_Wint_in_bool_context,
3534 		    "enum constant in boolean context");
3535       return integer_zerop (expr) ? truthvalue_false_node
3536 				  : truthvalue_true_node;
3537 
3538     case REAL_CST:
3539       return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3540 	     ? truthvalue_true_node
3541 	     : truthvalue_false_node;
3542 
3543     case FIXED_CST:
3544       return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3545 			    &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3546 	     ? truthvalue_true_node
3547 	     : truthvalue_false_node;
3548 
3549     case FUNCTION_DECL:
3550       expr = build_unary_op (location, ADDR_EXPR, expr, false);
3551       /* Fall through.  */
3552 
3553     case ADDR_EXPR:
3554       {
3555  	tree inner = TREE_OPERAND (expr, 0);
3556 	if (decl_with_nonnull_addr_p (inner)
3557 	    /* Check both EXPR and INNER for suppression.  */
3558 	    && !warning_suppressed_p (expr, OPT_Waddress)
3559 	    && !warning_suppressed_p (inner, OPT_Waddress))
3560 	  {
3561 	    /* Common Ada programmer's mistake.	 */
3562 	    warning_at (location,
3563 			OPT_Waddress,
3564 			"the address of %qD will always evaluate as %<true%>",
3565 			inner);
3566 	    suppress_warning (inner, OPT_Waddress);
3567 	    return truthvalue_true_node;
3568 	  }
3569 	break;
3570       }
3571 
3572     case COMPLEX_EXPR:
3573       expr = build_binary_op (EXPR_LOCATION (expr),
3574 			      (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3575 			       ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3576 		c_common_truthvalue_conversion (location,
3577 						TREE_OPERAND (expr, 0)),
3578 		c_common_truthvalue_conversion (location,
3579 						TREE_OPERAND (expr, 1)),
3580 			      false);
3581       goto ret;
3582 
3583     case NEGATE_EXPR:
3584     case ABS_EXPR:
3585     case ABSU_EXPR:
3586     case FLOAT_EXPR:
3587     case EXCESS_PRECISION_EXPR:
3588       /* These don't change whether an object is nonzero or zero.  */
3589       return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3590 
3591     case LROTATE_EXPR:
3592     case RROTATE_EXPR:
3593       /* These don't change whether an object is zero or nonzero, but
3594 	 we can't ignore them if their second arg has side-effects.  */
3595       if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3596 	{
3597 	  expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3598 			 TREE_OPERAND (expr, 1),
3599 			 c_common_truthvalue_conversion
3600 			 (location, TREE_OPERAND (expr, 0)));
3601 	  goto ret;
3602 	}
3603       else
3604 	return c_common_truthvalue_conversion (location,
3605 					       TREE_OPERAND (expr, 0));
3606 
3607     case MULT_EXPR:
3608       warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3609 		  "%<*%> in boolean context, suggest %<&&%> instead");
3610       break;
3611 
3612     case LSHIFT_EXPR:
3613       /* We will only warn on signed shifts here, because the majority of
3614 	 false positive warnings happen in code where unsigned arithmetic
3615 	 was used in anticipation of a possible overflow.
3616 	 Furthermore, if we see an unsigned type here we know that the
3617 	 result of the shift is not subject to integer promotion rules.  */
3618       if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3619 	  && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3620 	warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3621 		    "%<<<%> in boolean context, did you mean %<<%>?");
3622       break;
3623 
3624     case COND_EXPR:
3625       if (warn_int_in_bool_context
3626 	  && !from_macro_definition_at (EXPR_LOCATION (expr)))
3627 	{
3628 	  tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3629 	  tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3630 	  if (TREE_CODE (val1) == INTEGER_CST
3631 	      && TREE_CODE (val2) == INTEGER_CST
3632 	      && !integer_zerop (val1)
3633 	      && !integer_zerop (val2)
3634 	      && (!integer_onep (val1)
3635 		  || !integer_onep (val2)))
3636 	    warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3637 			"%<?:%> using integer constants in boolean context, "
3638 			"the expression will always evaluate to %<true%>");
3639 	  else if ((TREE_CODE (val1) == INTEGER_CST
3640 		    && !integer_zerop (val1)
3641 		    && !integer_onep (val1))
3642 		   || (TREE_CODE (val2) == INTEGER_CST
3643 		       && !integer_zerop (val2)
3644 		       && !integer_onep (val2)))
3645 	    warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3646 			"%<?:%> using integer constants in boolean context");
3647 	}
3648       /* Distribute the conversion into the arms of a COND_EXPR.  */
3649       if (c_dialect_cxx ())
3650 	/* Avoid premature folding.  */
3651 	break;
3652       else
3653 	{
3654 	  int w = warn_int_in_bool_context;
3655 	  warn_int_in_bool_context = 0;
3656 	  /* Folding will happen later for C.  */
3657 	  expr = build3 (COND_EXPR, truthvalue_type_node,
3658 			 TREE_OPERAND (expr, 0),
3659 			 c_common_truthvalue_conversion (location,
3660 							 TREE_OPERAND (expr, 1)),
3661 			 c_common_truthvalue_conversion (location,
3662 							 TREE_OPERAND (expr, 2)));
3663 	  warn_int_in_bool_context = w;
3664 	  goto ret;
3665 	}
3666 
3667     CASE_CONVERT:
3668       {
3669 	tree totype = TREE_TYPE (expr);
3670 	tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3671 
3672 	if (POINTER_TYPE_P (totype)
3673 	    && !c_inhibit_evaluation_warnings
3674 	    && TREE_CODE (fromtype) == REFERENCE_TYPE)
3675 	  {
3676 	    tree inner = expr;
3677 	    STRIP_NOPS (inner);
3678 
3679 	    if (DECL_P (inner))
3680 	      warning_at (location,
3681 			  OPT_Waddress,
3682 			  "the compiler can assume that the address of "
3683 			  "%qD will always evaluate to %<true%>",
3684 			  inner);
3685 	  }
3686 
3687 	/* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3688 	   since that affects how `default_conversion' will behave.  */
3689 	if (TREE_CODE (totype) == REFERENCE_TYPE
3690 	    || TREE_CODE (fromtype) == REFERENCE_TYPE)
3691 	  break;
3692 	/* Don't strip a conversion from C++0x scoped enum, since they
3693 	   don't implicitly convert to other types.  */
3694 	if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3695 	    && ENUM_IS_SCOPED (fromtype))
3696 	  break;
3697 	/* If this isn't narrowing the argument, we can ignore it.  */
3698 	if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3699 	  {
3700 	    tree op0 = TREE_OPERAND (expr, 0);
3701 	    if ((TREE_CODE (fromtype) == POINTER_TYPE
3702 		 && TREE_CODE (totype) == INTEGER_TYPE)
3703 		|| warning_suppressed_p (expr, OPT_Waddress))
3704 	      /* Suppress -Waddress for casts to intptr_t, propagating
3705 		 any suppression from the enclosing expression to its
3706 		 operand.  */
3707 	      suppress_warning (op0, OPT_Waddress);
3708 	    return c_common_truthvalue_conversion (location, op0);
3709 	  }
3710       }
3711       break;
3712 
3713     case MODIFY_EXPR:
3714       if (!warning_suppressed_p (expr, OPT_Wparentheses)
3715 	  && warn_parentheses
3716 	  && warning_at (location, OPT_Wparentheses,
3717 			 "suggest parentheses around assignment used as "
3718 			 "truth value"))
3719 	suppress_warning (expr, OPT_Wparentheses);
3720       break;
3721 
3722     case CONST_DECL:
3723       {
3724 	tree folded_expr = fold_for_warn (expr);
3725 	if (folded_expr != expr)
3726 	  return c_common_truthvalue_conversion (location, folded_expr);
3727       }
3728       break;
3729 
3730     default:
3731       break;
3732     }
3733 
3734   if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3735     {
3736       tree t = save_expr (expr);
3737       expr = (build_binary_op
3738 	      (EXPR_LOCATION (expr),
3739 	       (TREE_SIDE_EFFECTS (expr)
3740 		? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3741 	c_common_truthvalue_conversion
3742 	       (location,
3743 		build_unary_op (location, REALPART_EXPR, t, false)),
3744 	c_common_truthvalue_conversion
3745 	       (location,
3746 		build_unary_op (location, IMAGPART_EXPR, t, false)),
3747 	       false));
3748       goto ret;
3749     }
3750 
3751   if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
3752     {
3753       tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3754 					  FCONST0 (TYPE_MODE
3755 						   (TREE_TYPE (expr))));
3756       return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3757     }
3758   else
3759     return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3760 
3761  ret:
3762   protected_set_expr_location (expr, location);
3763   return expr;
3764 }
3765 
3766 static void def_builtin_1  (enum built_in_function fncode,
3767 			    const char *name,
3768 			    enum built_in_class fnclass,
3769 			    tree fntype, tree libtype,
3770 			    bool both_p, bool fallback_p, bool nonansi_p,
3771 			    tree fnattrs, bool implicit_p);
3772 
3773 
3774 /* Apply the TYPE_QUALS to the new DECL.  */
3775 
3776 void
c_apply_type_quals_to_decl(int type_quals,tree decl)3777 c_apply_type_quals_to_decl (int type_quals, tree decl)
3778 {
3779   tree type = TREE_TYPE (decl);
3780 
3781   if (type == error_mark_node)
3782     return;
3783 
3784   if ((type_quals & TYPE_QUAL_CONST)
3785       || (type && TREE_CODE (type) == REFERENCE_TYPE))
3786     /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3787        constructor can produce constant init, so rely on cp_finish_decl to
3788        clear TREE_READONLY if the variable has non-constant init.  */
3789     TREE_READONLY (decl) = 1;
3790   if (type_quals & TYPE_QUAL_VOLATILE)
3791     {
3792       TREE_SIDE_EFFECTS (decl) = 1;
3793       TREE_THIS_VOLATILE (decl) = 1;
3794     }
3795   if (type_quals & TYPE_QUAL_RESTRICT)
3796     {
3797       while (type && TREE_CODE (type) == ARRAY_TYPE)
3798 	/* Allow 'restrict' on arrays of pointers.
3799 	   FIXME currently we just ignore it.  */
3800 	type = TREE_TYPE (type);
3801       if (!type
3802 	  || !POINTER_TYPE_P (type)
3803 	  || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3804 	error ("invalid use of %<restrict%>");
3805     }
3806 }
3807 
3808 /* Return the typed-based alias set for T, which may be an expression
3809    or a type.  Return -1 if we don't do anything special.  */
3810 
3811 alias_set_type
c_common_get_alias_set(tree t)3812 c_common_get_alias_set (tree t)
3813 {
3814   /* For VLAs, use the alias set of the element type rather than the
3815      default of alias set 0 for types compared structurally.  */
3816   if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3817     {
3818       if (TREE_CODE (t) == ARRAY_TYPE)
3819 	return get_alias_set (TREE_TYPE (t));
3820       return -1;
3821     }
3822 
3823   /* That's all the expressions we handle specially.  */
3824   if (!TYPE_P (t))
3825     return -1;
3826 
3827   /* Unlike char, char8_t doesn't alias. */
3828   if (flag_char8_t && t == char8_type_node)
3829     return -1;
3830 
3831   /* The C standard guarantees that any object may be accessed via an
3832      lvalue that has narrow character type (except char8_t).  */
3833   if (t == char_type_node
3834       || t == signed_char_type_node
3835       || t == unsigned_char_type_node)
3836     return 0;
3837 
3838   /* The C standard specifically allows aliasing between signed and
3839      unsigned variants of the same type.  We treat the signed
3840      variant as canonical.  */
3841   if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
3842     {
3843       tree t1 = c_common_signed_type (t);
3844 
3845       /* t1 == t can happen for boolean nodes which are always unsigned.  */
3846       if (t1 != t)
3847 	return get_alias_set (t1);
3848     }
3849 
3850   return -1;
3851 }
3852 
3853 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3854    the IS_SIZEOF parameter indicates which operator is being applied.
3855    The COMPLAIN flag controls whether we should diagnose possibly
3856    ill-formed constructs or not.  LOC is the location of the SIZEOF or
3857    TYPEOF operator.  If MIN_ALIGNOF, the least alignment required for
3858    a type in any context should be returned, rather than the normal
3859    alignment for that type.  */
3860 
3861 tree
c_sizeof_or_alignof_type(location_t loc,tree type,bool is_sizeof,bool min_alignof,int complain)3862 c_sizeof_or_alignof_type (location_t loc,
3863 			  tree type, bool is_sizeof, bool min_alignof,
3864 			  int complain)
3865 {
3866   const char *op_name;
3867   tree value = NULL;
3868   enum tree_code type_code = TREE_CODE (type);
3869 
3870   op_name = is_sizeof ? "sizeof" : "__alignof__";
3871 
3872   if (type_code == FUNCTION_TYPE)
3873     {
3874       if (is_sizeof)
3875 	{
3876 	  if (complain && warn_pointer_arith)
3877 	    pedwarn (loc, OPT_Wpointer_arith,
3878 		     "invalid application of %<sizeof%> to a function type");
3879           else if (!complain)
3880             return error_mark_node;
3881 	  value = size_one_node;
3882 	}
3883       else
3884 	{
3885 	  if (complain)
3886 	    {
3887 	      if (c_dialect_cxx ())
3888 		pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3889 			 "%<alignof%> applied to a function type");
3890 	      else
3891 		pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3892 			 "%<_Alignof%> applied to a function type");
3893 	    }
3894 	  value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3895 	}
3896     }
3897   else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3898     {
3899       if (type_code == VOID_TYPE
3900 	  && complain && warn_pointer_arith)
3901 	pedwarn (loc, OPT_Wpointer_arith,
3902 		 "invalid application of %qs to a void type", op_name);
3903       else if (!complain)
3904         return error_mark_node;
3905       value = size_one_node;
3906     }
3907   else if (!COMPLETE_TYPE_P (type)
3908 	   && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3909     {
3910       if (complain)
3911 	error_at (loc, "invalid application of %qs to incomplete type %qT",
3912 		  op_name, type);
3913       return error_mark_node;
3914     }
3915   else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3916 	   && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3917     {
3918       if (complain)
3919 	error_at (loc, "invalid application of %qs to array type %qT of "
3920 		  "incomplete element type", op_name, type);
3921       return error_mark_node;
3922     }
3923   else if (!verify_type_context (loc, is_sizeof ? TCTX_SIZEOF : TCTX_ALIGNOF,
3924 				 type, !complain))
3925     {
3926       if (!complain)
3927 	return error_mark_node;
3928       value = size_one_node;
3929     }
3930   else
3931     {
3932       if (is_sizeof)
3933 	/* Convert in case a char is more than one unit.  */
3934 	value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3935 				size_int (TYPE_PRECISION (char_type_node)
3936 					  / BITS_PER_UNIT));
3937       else if (min_alignof)
3938 	value = size_int (min_align_of_type (type));
3939       else
3940 	value = size_int (TYPE_ALIGN_UNIT (type));
3941     }
3942 
3943   /* VALUE will have the middle-end integer type sizetype.
3944      However, we should really return a value of type `size_t',
3945      which is just a typedef for an ordinary integer type.  */
3946   value = fold_convert_loc (loc, size_type_node, value);
3947 
3948   return value;
3949 }
3950 
3951 /* Implement the __alignof keyword: Return the minimum required
3952    alignment of EXPR, measured in bytes.  For VAR_DECLs,
3953    FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3954    from an "aligned" __attribute__ specification).  LOC is the
3955    location of the ALIGNOF operator.  */
3956 
3957 tree
c_alignof_expr(location_t loc,tree expr)3958 c_alignof_expr (location_t loc, tree expr)
3959 {
3960   tree t;
3961 
3962   if (!verify_type_context (loc, TCTX_ALIGNOF, TREE_TYPE (expr)))
3963     t = size_one_node;
3964 
3965   else if (VAR_OR_FUNCTION_DECL_P (expr))
3966     t = size_int (DECL_ALIGN_UNIT (expr));
3967 
3968   else if (TREE_CODE (expr) == COMPONENT_REF
3969 	   && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3970     {
3971       error_at (loc, "%<__alignof%> applied to a bit-field");
3972       t = size_one_node;
3973     }
3974   else if (TREE_CODE (expr) == COMPONENT_REF
3975 	   && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3976     t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3977 
3978   else if (INDIRECT_REF_P (expr))
3979     {
3980       tree t = TREE_OPERAND (expr, 0);
3981       tree best = t;
3982       int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3983 
3984       while (CONVERT_EXPR_P (t)
3985 	     && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3986 	{
3987 	  int thisalign;
3988 
3989 	  t = TREE_OPERAND (t, 0);
3990 	  thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3991 	  if (thisalign > bestalign)
3992 	    best = t, bestalign = thisalign;
3993 	}
3994       return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
3995     }
3996   else
3997     return c_alignof (loc, TREE_TYPE (expr));
3998 
3999   return fold_convert_loc (loc, size_type_node, t);
4000 }
4001 
4002 /* Handle C and C++ default attributes.  */
4003 
4004 enum built_in_attribute
4005 {
4006 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
4007 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
4008 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
4009 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
4010 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
4011 #include "builtin-attrs.def"
4012 #undef DEF_ATTR_NULL_TREE
4013 #undef DEF_ATTR_INT
4014 #undef DEF_ATTR_STRING
4015 #undef DEF_ATTR_IDENT
4016 #undef DEF_ATTR_TREE_LIST
4017   ATTR_LAST
4018 };
4019 
4020 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
4021 
4022 static void c_init_attributes (void);
4023 
4024 enum c_builtin_type
4025 {
4026 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
4027 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
4028 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
4029 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
4030 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4031 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4032 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
4033 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4034 			    ARG6) NAME,
4035 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4036 			    ARG6, ARG7) NAME,
4037 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4038 			    ARG6, ARG7, ARG8) NAME,
4039 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4040 			    ARG6, ARG7, ARG8, ARG9) NAME,
4041 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4042 			     ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
4043 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4044 			     ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
4045 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
4046 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
4047 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
4048 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4049 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4050 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4051 				NAME,
4052 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4053 				ARG6) NAME,
4054 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4055 				ARG6, ARG7) NAME,
4056 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
4057 #include "builtin-types.def"
4058 #undef DEF_PRIMITIVE_TYPE
4059 #undef DEF_FUNCTION_TYPE_0
4060 #undef DEF_FUNCTION_TYPE_1
4061 #undef DEF_FUNCTION_TYPE_2
4062 #undef DEF_FUNCTION_TYPE_3
4063 #undef DEF_FUNCTION_TYPE_4
4064 #undef DEF_FUNCTION_TYPE_5
4065 #undef DEF_FUNCTION_TYPE_6
4066 #undef DEF_FUNCTION_TYPE_7
4067 #undef DEF_FUNCTION_TYPE_8
4068 #undef DEF_FUNCTION_TYPE_9
4069 #undef DEF_FUNCTION_TYPE_10
4070 #undef DEF_FUNCTION_TYPE_11
4071 #undef DEF_FUNCTION_TYPE_VAR_0
4072 #undef DEF_FUNCTION_TYPE_VAR_1
4073 #undef DEF_FUNCTION_TYPE_VAR_2
4074 #undef DEF_FUNCTION_TYPE_VAR_3
4075 #undef DEF_FUNCTION_TYPE_VAR_4
4076 #undef DEF_FUNCTION_TYPE_VAR_5
4077 #undef DEF_FUNCTION_TYPE_VAR_6
4078 #undef DEF_FUNCTION_TYPE_VAR_7
4079 #undef DEF_POINTER_TYPE
4080   BT_LAST
4081 };
4082 
4083 typedef enum c_builtin_type builtin_type;
4084 
4085 /* A temporary array for c_common_nodes_and_builtins.  Used in
4086    communication with def_fn_type.  */
4087 static tree builtin_types[(int) BT_LAST + 1];
4088 
4089 /* A helper function for c_common_nodes_and_builtins.  Build function type
4090    for DEF with return type RET and N arguments.  If VAR is true, then the
4091    function should be variadic after those N arguments.
4092 
4093    Takes special care not to ICE if any of the types involved are
4094    error_mark_node, which indicates that said type is not in fact available
4095    (see builtin_type_for_size).  In which case the function type as a whole
4096    should be error_mark_node.  */
4097 
4098 static void
def_fn_type(builtin_type def,builtin_type ret,bool var,int n,...)4099 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
4100 {
4101   tree t;
4102   tree *args = XALLOCAVEC (tree, n);
4103   va_list list;
4104   int i;
4105 
4106   va_start (list, n);
4107   for (i = 0; i < n; ++i)
4108     {
4109       builtin_type a = (builtin_type) va_arg (list, int);
4110       t = builtin_types[a];
4111       if (t == error_mark_node)
4112 	goto egress;
4113       args[i] = t;
4114     }
4115 
4116   t = builtin_types[ret];
4117   if (t == error_mark_node)
4118     goto egress;
4119   if (var)
4120     t = build_varargs_function_type_array (t, n, args);
4121   else
4122     t = build_function_type_array (t, n, args);
4123 
4124  egress:
4125   builtin_types[def] = t;
4126   va_end (list);
4127 }
4128 
4129 /* Build builtin functions common to both C and C++ language
4130    frontends.  */
4131 
4132 static void
c_define_builtins(tree va_list_ref_type_node,tree va_list_arg_type_node)4133 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
4134 {
4135 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
4136   builtin_types[ENUM] = VALUE;
4137 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
4138   def_fn_type (ENUM, RETURN, 0, 0);
4139 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
4140   def_fn_type (ENUM, RETURN, 0, 1, ARG1);
4141 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
4142   def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
4143 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4144   def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
4145 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4146   def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
4147 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5)	\
4148   def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4149 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4150 			    ARG6)					\
4151   def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4152 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4153 			    ARG6, ARG7)					\
4154   def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4155 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4156 			    ARG6, ARG7, ARG8)				\
4157   def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,	\
4158 	       ARG7, ARG8);
4159 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4160 			    ARG6, ARG7, ARG8, ARG9)			\
4161   def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,	\
4162 	       ARG7, ARG8, ARG9);
4163 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4164 			     ARG6, ARG7, ARG8, ARG9, ARG10)		 \
4165   def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,	 \
4166 	       ARG7, ARG8, ARG9, ARG10);
4167 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4168 			     ARG6, ARG7, ARG8, ARG9, ARG10, ARG11)	 \
4169   def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6,	 \
4170 	       ARG7, ARG8, ARG9, ARG10, ARG11);
4171 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
4172   def_fn_type (ENUM, RETURN, 1, 0);
4173 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
4174   def_fn_type (ENUM, RETURN, 1, 1, ARG1);
4175 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
4176   def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
4177 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4178   def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
4179 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4180   def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
4181 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4182   def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4183 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4184 				ARG6) \
4185   def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4186 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4187 				ARG6, ARG7)				\
4188   def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4189 #define DEF_POINTER_TYPE(ENUM, TYPE) \
4190   builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
4191 
4192 #include "builtin-types.def"
4193 
4194 #undef DEF_PRIMITIVE_TYPE
4195 #undef DEF_FUNCTION_TYPE_0
4196 #undef DEF_FUNCTION_TYPE_1
4197 #undef DEF_FUNCTION_TYPE_2
4198 #undef DEF_FUNCTION_TYPE_3
4199 #undef DEF_FUNCTION_TYPE_4
4200 #undef DEF_FUNCTION_TYPE_5
4201 #undef DEF_FUNCTION_TYPE_6
4202 #undef DEF_FUNCTION_TYPE_7
4203 #undef DEF_FUNCTION_TYPE_8
4204 #undef DEF_FUNCTION_TYPE_9
4205 #undef DEF_FUNCTION_TYPE_10
4206 #undef DEF_FUNCTION_TYPE_11
4207 #undef DEF_FUNCTION_TYPE_VAR_0
4208 #undef DEF_FUNCTION_TYPE_VAR_1
4209 #undef DEF_FUNCTION_TYPE_VAR_2
4210 #undef DEF_FUNCTION_TYPE_VAR_3
4211 #undef DEF_FUNCTION_TYPE_VAR_4
4212 #undef DEF_FUNCTION_TYPE_VAR_5
4213 #undef DEF_FUNCTION_TYPE_VAR_6
4214 #undef DEF_FUNCTION_TYPE_VAR_7
4215 #undef DEF_POINTER_TYPE
4216   builtin_types[(int) BT_LAST] = NULL_TREE;
4217 
4218   c_init_attributes ();
4219 
4220 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
4221 		    NONANSI_P, ATTRS, IMPLICIT, COND)			\
4222   if (NAME && COND)							\
4223     def_builtin_1 (ENUM, NAME, CLASS,                                   \
4224 		   builtin_types[(int) TYPE],                           \
4225 		   builtin_types[(int) LIBTYPE],                        \
4226 		   BOTH_P, FALLBACK_P, NONANSI_P,                       \
4227 		   built_in_attributes[(int) ATTRS], IMPLICIT);
4228 #include "builtins.def"
4229 
4230   targetm.init_builtins ();
4231 
4232   build_common_builtin_nodes ();
4233 }
4234 
4235 /* Like get_identifier, but avoid warnings about null arguments when
4236    the argument may be NULL for targets where GCC lacks stdint.h type
4237    information.  */
4238 
4239 static inline tree
c_get_ident(const char * id)4240 c_get_ident (const char *id)
4241 {
4242   return get_identifier (id);
4243 }
4244 
4245 /* Build tree nodes and builtin functions common to both C and C++ language
4246    frontends.  */
4247 
4248 void
c_common_nodes_and_builtins(void)4249 c_common_nodes_and_builtins (void)
4250 {
4251   int char8_type_size;
4252   int char16_type_size;
4253   int char32_type_size;
4254   int wchar_type_size;
4255   tree array_domain_type;
4256   tree va_list_ref_type_node;
4257   tree va_list_arg_type_node;
4258   int i;
4259 
4260   build_common_tree_nodes (flag_signed_char);
4261 
4262   /* Define `int' and `char' first so that dbx will output them first.  */
4263   record_builtin_type (RID_INT, NULL, integer_type_node);
4264   record_builtin_type (RID_CHAR, "char", char_type_node);
4265 
4266   /* `signed' is the same as `int'.  FIXME: the declarations of "signed",
4267      "unsigned long", "long long unsigned" and "unsigned short" were in C++
4268      but not C.  Are the conditionals here needed?  */
4269   if (c_dialect_cxx ())
4270     record_builtin_type (RID_SIGNED, NULL, integer_type_node);
4271   record_builtin_type (RID_LONG, "long int", long_integer_type_node);
4272   record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
4273   record_builtin_type (RID_MAX, "long unsigned int",
4274 		       long_unsigned_type_node);
4275 
4276   for (i = 0; i < NUM_INT_N_ENTS; i ++)
4277     {
4278       char name[25];
4279 
4280       sprintf (name, "__int%d", int_n_data[i].bitsize);
4281       record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4282 			   int_n_trees[i].signed_type);
4283       sprintf (name, "__int%d__", int_n_data[i].bitsize);
4284       record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4285 			   int_n_trees[i].signed_type);
4286       ridpointers[RID_FIRST_INT_N + i]
4287 	= DECL_NAME (TYPE_NAME (int_n_trees[i].signed_type));
4288 
4289       sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
4290       record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4291       sprintf (name, "__int%d__ unsigned", int_n_data[i].bitsize);
4292       record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4293     }
4294 
4295   if (c_dialect_cxx ())
4296     record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
4297   record_builtin_type (RID_MAX, "long long int",
4298 		       long_long_integer_type_node);
4299   record_builtin_type (RID_MAX, "long long unsigned int",
4300 		       long_long_unsigned_type_node);
4301   if (c_dialect_cxx ())
4302     record_builtin_type (RID_MAX, "long long unsigned",
4303 			 long_long_unsigned_type_node);
4304   record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4305   record_builtin_type (RID_MAX, "short unsigned int",
4306 		       short_unsigned_type_node);
4307   if (c_dialect_cxx ())
4308     record_builtin_type (RID_MAX, "unsigned short",
4309 			 short_unsigned_type_node);
4310 
4311   /* Define both `signed char' and `unsigned char'.  */
4312   record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4313   record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4314 
4315   /* These are types that c_common_type_for_size and
4316      c_common_type_for_mode use.  */
4317   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4318 					 TYPE_DECL, NULL_TREE,
4319 					 intQI_type_node));
4320   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4321 					 TYPE_DECL, NULL_TREE,
4322 					 intHI_type_node));
4323   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4324 					 TYPE_DECL, NULL_TREE,
4325 					 intSI_type_node));
4326   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4327 					 TYPE_DECL, NULL_TREE,
4328 					 intDI_type_node));
4329 #if HOST_BITS_PER_WIDE_INT >= 64
4330   /* Note that this is different than the __int128 type that's part of
4331      the generic __intN support.  */
4332   if (targetm.scalar_mode_supported_p (TImode))
4333     lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4334 					   TYPE_DECL,
4335 					   get_identifier ("__int128_t"),
4336 					   intTI_type_node));
4337 #endif
4338   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4339 					 TYPE_DECL, NULL_TREE,
4340 					 unsigned_intQI_type_node));
4341   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4342 					 TYPE_DECL, NULL_TREE,
4343 					 unsigned_intHI_type_node));
4344   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4345 					 TYPE_DECL, NULL_TREE,
4346 					 unsigned_intSI_type_node));
4347   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4348 					 TYPE_DECL, NULL_TREE,
4349 					 unsigned_intDI_type_node));
4350 #if HOST_BITS_PER_WIDE_INT >= 64
4351   if (targetm.scalar_mode_supported_p (TImode))
4352     lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4353 					   TYPE_DECL,
4354 					   get_identifier ("__uint128_t"),
4355 					   unsigned_intTI_type_node));
4356 #endif
4357 
4358   /* Create the widest literal types.  */
4359   if (targetm.scalar_mode_supported_p (TImode))
4360     {
4361       widest_integer_literal_type_node = intTI_type_node;
4362       widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4363     }
4364   else
4365     {
4366       widest_integer_literal_type_node = intDI_type_node;
4367       widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4368     }
4369 
4370   signed_size_type_node = c_common_signed_type (size_type_node);
4371 
4372   pid_type_node =
4373     TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4374 
4375   record_builtin_type (RID_FLOAT, NULL, float_type_node);
4376   record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4377   record_builtin_type (RID_MAX, "long double", long_double_type_node);
4378 
4379   if (!c_dialect_cxx ())
4380     for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4381       if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4382 	record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4383 			     FLOATN_NX_TYPE_NODE (i));
4384 
4385   /* Only supported decimal floating point extension if the target
4386      actually supports underlying modes. */
4387   if (targetm.scalar_mode_supported_p (SDmode)
4388       && targetm.scalar_mode_supported_p (DDmode)
4389       && targetm.scalar_mode_supported_p (TDmode))
4390     {
4391       record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4392       record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4393       record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4394     }
4395 
4396   if (targetm.fixed_point_supported_p ())
4397     {
4398       record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4399       record_builtin_type (RID_FRACT, NULL, fract_type_node);
4400       record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4401       record_builtin_type (RID_MAX, "long long _Fract",
4402 			   long_long_fract_type_node);
4403       record_builtin_type (RID_MAX, "unsigned short _Fract",
4404 			   unsigned_short_fract_type_node);
4405       record_builtin_type (RID_MAX, "unsigned _Fract",
4406 			   unsigned_fract_type_node);
4407       record_builtin_type (RID_MAX, "unsigned long _Fract",
4408 			   unsigned_long_fract_type_node);
4409       record_builtin_type (RID_MAX, "unsigned long long _Fract",
4410 			   unsigned_long_long_fract_type_node);
4411       record_builtin_type (RID_MAX, "_Sat short _Fract",
4412 			   sat_short_fract_type_node);
4413       record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4414       record_builtin_type (RID_MAX, "_Sat long _Fract",
4415 			   sat_long_fract_type_node);
4416       record_builtin_type (RID_MAX, "_Sat long long _Fract",
4417 			   sat_long_long_fract_type_node);
4418       record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4419 			   sat_unsigned_short_fract_type_node);
4420       record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4421 			   sat_unsigned_fract_type_node);
4422       record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4423 			   sat_unsigned_long_fract_type_node);
4424       record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4425 			   sat_unsigned_long_long_fract_type_node);
4426       record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4427       record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4428       record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4429       record_builtin_type (RID_MAX, "long long _Accum",
4430 			   long_long_accum_type_node);
4431       record_builtin_type (RID_MAX, "unsigned short _Accum",
4432 			   unsigned_short_accum_type_node);
4433       record_builtin_type (RID_MAX, "unsigned _Accum",
4434 			   unsigned_accum_type_node);
4435       record_builtin_type (RID_MAX, "unsigned long _Accum",
4436 			   unsigned_long_accum_type_node);
4437       record_builtin_type (RID_MAX, "unsigned long long _Accum",
4438 			   unsigned_long_long_accum_type_node);
4439       record_builtin_type (RID_MAX, "_Sat short _Accum",
4440 			   sat_short_accum_type_node);
4441       record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4442       record_builtin_type (RID_MAX, "_Sat long _Accum",
4443 			   sat_long_accum_type_node);
4444       record_builtin_type (RID_MAX, "_Sat long long _Accum",
4445 			  sat_long_long_accum_type_node);
4446       record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4447 			   sat_unsigned_short_accum_type_node);
4448       record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4449 			   sat_unsigned_accum_type_node);
4450       record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4451 			   sat_unsigned_long_accum_type_node);
4452       record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4453 			   sat_unsigned_long_long_accum_type_node);
4454 
4455     }
4456 
4457   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4458 					 TYPE_DECL,
4459 					 get_identifier ("complex int"),
4460 					 complex_integer_type_node));
4461   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4462 					 TYPE_DECL,
4463 					 get_identifier ("complex float"),
4464 					 complex_float_type_node));
4465   lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4466 					 TYPE_DECL,
4467 					 get_identifier ("complex double"),
4468 					 complex_double_type_node));
4469   lang_hooks.decls.pushdecl
4470     (build_decl (UNKNOWN_LOCATION,
4471 		 TYPE_DECL, get_identifier ("complex long double"),
4472 		 complex_long_double_type_node));
4473 
4474   if (!c_dialect_cxx ())
4475     for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4476       if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4477 	{
4478 	  char buf[30];
4479 	  sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4480 		   floatn_nx_types[i].extended ? "x" : "");
4481 	  lang_hooks.decls.pushdecl
4482 	    (build_decl (UNKNOWN_LOCATION,
4483 			 TYPE_DECL,
4484 			 get_identifier (buf),
4485 			 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4486 	}
4487 
4488   /* Make fileptr_type_node a distinct void * type until
4489      FILE type is defined.  Likewise for const struct tm*.  */
4490   for (unsigned i = 0;
4491        i < sizeof (builtin_structptr_types) / sizeof (builtin_structptr_type);
4492        ++i)
4493     builtin_structptr_types[i].node
4494       = build_variant_type_copy (builtin_structptr_types[i].base);
4495 
4496   record_builtin_type (RID_VOID, NULL, void_type_node);
4497 
4498   /* Set the TYPE_NAME for any variants that were built before
4499      record_builtin_type gave names to the built-in types. */
4500   {
4501     tree void_name = TYPE_NAME (void_type_node);
4502     TYPE_NAME (void_type_node) = NULL_TREE;
4503     TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4504       = void_name;
4505     TYPE_NAME (void_type_node) = void_name;
4506   }
4507 
4508   void_list_node = build_void_list_node ();
4509 
4510   /* Make a type to be the domain of a few array types
4511      whose domains don't really matter.
4512      200 is small enough that it always fits in size_t
4513      and large enough that it can hold most function names for the
4514      initializations of __FUNCTION__ and __PRETTY_FUNCTION__.  */
4515   array_domain_type = build_index_type (size_int (200));
4516 
4517   /* Make a type for arrays of characters.
4518      With luck nothing will ever really depend on the length of this
4519      array type.  */
4520   char_array_type_node
4521     = build_array_type (char_type_node, array_domain_type);
4522 
4523   string_type_node = build_pointer_type (char_type_node);
4524   const_string_type_node
4525     = build_pointer_type (build_qualified_type
4526 			  (char_type_node, TYPE_QUAL_CONST));
4527 
4528   /* This is special for C++ so functions can be overloaded.  */
4529   wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4530   wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4531   wchar_type_size = TYPE_PRECISION (wchar_type_node);
4532   underlying_wchar_type_node = wchar_type_node;
4533   if (c_dialect_cxx ())
4534     {
4535       if (TYPE_UNSIGNED (wchar_type_node))
4536 	wchar_type_node = make_unsigned_type (wchar_type_size);
4537       else
4538 	wchar_type_node = make_signed_type (wchar_type_size);
4539       record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4540     }
4541 
4542   /* This is for wide string constants.  */
4543   wchar_array_type_node
4544     = build_array_type (wchar_type_node, array_domain_type);
4545 
4546   /* Define 'char8_t'.  */
4547   char8_type_node = get_identifier (CHAR8_TYPE);
4548   char8_type_node = TREE_TYPE (identifier_global_value (char8_type_node));
4549   char8_type_size = TYPE_PRECISION (char8_type_node);
4550   if (c_dialect_cxx ())
4551     {
4552       char8_type_node = make_unsigned_type (char8_type_size);
4553 
4554       if (flag_char8_t)
4555         record_builtin_type (RID_CHAR8, "char8_t", char8_type_node);
4556     }
4557 
4558   /* This is for UTF-8 string constants.  */
4559   char8_array_type_node
4560     = build_array_type (char8_type_node, array_domain_type);
4561 
4562   /* Define 'char16_t'.  */
4563   char16_type_node = get_identifier (CHAR16_TYPE);
4564   char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4565   char16_type_size = TYPE_PRECISION (char16_type_node);
4566   if (c_dialect_cxx ())
4567     {
4568       char16_type_node = make_unsigned_type (char16_type_size);
4569 
4570       if (cxx_dialect >= cxx11)
4571 	record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4572     }
4573 
4574   /* This is for UTF-16 string constants.  */
4575   char16_array_type_node
4576     = build_array_type (char16_type_node, array_domain_type);
4577 
4578   /* Define 'char32_t'.  */
4579   char32_type_node = get_identifier (CHAR32_TYPE);
4580   char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4581   char32_type_size = TYPE_PRECISION (char32_type_node);
4582   if (c_dialect_cxx ())
4583     {
4584       char32_type_node = make_unsigned_type (char32_type_size);
4585 
4586       if (cxx_dialect >= cxx11)
4587 	record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4588     }
4589 
4590   /* This is for UTF-32 string constants.  */
4591   char32_array_type_node
4592     = build_array_type (char32_type_node, array_domain_type);
4593 
4594   wint_type_node =
4595     TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4596 
4597   intmax_type_node =
4598     TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4599   uintmax_type_node =
4600     TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4601 
4602   if (SIG_ATOMIC_TYPE)
4603     sig_atomic_type_node =
4604       TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4605   if (INT8_TYPE)
4606     int8_type_node =
4607       TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4608   if (INT16_TYPE)
4609     int16_type_node =
4610       TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4611   if (INT32_TYPE)
4612     int32_type_node =
4613       TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4614   if (INT64_TYPE)
4615     int64_type_node =
4616       TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4617   if (UINT8_TYPE)
4618     uint8_type_node =
4619       TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4620   if (UINT16_TYPE)
4621     c_uint16_type_node = uint16_type_node =
4622       TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4623   if (UINT32_TYPE)
4624     c_uint32_type_node = uint32_type_node =
4625       TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4626   if (UINT64_TYPE)
4627     c_uint64_type_node = uint64_type_node =
4628       TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4629   if (INT_LEAST8_TYPE)
4630     int_least8_type_node =
4631       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4632   if (INT_LEAST16_TYPE)
4633     int_least16_type_node =
4634       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4635   if (INT_LEAST32_TYPE)
4636     int_least32_type_node =
4637       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4638   if (INT_LEAST64_TYPE)
4639     int_least64_type_node =
4640       TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4641   if (UINT_LEAST8_TYPE)
4642     uint_least8_type_node =
4643       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4644   if (UINT_LEAST16_TYPE)
4645     uint_least16_type_node =
4646       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4647   if (UINT_LEAST32_TYPE)
4648     uint_least32_type_node =
4649       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4650   if (UINT_LEAST64_TYPE)
4651     uint_least64_type_node =
4652       TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4653   if (INT_FAST8_TYPE)
4654     int_fast8_type_node =
4655       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4656   if (INT_FAST16_TYPE)
4657     int_fast16_type_node =
4658       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4659   if (INT_FAST32_TYPE)
4660     int_fast32_type_node =
4661       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4662   if (INT_FAST64_TYPE)
4663     int_fast64_type_node =
4664       TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4665   if (UINT_FAST8_TYPE)
4666     uint_fast8_type_node =
4667       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4668   if (UINT_FAST16_TYPE)
4669     uint_fast16_type_node =
4670       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4671   if (UINT_FAST32_TYPE)
4672     uint_fast32_type_node =
4673       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4674   if (UINT_FAST64_TYPE)
4675     uint_fast64_type_node =
4676       TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4677   if (INTPTR_TYPE)
4678     intptr_type_node =
4679       TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4680   if (UINTPTR_TYPE)
4681     uintptr_type_node =
4682       TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4683 
4684   default_function_type
4685     = build_varargs_function_type_list (integer_type_node, NULL_TREE);
4686   unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4687 
4688   lang_hooks.decls.pushdecl
4689     (build_decl (UNKNOWN_LOCATION,
4690 		 TYPE_DECL, get_identifier ("__builtin_va_list"),
4691 		 va_list_type_node));
4692   if (targetm.enum_va_list_p)
4693     {
4694       int l;
4695       const char *pname;
4696       tree ptype;
4697 
4698       for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4699 	{
4700 	  lang_hooks.decls.pushdecl
4701 	    (build_decl (UNKNOWN_LOCATION,
4702 		         TYPE_DECL, get_identifier (pname),
4703 	  	         ptype));
4704 
4705 	}
4706     }
4707 
4708   if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4709     {
4710       va_list_arg_type_node = va_list_ref_type_node =
4711 	build_pointer_type (TREE_TYPE (va_list_type_node));
4712     }
4713   else
4714     {
4715       va_list_arg_type_node = va_list_type_node;
4716       va_list_ref_type_node = build_reference_type (va_list_type_node);
4717     }
4718 
4719   c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4720 
4721   main_identifier_node = get_identifier ("main");
4722 
4723   /* Create the built-in __null node.  It is important that this is
4724      not shared.  */
4725   null_node = make_int_cst (1, 1);
4726   TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4727 
4728   /* Since builtin_types isn't gc'ed, don't export these nodes.  */
4729   memset (builtin_types, 0, sizeof (builtin_types));
4730 }
4731 
4732 /* The number of named compound-literals generated thus far.  */
4733 static GTY(()) int compound_literal_number;
4734 
4735 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal.  */
4736 
4737 void
set_compound_literal_name(tree decl)4738 set_compound_literal_name (tree decl)
4739 {
4740   char *name;
4741   ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4742 			   compound_literal_number);
4743   compound_literal_number++;
4744   DECL_NAME (decl) = get_identifier (name);
4745 }
4746 
4747 /* build_va_arg helper function.  Return a VA_ARG_EXPR with location LOC, type
4748    TYPE and operand OP.  */
4749 
4750 static tree
build_va_arg_1(location_t loc,tree type,tree op)4751 build_va_arg_1 (location_t loc, tree type, tree op)
4752 {
4753   tree expr = build1 (VA_ARG_EXPR, type, op);
4754   SET_EXPR_LOCATION (expr, loc);
4755   return expr;
4756 }
4757 
4758 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4759    va_arg (EXPR, TYPE) at source location LOC.  */
4760 
4761 tree
build_va_arg(location_t loc,tree expr,tree type)4762 build_va_arg (location_t loc, tree expr, tree type)
4763 {
4764   tree va_type = TREE_TYPE (expr);
4765   tree canon_va_type = (va_type == error_mark_node
4766 			? error_mark_node
4767 			: targetm.canonical_va_list_type (va_type));
4768 
4769   if (va_type == error_mark_node
4770       || canon_va_type == NULL_TREE)
4771     {
4772       if (canon_va_type == NULL_TREE)
4773 	error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4774 
4775       /* Let's handle things neutrally, if expr:
4776 	 - has undeclared type, or
4777 	 - is not an va_list type.  */
4778       return build_va_arg_1 (loc, type, error_mark_node);
4779     }
4780 
4781   if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4782     {
4783       /* Case 1: Not an array type.  */
4784 
4785       /* Take the address, to get '&ap'.  Note that &ap is not a va_list
4786 	 type.  */
4787       c_common_mark_addressable_vec (expr);
4788       expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4789 
4790       return build_va_arg_1 (loc, type, expr);
4791     }
4792 
4793   /* Case 2: Array type.
4794 
4795      Background:
4796 
4797      For contrast, let's start with the simple case (case 1).  If
4798      canon_va_type is not an array type, but say a char *, then when
4799      passing-by-value a va_list, the type of the va_list param decl is
4800      the same as for another va_list decl (all ap's are char *):
4801 
4802      f2_1 (char * ap)
4803        D.1815 = VA_ARG (&ap, 0B, 1);
4804        return D.1815;
4805 
4806      f2 (int i)
4807        char * ap.0;
4808        char * ap;
4809        __builtin_va_start (&ap, 0);
4810        ap.0 = ap;
4811        res = f2_1 (ap.0);
4812        __builtin_va_end (&ap);
4813        D.1812 = res;
4814        return D.1812;
4815 
4816      However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4817      va_list the type of the va_list param decl (case 2b, struct * ap) is not
4818      the same as for another va_list decl (case 2a, struct ap[1]).
4819 
4820      f2_1 (struct  * ap)
4821        D.1844 = VA_ARG (ap, 0B, 0);
4822        return D.1844;
4823 
4824      f2 (int i)
4825        struct  ap[1];
4826        __builtin_va_start (&ap, 0);
4827        res = f2_1 (&ap);
4828        __builtin_va_end (&ap);
4829        D.1841 = res;
4830        return D.1841;
4831 
4832      Case 2b is different because:
4833      - on the callee side, the parm decl has declared type va_list, but
4834        grokdeclarator changes the type of the parm decl to a pointer to the
4835        array elem type.
4836      - on the caller side, the pass-by-value uses &ap.
4837 
4838      We unify these two cases (case 2a: va_list is array type,
4839      case 2b: va_list is pointer to array elem type), by adding '&' for the
4840      array type case, such that we have a pointer to array elem in both
4841      cases.  */
4842 
4843   if (TREE_CODE (va_type) == ARRAY_TYPE)
4844     {
4845       /* Case 2a: va_list is array type.  */
4846 
4847       /* Take the address, to get '&ap'.  Make sure it's a pointer to array
4848 	 elem type.  */
4849       c_common_mark_addressable_vec (expr);
4850       expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4851 		     expr);
4852 
4853       /* Verify that &ap is still recognized as having va_list type.  */
4854       tree canon_expr_type
4855 	= targetm.canonical_va_list_type (TREE_TYPE (expr));
4856       gcc_assert (canon_expr_type != NULL_TREE);
4857     }
4858   else
4859     {
4860       /* Case 2b: va_list is pointer to array elem type.  */
4861       gcc_assert (POINTER_TYPE_P (va_type));
4862 
4863       /* Comparison as in std_canonical_va_list_type.  */
4864       gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4865 		  == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4866 
4867       /* Don't take the address.  We've already got '&ap'.  */
4868       ;
4869     }
4870 
4871   return build_va_arg_1 (loc, type, expr);
4872 }
4873 
4874 
4875 /* Linked list of disabled built-in functions.  */
4876 
4877 struct disabled_builtin
4878 {
4879   const char *name;
4880   struct disabled_builtin *next;
4881 };
4882 static disabled_builtin *disabled_builtins = NULL;
4883 
4884 static bool builtin_function_disabled_p (const char *);
4885 
4886 /* Disable a built-in function specified by -fno-builtin-NAME.  If NAME
4887    begins with "__builtin_", give an error.  */
4888 
4889 void
disable_builtin_function(const char * name)4890 disable_builtin_function (const char *name)
4891 {
4892   if (startswith (name, "__builtin_"))
4893     error ("cannot disable built-in function %qs", name);
4894   else
4895     {
4896       disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4897       new_disabled_builtin->name = name;
4898       new_disabled_builtin->next = disabled_builtins;
4899       disabled_builtins = new_disabled_builtin;
4900     }
4901 }
4902 
4903 
4904 /* Return true if the built-in function NAME has been disabled, false
4905    otherwise.  */
4906 
4907 static bool
builtin_function_disabled_p(const char * name)4908 builtin_function_disabled_p (const char *name)
4909 {
4910   disabled_builtin *p;
4911   for (p = disabled_builtins; p != NULL; p = p->next)
4912     {
4913       if (strcmp (name, p->name) == 0)
4914 	return true;
4915     }
4916   return false;
4917 }
4918 
4919 
4920 /* Worker for DEF_BUILTIN.
4921    Possibly define a builtin function with one or two names.
4922    Does not declare a non-__builtin_ function if flag_no_builtin, or if
4923    nonansi_p and flag_no_nonansi_builtin.  */
4924 
4925 static void
def_builtin_1(enum built_in_function fncode,const char * name,enum built_in_class fnclass,tree fntype,tree libtype,bool both_p,bool fallback_p,bool nonansi_p,tree fnattrs,bool implicit_p)4926 def_builtin_1 (enum built_in_function fncode,
4927 	       const char *name,
4928 	       enum built_in_class fnclass,
4929 	       tree fntype, tree libtype,
4930 	       bool both_p, bool fallback_p, bool nonansi_p,
4931 	       tree fnattrs, bool implicit_p)
4932 {
4933   tree decl;
4934   const char *libname;
4935 
4936   if (fntype == error_mark_node)
4937     return;
4938 
4939   gcc_assert ((!both_p && !fallback_p)
4940 	      || startswith (name, "__builtin_"));
4941 
4942   libname = name + strlen ("__builtin_");
4943   decl = add_builtin_function (name, fntype, fncode, fnclass,
4944 			       (fallback_p ? libname : NULL),
4945 			       fnattrs);
4946 
4947   set_builtin_decl (fncode, decl, implicit_p);
4948 
4949   if (both_p
4950       && !flag_no_builtin && !builtin_function_disabled_p (libname)
4951       && !(nonansi_p && flag_no_nonansi_builtin))
4952     add_builtin_function (libname, libtype, fncode, fnclass,
4953 			  NULL, fnattrs);
4954 }
4955 
4956 /* Nonzero if the type T promotes to int.  This is (nearly) the
4957    integral promotions defined in ISO C99 6.3.1.1/2.  */
4958 
4959 bool
c_promoting_integer_type_p(const_tree t)4960 c_promoting_integer_type_p (const_tree t)
4961 {
4962   switch (TREE_CODE (t))
4963     {
4964     case INTEGER_TYPE:
4965       return (TYPE_MAIN_VARIANT (t) == char_type_node
4966 	      || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4967 	      || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4968 	      || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4969 	      || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
4970 	      || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
4971 
4972     case ENUMERAL_TYPE:
4973       /* ??? Technically all enumerations not larger than an int
4974 	 promote to an int.  But this is used along code paths
4975 	 that only want to notice a size change.  */
4976       return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
4977 
4978     case BOOLEAN_TYPE:
4979       return true;
4980 
4981     default:
4982       return false;
4983     }
4984 }
4985 
4986 /* Return 1 if PARMS specifies a fixed number of parameters
4987    and none of their types is affected by default promotions.  */
4988 
4989 bool
self_promoting_args_p(const_tree parms)4990 self_promoting_args_p (const_tree parms)
4991 {
4992   const_tree t;
4993   for (t = parms; t; t = TREE_CHAIN (t))
4994     {
4995       tree type = TREE_VALUE (t);
4996 
4997       if (type == error_mark_node)
4998 	continue;
4999 
5000       if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
5001 	return false;
5002 
5003       if (type == NULL_TREE)
5004 	return false;
5005 
5006       if (TYPE_MAIN_VARIANT (type) == float_type_node)
5007 	return false;
5008 
5009       if (c_promoting_integer_type_p (type))
5010 	return false;
5011     }
5012   return true;
5013 }
5014 
5015 /* Recursively remove any '*' or '&' operator from TYPE.  */
5016 tree
strip_pointer_operator(tree t)5017 strip_pointer_operator (tree t)
5018 {
5019   while (POINTER_TYPE_P (t))
5020     t = TREE_TYPE (t);
5021   return t;
5022 }
5023 
5024 /* Recursively remove pointer or array type from TYPE. */
5025 tree
strip_pointer_or_array_types(tree t)5026 strip_pointer_or_array_types (tree t)
5027 {
5028   while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
5029     t = TREE_TYPE (t);
5030   return t;
5031 }
5032 
5033 /* Used to compare case labels.  K1 and K2 are actually tree nodes
5034    representing case labels, or NULL_TREE for a `default' label.
5035    Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
5036    K2, and 0 if K1 and K2 are equal.  */
5037 
5038 int
case_compare(splay_tree_key k1,splay_tree_key k2)5039 case_compare (splay_tree_key k1, splay_tree_key k2)
5040 {
5041   /* Consider a NULL key (such as arises with a `default' label) to be
5042      smaller than anything else.  */
5043   if (!k1)
5044     return k2 ? -1 : 0;
5045   else if (!k2)
5046     return k1 ? 1 : 0;
5047 
5048   return tree_int_cst_compare ((tree) k1, (tree) k2);
5049 }
5050 
5051 /* Process a case label, located at LOC, for the range LOW_VALUE
5052    ... HIGH_VALUE.  If LOW_VALUE and HIGH_VALUE are both NULL_TREE
5053    then this case label is actually a `default' label.  If only
5054    HIGH_VALUE is NULL_TREE, then case label was declared using the
5055    usual C/C++ syntax, rather than the GNU case range extension.
5056    CASES is a tree containing all the case ranges processed so far;
5057    COND is the condition for the switch-statement itself.
5058    Returns the CASE_LABEL_EXPR created, or ERROR_MARK_NODE if no
5059    CASE_LABEL_EXPR is created.  */
5060 
5061 tree
c_add_case_label(location_t loc,splay_tree cases,tree cond,tree low_value,tree high_value)5062 c_add_case_label (location_t loc, splay_tree cases, tree cond,
5063 		  tree low_value, tree high_value)
5064 {
5065   tree type;
5066   tree label;
5067   tree case_label;
5068   splay_tree_node node;
5069 
5070   /* Create the LABEL_DECL itself.  */
5071   label = create_artificial_label (loc);
5072 
5073   /* If there was an error processing the switch condition, bail now
5074      before we get more confused.  */
5075   if (!cond || cond == error_mark_node)
5076     goto error_out;
5077 
5078   if ((low_value && TREE_TYPE (low_value)
5079        && POINTER_TYPE_P (TREE_TYPE (low_value)))
5080       || (high_value && TREE_TYPE (high_value)
5081 	  && POINTER_TYPE_P (TREE_TYPE (high_value))))
5082     {
5083       error_at (loc, "pointers are not permitted as case values");
5084       goto error_out;
5085     }
5086 
5087   /* Case ranges are a GNU extension.  */
5088   if (high_value)
5089     pedwarn (loc, OPT_Wpedantic,
5090 	     "range expressions in switch statements are non-standard");
5091 
5092   type = TREE_TYPE (cond);
5093   if (low_value)
5094     {
5095       low_value = check_case_value (loc, low_value);
5096       low_value = convert_and_check (loc, type, low_value);
5097       low_value = fold (low_value);
5098       if (low_value == error_mark_node)
5099 	goto error_out;
5100     }
5101   if (high_value)
5102     {
5103       high_value = check_case_value (loc, high_value);
5104       high_value = convert_and_check (loc, type, high_value);
5105       high_value = fold (high_value);
5106       if (high_value == error_mark_node)
5107 	goto error_out;
5108     }
5109 
5110   if (low_value && high_value)
5111     {
5112       /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
5113 	 really a case range, even though it was written that way.
5114 	 Remove the HIGH_VALUE to simplify later processing.  */
5115       if (tree_int_cst_equal (low_value, high_value))
5116 	high_value = NULL_TREE;
5117       else if (!tree_int_cst_lt (low_value, high_value))
5118 	warning_at (loc, 0, "empty range specified");
5119     }
5120 
5121   /* Look up the LOW_VALUE in the table of case labels we already
5122      have.  */
5123   node = splay_tree_lookup (cases, (splay_tree_key) low_value);
5124   /* If there was not an exact match, check for overlapping ranges.
5125      There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
5126      that's a `default' label and the only overlap is an exact match.  */
5127   if (!node && (low_value || high_value))
5128     {
5129       splay_tree_node low_bound;
5130       splay_tree_node high_bound;
5131 
5132       /* Even though there wasn't an exact match, there might be an
5133 	 overlap between this case range and another case range.
5134 	 Since we've (inductively) not allowed any overlapping case
5135 	 ranges, we simply need to find the greatest low case label
5136 	 that is smaller that LOW_VALUE, and the smallest low case
5137 	 label that is greater than LOW_VALUE.  If there is an overlap
5138 	 it will occur in one of these two ranges.  */
5139       low_bound = splay_tree_predecessor (cases,
5140 					  (splay_tree_key) low_value);
5141       high_bound = splay_tree_successor (cases,
5142 					 (splay_tree_key) low_value);
5143 
5144       /* Check to see if the LOW_BOUND overlaps.  It is smaller than
5145 	 the LOW_VALUE, so there is no need to check unless the
5146 	 LOW_BOUND is in fact itself a case range.  */
5147       if (low_bound
5148 	  && CASE_HIGH ((tree) low_bound->value)
5149 	  && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
5150 				    low_value) >= 0)
5151 	node = low_bound;
5152       /* Check to see if the HIGH_BOUND overlaps.  The low end of that
5153 	 range is bigger than the low end of the current range, so we
5154 	 are only interested if the current range is a real range, and
5155 	 not an ordinary case label.  */
5156       else if (high_bound
5157 	       && high_value
5158 	       && (tree_int_cst_compare ((tree) high_bound->key,
5159 					 high_value)
5160 		   <= 0))
5161 	node = high_bound;
5162     }
5163   /* If there was an overlap, issue an error.  */
5164   if (node)
5165     {
5166       tree duplicate = CASE_LABEL ((tree) node->value);
5167 
5168       if (high_value)
5169 	{
5170 	  error_at (loc, "duplicate (or overlapping) case value");
5171 	  inform (DECL_SOURCE_LOCATION (duplicate),
5172 		  "this is the first entry overlapping that value");
5173 	}
5174       else if (low_value)
5175 	{
5176 	  error_at (loc, "duplicate case value") ;
5177 	  inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
5178 	}
5179       else
5180 	{
5181 	  error_at (loc, "multiple default labels in one switch");
5182 	  inform (DECL_SOURCE_LOCATION (duplicate),
5183 		  "this is the first default label");
5184 	}
5185       goto error_out;
5186     }
5187 
5188   /* Add a CASE_LABEL to the statement-tree.  */
5189   case_label = add_stmt (build_case_label (low_value, high_value, label));
5190   /* Register this case label in the splay tree.  */
5191   splay_tree_insert (cases,
5192 		     (splay_tree_key) low_value,
5193 		     (splay_tree_value) case_label);
5194 
5195   return case_label;
5196 
5197  error_out:
5198   /* Add a label so that the back-end doesn't think that the beginning of
5199      the switch is unreachable.  Note that we do not add a case label, as
5200      that just leads to duplicates and thence to failure later on.  */
5201   if (!cases->root)
5202     {
5203       tree t = create_artificial_label (loc);
5204       add_stmt (build_stmt (loc, LABEL_EXPR, t));
5205     }
5206   return error_mark_node;
5207 }
5208 
5209 /* Subroutine of c_switch_covers_all_cases_p, called via
5210    splay_tree_foreach.  Return 1 if it doesn't cover all the cases.
5211    ARGS[0] is initially NULL and after the first iteration is the
5212    so far highest case label.  ARGS[1] is the minimum of SWITCH_COND's
5213    type.  */
5214 
5215 static int
c_switch_covers_all_cases_p_1(splay_tree_node node,void * data)5216 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
5217 {
5218   tree label = (tree) node->value;
5219   tree *args = (tree *) data;
5220 
5221   /* If there is a default case, we shouldn't have called this.  */
5222   gcc_assert (CASE_LOW (label));
5223 
5224   if (args[0] == NULL_TREE)
5225     {
5226       if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
5227 	return 1;
5228     }
5229   else if (wi::add (wi::to_widest (args[0]), 1)
5230 	   != wi::to_widest (CASE_LOW (label)))
5231     return 1;
5232   if (CASE_HIGH (label))
5233     args[0] = CASE_HIGH (label);
5234   else
5235     args[0] = CASE_LOW (label);
5236   return 0;
5237 }
5238 
5239 /* Return true if switch with CASES and switch condition with type
5240    covers all possible values in the case labels.  */
5241 
5242 bool
c_switch_covers_all_cases_p(splay_tree cases,tree type)5243 c_switch_covers_all_cases_p (splay_tree cases, tree type)
5244 {
5245   /* If there is default:, this is always the case.  */
5246   splay_tree_node default_node
5247     = splay_tree_lookup (cases, (splay_tree_key) NULL);
5248   if (default_node)
5249     return true;
5250 
5251   if (!INTEGRAL_TYPE_P (type))
5252     return false;
5253 
5254   tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
5255   if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
5256     return false;
5257 
5258   /* If there are no cases at all, or if the highest case label
5259      is smaller than TYPE_MAX_VALUE, return false.  */
5260   if (args[0] == NULL_TREE
5261       || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
5262     return false;
5263 
5264   return true;
5265 }
5266 
5267 /* Return true if stmt can fall through.  Used by block_may_fallthru
5268    default case.  */
5269 
5270 bool
c_block_may_fallthru(const_tree stmt)5271 c_block_may_fallthru (const_tree stmt)
5272 {
5273   switch (TREE_CODE (stmt))
5274     {
5275     case SWITCH_STMT:
5276       return (!SWITCH_STMT_ALL_CASES_P (stmt)
5277 	      || !SWITCH_STMT_NO_BREAK_P (stmt)
5278 	      || block_may_fallthru (SWITCH_STMT_BODY (stmt)));
5279 
5280     default:
5281       return true;
5282     }
5283 }
5284 
5285 /* Finish an expression taking the address of LABEL (an
5286    IDENTIFIER_NODE).  Returns an expression for the address.
5287 
5288    LOC is the location for the expression returned.  */
5289 
5290 tree
finish_label_address_expr(tree label,location_t loc)5291 finish_label_address_expr (tree label, location_t loc)
5292 {
5293   tree result;
5294 
5295   pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
5296 
5297   if (label == error_mark_node)
5298     return error_mark_node;
5299 
5300   label = lookup_label (label);
5301   if (label == NULL_TREE)
5302     result = null_pointer_node;
5303   else
5304     {
5305       TREE_USED (label) = 1;
5306       result = build1 (ADDR_EXPR, ptr_type_node, label);
5307       /* The current function is not necessarily uninlinable.
5308 	 Computed gotos are incompatible with inlining, but the value
5309 	 here could be used only in a diagnostic, for example.  */
5310       protected_set_expr_location (result, loc);
5311     }
5312 
5313   return result;
5314 }
5315 
5316 
5317 /* Given a boolean expression ARG, return a tree representing an increment
5318    or decrement (as indicated by CODE) of ARG.  The front end must check for
5319    invalid cases (e.g., decrement in C++).  */
5320 tree
boolean_increment(enum tree_code code,tree arg)5321 boolean_increment (enum tree_code code, tree arg)
5322 {
5323   tree val;
5324   tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5325 
5326   arg = stabilize_reference (arg);
5327   switch (code)
5328     {
5329     case PREINCREMENT_EXPR:
5330       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5331       break;
5332     case POSTINCREMENT_EXPR:
5333       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5334       arg = save_expr (arg);
5335       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5336       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5337       break;
5338     case PREDECREMENT_EXPR:
5339       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5340 		    invert_truthvalue_loc (input_location, arg));
5341       break;
5342     case POSTDECREMENT_EXPR:
5343       val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5344 		    invert_truthvalue_loc (input_location, arg));
5345       arg = save_expr (arg);
5346       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5347       val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5348       break;
5349     default:
5350       gcc_unreachable ();
5351     }
5352   TREE_SIDE_EFFECTS (val) = 1;
5353   return val;
5354 }
5355 
5356 /* Built-in macros for stddef.h and stdint.h, that require macros
5357    defined in this file.  */
5358 void
c_stddef_cpp_builtins(void)5359 c_stddef_cpp_builtins(void)
5360 {
5361   builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5362   builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5363   builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5364   builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5365   builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5366   builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5367   if (flag_char8_t)
5368     builtin_define_with_value ("__CHAR8_TYPE__", CHAR8_TYPE, 0);
5369   builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5370   builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5371   if (SIG_ATOMIC_TYPE)
5372     builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5373   if (INT8_TYPE)
5374     builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5375   if (INT16_TYPE)
5376     builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5377   if (INT32_TYPE)
5378     builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5379   if (INT64_TYPE)
5380     builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5381   if (UINT8_TYPE)
5382     builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5383   if (UINT16_TYPE)
5384     builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5385   if (UINT32_TYPE)
5386     builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5387   if (UINT64_TYPE)
5388     builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5389   if (INT_LEAST8_TYPE)
5390     builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5391   if (INT_LEAST16_TYPE)
5392     builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5393   if (INT_LEAST32_TYPE)
5394     builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5395   if (INT_LEAST64_TYPE)
5396     builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5397   if (UINT_LEAST8_TYPE)
5398     builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5399   if (UINT_LEAST16_TYPE)
5400     builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5401   if (UINT_LEAST32_TYPE)
5402     builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5403   if (UINT_LEAST64_TYPE)
5404     builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5405   if (INT_FAST8_TYPE)
5406     builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5407   if (INT_FAST16_TYPE)
5408     builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5409   if (INT_FAST32_TYPE)
5410     builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5411   if (INT_FAST64_TYPE)
5412     builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5413   if (UINT_FAST8_TYPE)
5414     builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5415   if (UINT_FAST16_TYPE)
5416     builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5417   if (UINT_FAST32_TYPE)
5418     builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5419   if (UINT_FAST64_TYPE)
5420     builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5421   if (INTPTR_TYPE)
5422     builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5423   if (UINTPTR_TYPE)
5424     builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5425   /* GIMPLE FE testcases need access to the GCC internal 'sizetype'.
5426      Expose it as __SIZETYPE__.  */
5427   if (flag_gimple)
5428     builtin_define_with_value ("__SIZETYPE__", SIZETYPE, 0);
5429 }
5430 
5431 static void
c_init_attributes(void)5432 c_init_attributes (void)
5433 {
5434   /* Fill in the built_in_attributes array.  */
5435 #define DEF_ATTR_NULL_TREE(ENUM)				\
5436   built_in_attributes[(int) ENUM] = NULL_TREE;
5437 #define DEF_ATTR_INT(ENUM, VALUE)				\
5438   built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5439 #define DEF_ATTR_STRING(ENUM, VALUE)				\
5440   built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5441 #define DEF_ATTR_IDENT(ENUM, STRING)				\
5442   built_in_attributes[(int) ENUM] = get_identifier (STRING);
5443 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN)	\
5444   built_in_attributes[(int) ENUM]			\
5445     = tree_cons (built_in_attributes[(int) PURPOSE],	\
5446 		 built_in_attributes[(int) VALUE],	\
5447 		 built_in_attributes[(int) CHAIN]);
5448 #include "builtin-attrs.def"
5449 #undef DEF_ATTR_NULL_TREE
5450 #undef DEF_ATTR_INT
5451 #undef DEF_ATTR_IDENT
5452 #undef DEF_ATTR_TREE_LIST
5453 }
5454 
5455 /* Check whether the byte alignment ALIGN is a valid user-specified
5456    alignment less than the supported maximum.  If so, return ALIGN's
5457    base-2 log; if not, output an error and return -1.  If OBJFILE
5458    then reject alignments greater than MAX_OFILE_ALIGNMENT when
5459    converted to bits.  Otherwise, consider valid only alignments
5460    that are less than HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT.
5461    Zero is not considered a valid argument (and results in -1 on
5462    return) but it only triggers a warning when WARN_ZERO is set.  */
5463 
5464 int
check_user_alignment(const_tree align,bool objfile,bool warn_zero)5465 check_user_alignment (const_tree align, bool objfile, bool warn_zero)
5466 {
5467   if (error_operand_p (align))
5468     return -1;
5469 
5470   if (TREE_CODE (align) != INTEGER_CST
5471       || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5472     {
5473       error ("requested alignment is not an integer constant");
5474       return -1;
5475     }
5476 
5477   if (integer_zerop (align))
5478     {
5479       if (warn_zero)
5480 	warning (OPT_Wattributes,
5481 		 "requested alignment %qE is not a positive power of 2",
5482 		 align);
5483       return -1;
5484     }
5485 
5486   /* Log2 of the byte alignment ALIGN.  */
5487   int log2align;
5488   if (tree_int_cst_sgn (align) == -1
5489       || (log2align = tree_log2 (align)) == -1)
5490     {
5491       error ("requested alignment %qE is not a positive power of 2",
5492 	     align);
5493       return -1;
5494     }
5495 
5496   if (objfile)
5497     {
5498       unsigned maxalign = MAX_OFILE_ALIGNMENT / BITS_PER_UNIT;
5499       if (!tree_fits_uhwi_p (align) || tree_to_uhwi (align) > maxalign)
5500 	{
5501 	  error ("requested alignment %qE exceeds object file maximum %u",
5502 		 align, maxalign);
5503 	  return -1;
5504 	}
5505     }
5506 
5507   if (log2align >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5508     {
5509       error ("requested alignment %qE exceeds maximum %u",
5510 	     align, 1U << (HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT - 1));
5511       return -1;
5512     }
5513 
5514   return log2align;
5515 }
5516 
5517 /* Determine the ELF symbol visibility for DECL, which is either a
5518    variable or a function.  It is an error to use this function if a
5519    definition of DECL is not available in this translation unit.
5520    Returns true if the final visibility has been determined by this
5521    function; false if the caller is free to make additional
5522    modifications.  */
5523 
5524 bool
c_determine_visibility(tree decl)5525 c_determine_visibility (tree decl)
5526 {
5527   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5528 
5529   /* If the user explicitly specified the visibility with an
5530      attribute, honor that.  DECL_VISIBILITY will have been set during
5531      the processing of the attribute.  We check for an explicit
5532      attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5533      to distinguish the use of an attribute from the use of a "#pragma
5534      GCC visibility push(...)"; in the latter case we still want other
5535      considerations to be able to overrule the #pragma.  */
5536   if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5537       || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5538 	  && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5539 	      || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5540     return true;
5541 
5542   /* Set default visibility to whatever the user supplied with
5543      visibility_specified depending on #pragma GCC visibility.  */
5544   if (!DECL_VISIBILITY_SPECIFIED (decl))
5545     {
5546       if (visibility_options.inpragma
5547 	  || DECL_VISIBILITY (decl) != default_visibility)
5548 	{
5549 	  DECL_VISIBILITY (decl) = default_visibility;
5550 	  DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5551 	  /* If visibility changed and DECL already has DECL_RTL, ensure
5552 	     symbol flags are updated.  */
5553 	  if (((VAR_P (decl) && TREE_STATIC (decl))
5554 	       || TREE_CODE (decl) == FUNCTION_DECL)
5555 	      && DECL_RTL_SET_P (decl))
5556 	    make_decl_rtl (decl);
5557 	}
5558     }
5559   return false;
5560 }
5561 
5562 /* Data to communicate through check_function_arguments_recurse between
5563    check_function_nonnull and check_nonnull_arg.  */
5564 
5565 struct nonnull_arg_ctx
5566 {
5567   /* Location of the call.  */
5568   location_t loc;
5569   /* The function whose arguments are being checked and its type (used
5570      for calls through function pointers).  */
5571   const_tree fndecl, fntype;
5572   /* True if a warning has been issued.  */
5573   bool warned_p;
5574 };
5575 
5576 /* Check the argument list of a function call to CTX.FNDECL of CTX.FNTYPE
5577    for null in argument slots that are marked as requiring a non-null
5578    pointer argument.  The NARGS arguments are passed in the array ARGARRAY.
5579    Return true if we have warned.  */
5580 
5581 static bool
check_function_nonnull(nonnull_arg_ctx & ctx,int nargs,tree * argarray)5582 check_function_nonnull (nonnull_arg_ctx &ctx, int nargs, tree *argarray)
5583 {
5584   int firstarg = 0;
5585   if (TREE_CODE (ctx.fntype) == METHOD_TYPE)
5586     {
5587       bool closure = false;
5588       if (ctx.fndecl)
5589 	{
5590 	  /* For certain lambda expressions the C++ front end emits calls
5591 	     that pass a null this pointer as an argument named __closure
5592 	     to the member operator() of empty function.  Detect those
5593 	     and avoid checking them, but proceed to check the remaining
5594 	     arguments.  */
5595 	  tree arg0 = DECL_ARGUMENTS (ctx.fndecl);
5596 	  if (tree arg0name = DECL_NAME (arg0))
5597 	    closure = id_equal (arg0name, "__closure");
5598 	}
5599 
5600       /* In calls to C++ non-static member functions check the this
5601 	 pointer regardless of whether the function is declared with
5602 	 attribute nonnull.  */
5603       firstarg = 1;
5604       if (!closure)
5605 	check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[0],
5606 					  firstarg, OPT_Wnonnull);
5607     }
5608 
5609   tree attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (ctx.fntype));
5610   if (attrs == NULL_TREE)
5611     return ctx.warned_p;
5612 
5613   tree a = attrs;
5614   /* See if any of the nonnull attributes has no arguments.  If so,
5615      then every pointer argument is checked (in which case the check
5616      for pointer type is done in check_nonnull_arg).  */
5617   if (TREE_VALUE (a) != NULL_TREE)
5618     do
5619       a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5620     while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5621 
5622   if (a != NULL_TREE)
5623     for (int i = firstarg; i < nargs; i++)
5624       check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5625 					i + 1, OPT_Wnonnull);
5626   else
5627     {
5628       /* Walk the argument list.  If we encounter an argument number we
5629 	 should check for non-null, do it.  */
5630       for (int i = firstarg; i < nargs; i++)
5631 	{
5632 	  for (a = attrs; ; a = TREE_CHAIN (a))
5633 	    {
5634 	      a = lookup_attribute ("nonnull", a);
5635 	      if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5636 		break;
5637 	    }
5638 
5639 	  if (a != NULL_TREE)
5640 	    check_function_arguments_recurse (check_nonnull_arg, &ctx,
5641 					      argarray[i], i + 1,
5642 					      OPT_Wnonnull);
5643 	}
5644     }
5645   return ctx.warned_p;
5646 }
5647 
5648 /* Check that the Nth argument of a function call (counting backwards
5649    from the end) is a (pointer)0.  The NARGS arguments are passed in the
5650    array ARGARRAY.  */
5651 
5652 static void
check_function_sentinel(const_tree fntype,int nargs,tree * argarray)5653 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5654 {
5655   tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5656 
5657   if (attr)
5658     {
5659       int len = 0;
5660       int pos = 0;
5661       tree sentinel;
5662       function_args_iterator iter;
5663       tree t;
5664 
5665       /* Skip over the named arguments.  */
5666       FOREACH_FUNCTION_ARGS (fntype, t, iter)
5667 	{
5668 	  if (len == nargs)
5669 	    break;
5670 	  len++;
5671 	}
5672 
5673       if (TREE_VALUE (attr))
5674 	{
5675 	  tree p = TREE_VALUE (TREE_VALUE (attr));
5676 	  pos = TREE_INT_CST_LOW (p);
5677 	}
5678 
5679       /* The sentinel must be one of the varargs, i.e.
5680 	 in position >= the number of fixed arguments.  */
5681       if ((nargs - 1 - pos) < len)
5682 	{
5683 	  warning (OPT_Wformat_,
5684 		   "not enough variable arguments to fit a sentinel");
5685 	  return;
5686 	}
5687 
5688       /* Validate the sentinel.  */
5689       sentinel = fold_for_warn (argarray[nargs - 1 - pos]);
5690       if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5691 	   || !integer_zerop (sentinel))
5692 	  /* Although __null (in C++) is only an integer we allow it
5693 	     nevertheless, as we are guaranteed that it's exactly
5694 	     as wide as a pointer, and we don't want to force
5695 	     users to cast the NULL they have written there.
5696 	     We warn with -Wstrict-null-sentinel, though.  */
5697 	  && (warn_strict_null_sentinel || null_node != sentinel))
5698 	warning (OPT_Wformat_, "missing sentinel in function call");
5699     }
5700 }
5701 
5702 /* Check that the same argument isn't passed to two or more
5703    restrict-qualified formal and issue a -Wrestrict warning
5704    if it is.  Return true if a warning has been issued.  */
5705 
5706 static bool
check_function_restrict(const_tree fndecl,const_tree fntype,int nargs,tree * unfolded_argarray)5707 check_function_restrict (const_tree fndecl, const_tree fntype,
5708 			 int nargs, tree *unfolded_argarray)
5709 {
5710   int i;
5711   tree parms = TYPE_ARG_TYPES (fntype);
5712 
5713   /* Call fold_for_warn on all of the arguments.  */
5714   auto_vec<tree> argarray (nargs);
5715   for (i = 0; i < nargs; i++)
5716     argarray.quick_push (fold_for_warn (unfolded_argarray[i]));
5717 
5718   if (fndecl
5719       && TREE_CODE (fndecl) == FUNCTION_DECL)
5720     {
5721       /* Avoid diagnosing calls built-ins with a zero size/bound
5722 	 here.  They are checked in more detail elsewhere.  */
5723       if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
5724 	  && nargs == 3
5725 	  && TREE_CODE (argarray[2]) == INTEGER_CST
5726 	  && integer_zerop (argarray[2]))
5727 	return false;
5728 
5729       if (DECL_ARGUMENTS (fndecl))
5730 	parms = DECL_ARGUMENTS (fndecl);
5731     }
5732 
5733   for (i = 0; i < nargs; i++)
5734     TREE_VISITED (argarray[i]) = 0;
5735 
5736   bool warned = false;
5737 
5738   for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5739     {
5740       tree type;
5741       if (TREE_CODE (parms) == PARM_DECL)
5742 	{
5743 	  type = TREE_TYPE (parms);
5744 	  parms = DECL_CHAIN (parms);
5745 	}
5746       else
5747 	{
5748 	  type = TREE_VALUE (parms);
5749 	  parms = TREE_CHAIN (parms);
5750 	}
5751       if (POINTER_TYPE_P (type)
5752 	  && TYPE_RESTRICT (type)
5753 	  && !TYPE_READONLY (TREE_TYPE (type)))
5754 	warned |= warn_for_restrict (i, argarray.address (), nargs);
5755     }
5756 
5757   for (i = 0; i < nargs; i++)
5758     TREE_VISITED (argarray[i]) = 0;
5759 
5760   return warned;
5761 }
5762 
5763 /* Helper for check_function_nonnull; given a list of operands which
5764    must be non-null in ARGS, determine if operand PARAM_NUM should be
5765    checked.  */
5766 
5767 static bool
nonnull_check_p(tree args,unsigned HOST_WIDE_INT param_num)5768 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5769 {
5770   unsigned HOST_WIDE_INT arg_num = 0;
5771 
5772   for (; args; args = TREE_CHAIN (args))
5773     {
5774       bool found = get_attribute_operand (TREE_VALUE (args), &arg_num);
5775 
5776       gcc_assert (found);
5777 
5778       if (arg_num == param_num)
5779 	return true;
5780     }
5781   return false;
5782 }
5783 
5784 /* Check that the function argument PARAM (which is operand number
5785    PARAM_NUM) is non-null.  This is called by check_function_nonnull
5786    via check_function_arguments_recurse.  */
5787 
5788 static void
check_nonnull_arg(void * ctx,tree param,unsigned HOST_WIDE_INT param_num)5789 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5790 {
5791   struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5792 
5793   /* Just skip checking the argument if it's not a pointer.  This can
5794      happen if the "nonnull" attribute was given without an operand
5795      list (which means to check every pointer argument).  */
5796 
5797   tree paramtype = TREE_TYPE (param);
5798   if (TREE_CODE (paramtype) != POINTER_TYPE
5799       && TREE_CODE (paramtype) != NULLPTR_TYPE)
5800     return;
5801 
5802   /* Diagnose the simple cases of null arguments.  */
5803   if (!integer_zerop (fold_for_warn (param)))
5804     return;
5805 
5806   auto_diagnostic_group adg;
5807 
5808   const location_t loc = EXPR_LOC_OR_LOC (param, pctx->loc);
5809 
5810   if (TREE_CODE (pctx->fntype) == METHOD_TYPE)
5811     --param_num;
5812 
5813   bool warned;
5814   if (param_num == 0)
5815     {
5816       warned = warning_at (loc, OPT_Wnonnull,
5817 			   "%qs pointer is null", "this");
5818       if (warned && pctx->fndecl)
5819 	inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5820 		"in a call to non-static member function %qD",
5821 		pctx->fndecl);
5822     }
5823   else
5824     {
5825       warned = warning_at (loc, OPT_Wnonnull,
5826 			   "argument %u null where non-null expected",
5827 			   (unsigned) param_num);
5828       if (warned && pctx->fndecl)
5829 	inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5830 		"in a call to function %qD declared %qs",
5831 		pctx->fndecl, "nonnull");
5832     }
5833 
5834   if (warned)
5835     pctx->warned_p = true;
5836 }
5837 
5838 /* Helper for attribute handling; fetch the operand number from
5839    the attribute argument list.  */
5840 
5841 bool
get_attribute_operand(tree arg_num_expr,unsigned HOST_WIDE_INT * valp)5842 get_attribute_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5843 {
5844   /* Verify the arg number is a small constant.  */
5845   if (tree_fits_uhwi_p (arg_num_expr))
5846     {
5847       *valp = tree_to_uhwi (arg_num_expr);
5848       return true;
5849     }
5850   else
5851     return false;
5852 }
5853 
5854 /* Arguments being collected for optimization.  */
5855 typedef const char *const_char_p;		/* For DEF_VEC_P.  */
5856 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5857 
5858 
5859 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5860    options in ARGS.  ATTR_P is true if this is for attribute(optimize), and
5861    false for #pragma GCC optimize.  */
5862 
5863 bool
parse_optimize_options(tree args,bool attr_p)5864 parse_optimize_options (tree args, bool attr_p)
5865 {
5866   bool ret = true;
5867   unsigned opt_argc;
5868   unsigned i;
5869   const char **opt_argv;
5870   struct cl_decoded_option *decoded_options;
5871   unsigned int decoded_options_count;
5872   tree ap;
5873 
5874   /* Build up argv vector.  Just in case the string is stored away, use garbage
5875      collected strings.  */
5876   vec_safe_truncate (optimize_args, 0);
5877   vec_safe_push (optimize_args, (const char *) NULL);
5878 
5879   for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5880     {
5881       tree value = TREE_VALUE (ap);
5882 
5883       if (TREE_CODE (value) == INTEGER_CST)
5884 	{
5885 	  char buffer[HOST_BITS_PER_LONG / 3 + 4];
5886 	  sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5887 	  vec_safe_push (optimize_args, ggc_strdup (buffer));
5888 	}
5889 
5890       else if (TREE_CODE (value) == STRING_CST)
5891 	{
5892 	  /* Split string into multiple substrings.  */
5893 	  size_t len = TREE_STRING_LENGTH (value);
5894 	  char *p = ASTRDUP (TREE_STRING_POINTER (value));
5895 	  char *end = p + len;
5896 	  char *comma;
5897 	  char *next_p = p;
5898 
5899 	  while (next_p != NULL)
5900 	    {
5901 	      size_t len2;
5902 	      char *q, *r;
5903 
5904 	      p = next_p;
5905 	      comma = strchr (p, ',');
5906 	      if (comma)
5907 		{
5908 		  len2 = comma - p;
5909 		  *comma = '\0';
5910 		  next_p = comma+1;
5911 		}
5912 	      else
5913 		{
5914 		  len2 = end - p;
5915 		  next_p = NULL;
5916 		}
5917 
5918 	      /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5919 		 options.  */
5920 	      if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5921 		{
5922 		  ret = false;
5923 		  if (attr_p)
5924 		    warning (OPT_Wattributes,
5925 			     "bad option %qs to attribute %<optimize%>", p);
5926 		  else
5927 		    warning (OPT_Wpragmas,
5928 			     "bad option %qs to pragma %<optimize%>", p);
5929 		  continue;
5930 		}
5931 
5932 	      /* Can't use GC memory here, see PR88007.  */
5933 	      r = q = XOBNEWVEC (&opts_obstack, char, len2 + 3);
5934 
5935 	      if (*p != '-')
5936 		{
5937 		  *r++ = '-';
5938 
5939 		  /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5940 		     itself is -Os, and any other switch begins with a -f.  */
5941 		  if ((*p >= '0' && *p <= '9')
5942 		      || (p[0] == 's' && p[1] == '\0'))
5943 		    *r++ = 'O';
5944 		  else if (*p != 'O')
5945 		    *r++ = 'f';
5946 		}
5947 
5948 	      memcpy (r, p, len2);
5949 	      r[len2] = '\0';
5950 	      vec_safe_push (optimize_args, (const char *) q);
5951 	    }
5952 
5953 	}
5954     }
5955 
5956   opt_argc = optimize_args->length ();
5957   opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5958 
5959   for (i = 1; i < opt_argc; i++)
5960     opt_argv[i] = (*optimize_args)[i];
5961 
5962   /* Now parse the options.  */
5963   decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
5964 						&decoded_options,
5965 						&decoded_options_count);
5966   /* Drop non-Optimization options.  */
5967   unsigned j = 1;
5968   for (i = 1; i < decoded_options_count; ++i)
5969     {
5970       if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
5971 	{
5972 	  ret = false;
5973 	  if (attr_p)
5974 	    warning (OPT_Wattributes,
5975 		     "bad option %qs to attribute %<optimize%>",
5976 		     decoded_options[i].orig_option_with_args_text);
5977 	  else
5978 	    warning (OPT_Wpragmas,
5979 		     "bad option %qs to pragma %<optimize%>",
5980 		     decoded_options[i].orig_option_with_args_text);
5981 	  continue;
5982 	}
5983       if (i != j)
5984 	decoded_options[j] = decoded_options[i];
5985       j++;
5986     }
5987   decoded_options_count = j;
5988 
5989   /* Merge the decoded options with save_decoded_options.  */
5990   unsigned save_opt_count = save_opt_decoded_options->length ();
5991   unsigned merged_decoded_options_count
5992     = save_opt_count + decoded_options_count;
5993   cl_decoded_option *merged_decoded_options
5994     = XNEWVEC (cl_decoded_option, merged_decoded_options_count);
5995 
5996   /* Note the first decoded_options is used for the program name.  */
5997   for (unsigned i = 0; i < save_opt_count; ++i)
5998     merged_decoded_options[i + 1] = (*save_opt_decoded_options)[i];
5999   for (unsigned i = 1; i < decoded_options_count; ++i)
6000     merged_decoded_options[save_opt_count + i] = decoded_options[i];
6001 
6002    /* And apply them.  */
6003   decode_options (&global_options, &global_options_set,
6004 		  merged_decoded_options, merged_decoded_options_count,
6005 		  input_location, global_dc, NULL);
6006   free (decoded_options);
6007 
6008   targetm.override_options_after_change();
6009 
6010   optimize_args->truncate (0);
6011   return ret;
6012 }
6013 
6014 /* Check whether ATTR is a valid attribute fallthrough.  */
6015 
6016 bool
attribute_fallthrough_p(tree attr)6017 attribute_fallthrough_p (tree attr)
6018 {
6019   if (attr == error_mark_node)
6020    return false;
6021   tree t = lookup_attribute ("fallthrough", attr);
6022   if (t == NULL_TREE)
6023     return false;
6024   /* It is no longer true that "this attribute shall appear at most once in
6025      each attribute-list", but we still give a warning.  */
6026   if (lookup_attribute ("fallthrough", TREE_CHAIN (t)))
6027     warning (OPT_Wattributes, "attribute %<fallthrough%> specified multiple "
6028 	     "times");
6029   /* No attribute-argument-clause shall be present.  */
6030   else if (TREE_VALUE (t) != NULL_TREE)
6031     warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
6032 	     "a parameter");
6033   /* Warn if other attributes are found.  */
6034   for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
6035     {
6036       tree name = get_attribute_name (t);
6037       if (!is_attribute_p ("fallthrough", name))
6038 	{
6039 	  if (!c_dialect_cxx () && get_attribute_namespace (t) == NULL_TREE)
6040 	    /* The specifications of standard attributes in C mean
6041 	       this is a constraint violation.  */
6042 	    pedwarn (input_location, OPT_Wattributes, "%qE attribute ignored",
6043 		     get_attribute_name (t));
6044 	  else
6045 	    warning (OPT_Wattributes, "%qE attribute ignored", name);
6046 	}
6047     }
6048   return true;
6049 }
6050 
6051 
6052 /* Check for valid arguments being passed to a function with FNTYPE.
6053    There are NARGS arguments in the array ARGARRAY.  LOC should be used
6054    for diagnostics.  Return true if either -Wnonnull or -Wrestrict has
6055    been issued.
6056 
6057    The arguments in ARGARRAY may not have been folded yet (e.g. for C++,
6058    to preserve location wrappers); checks that require folded arguments
6059    should call fold_for_warn on them.  */
6060 
6061 bool
check_function_arguments(location_t loc,const_tree fndecl,const_tree fntype,int nargs,tree * argarray,vec<location_t> * arglocs)6062 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
6063 			  int nargs, tree *argarray, vec<location_t> *arglocs)
6064 {
6065   bool warned_p = false;
6066 
6067   /* Check for null being passed in a pointer argument that must be
6068      non-null.  In C++, this includes the this pointer.  We also need
6069      to do this if format checking is enabled.  */
6070   if (warn_nonnull)
6071     {
6072       nonnull_arg_ctx ctx = { loc, fndecl, fntype, false };
6073       warned_p = check_function_nonnull (ctx, nargs, argarray);
6074     }
6075 
6076   /* Check for errors in format strings.  */
6077 
6078   if (warn_format || warn_suggest_attribute_format)
6079     check_function_format (fntype, TYPE_ATTRIBUTES (fntype), nargs, argarray,
6080 			   arglocs);
6081 
6082   if (warn_format)
6083     check_function_sentinel (fntype, nargs, argarray);
6084 
6085   if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
6086     {
6087       switch (DECL_FUNCTION_CODE (fndecl))
6088 	{
6089 	case BUILT_IN_SPRINTF:
6090 	case BUILT_IN_SPRINTF_CHK:
6091 	case BUILT_IN_SNPRINTF:
6092 	case BUILT_IN_SNPRINTF_CHK:
6093 	  /* Let the sprintf pass handle these.  */
6094 	  return warned_p;
6095 
6096 	default:
6097 	  break;
6098 	}
6099     }
6100 
6101   /* check_function_restrict sets the DECL_READ_P for arguments
6102      so it must be called unconditionally.  */
6103   warned_p |= check_function_restrict (fndecl, fntype, nargs, argarray);
6104 
6105   return warned_p;
6106 }
6107 
6108 /* Generic argument checking recursion routine.  PARAM is the argument to
6109    be checked.  PARAM_NUM is the number of the argument.  CALLBACK is invoked
6110    once the argument is resolved.  CTX is context for the callback.
6111    OPT is the warning for which this is done.  */
6112 void
check_function_arguments_recurse(void (* callback)(void *,tree,unsigned HOST_WIDE_INT),void * ctx,tree param,unsigned HOST_WIDE_INT param_num,opt_code opt)6113 check_function_arguments_recurse (void (*callback)
6114 				  (void *, tree, unsigned HOST_WIDE_INT),
6115 				  void *ctx, tree param,
6116 				  unsigned HOST_WIDE_INT param_num,
6117 				  opt_code opt)
6118 {
6119   if (opt != OPT_Wformat_ && warning_suppressed_p (param))
6120     return;
6121 
6122   if (CONVERT_EXPR_P (param)
6123       && (TYPE_PRECISION (TREE_TYPE (param))
6124 	  == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
6125     {
6126       /* Strip coercion.  */
6127       check_function_arguments_recurse (callback, ctx,
6128 					TREE_OPERAND (param, 0), param_num,
6129 					opt);
6130       return;
6131     }
6132 
6133   if (TREE_CODE (param) == CALL_EXPR && CALL_EXPR_FN (param))
6134     {
6135       tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
6136       tree attrs;
6137       bool found_format_arg = false;
6138 
6139       /* See if this is a call to a known internationalization function
6140 	 that modifies a format arg.  Such a function may have multiple
6141 	 format_arg attributes (for example, ngettext).  */
6142 
6143       for (attrs = TYPE_ATTRIBUTES (type);
6144 	   attrs;
6145 	   attrs = TREE_CHAIN (attrs))
6146 	if (is_attribute_p ("format_arg", get_attribute_name (attrs)))
6147 	  {
6148 	    tree inner_arg;
6149 	    tree format_num_expr;
6150 	    int format_num;
6151 	    int i;
6152 	    call_expr_arg_iterator iter;
6153 
6154 	    /* Extract the argument number, which was previously checked
6155 	       to be valid.  */
6156 	    format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
6157 
6158 	    format_num = tree_to_uhwi (format_num_expr);
6159 
6160 	    for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
6161 		 inner_arg != NULL_TREE;
6162 		 inner_arg = next_call_expr_arg (&iter), i++)
6163 	      if (i == format_num)
6164 		{
6165 		  check_function_arguments_recurse (callback, ctx,
6166 						    inner_arg, param_num,
6167 						    opt);
6168 		  found_format_arg = true;
6169 		  break;
6170 		}
6171 	  }
6172 
6173       /* If we found a format_arg attribute and did a recursive check,
6174 	 we are done with checking this argument.  Otherwise, we continue
6175 	 and this will be considered a non-literal.  */
6176       if (found_format_arg)
6177 	return;
6178     }
6179 
6180   if (TREE_CODE (param) == COND_EXPR)
6181     {
6182       /* Simplify to avoid warning for an impossible case.  */
6183       param = fold_for_warn (param);
6184       if (TREE_CODE (param) == COND_EXPR)
6185 	{
6186 	  /* Check both halves of the conditional expression.  */
6187 	  check_function_arguments_recurse (callback, ctx,
6188 					    TREE_OPERAND (param, 1),
6189 					    param_num, opt);
6190 	  check_function_arguments_recurse (callback, ctx,
6191 					    TREE_OPERAND (param, 2),
6192 					    param_num, opt);
6193 	  return;
6194 	}
6195     }
6196 
6197   (*callback) (ctx, param, param_num);
6198 }
6199 
6200 /* Checks for a builtin function FNDECL that the number of arguments
6201    NARGS against the required number REQUIRED and issues an error if
6202    there is a mismatch.  Returns true if the number of arguments is
6203    correct, otherwise false.  LOC is the location of FNDECL.  */
6204 
6205 static bool
builtin_function_validate_nargs(location_t loc,tree fndecl,int nargs,int required)6206 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
6207 				 int required)
6208 {
6209   if (nargs < required)
6210     {
6211       error_at (loc, "too few arguments to function %qE", fndecl);
6212       return false;
6213     }
6214   else if (nargs > required)
6215     {
6216       error_at (loc, "too many arguments to function %qE", fndecl);
6217       return false;
6218     }
6219   return true;
6220 }
6221 
6222 /* Helper macro for check_builtin_function_arguments.  */
6223 #define ARG_LOCATION(N)					\
6224   (arg_loc.is_empty ()					\
6225    ? EXPR_LOC_OR_LOC (args[(N)], input_location)	\
6226    : expansion_point_location (arg_loc[(N)]))
6227 
6228 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
6229    Returns false if there was an error, otherwise true.  LOC is the
6230    location of the function; ARG_LOC is a vector of locations of the
6231    arguments.  If FNDECL is the result of resolving an overloaded
6232    target built-in, ORIG_FNDECL is the original function decl,
6233    otherwise it is null.  */
6234 
6235 bool
check_builtin_function_arguments(location_t loc,vec<location_t> arg_loc,tree fndecl,tree orig_fndecl,int nargs,tree * args)6236 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
6237 				  tree fndecl, tree orig_fndecl,
6238 				  int nargs, tree *args)
6239 {
6240   if (!fndecl_built_in_p (fndecl))
6241     return true;
6242 
6243   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6244     return (!targetm.check_builtin_call
6245 	    || targetm.check_builtin_call (loc, arg_loc, fndecl,
6246 					   orig_fndecl, nargs, args));
6247 
6248   if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_FRONTEND)
6249     return true;
6250 
6251   gcc_assert (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL);
6252   switch (DECL_FUNCTION_CODE (fndecl))
6253     {
6254     case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
6255       if (!tree_fits_uhwi_p (args[2]))
6256 	{
6257 	  error_at (ARG_LOCATION (2),
6258 		    "third argument to function %qE must be a constant integer",
6259 		    fndecl);
6260 	  return false;
6261 	}
6262       /* fall through */
6263 
6264     case BUILT_IN_ALLOCA_WITH_ALIGN:
6265       {
6266 	/* Get the requested alignment (in bits) if it's a constant
6267 	   integer expression.  */
6268 	unsigned HOST_WIDE_INT align
6269 	  = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
6270 
6271 	/* Determine if the requested alignment is a power of 2.  */
6272 	if ((align & (align - 1)))
6273 	  align = 0;
6274 
6275 	/* The maximum alignment in bits corresponding to the same
6276 	   maximum in bytes enforced in check_user_alignment().  */
6277 	unsigned maxalign = (UINT_MAX >> 1) + 1;
6278 
6279 	/* Reject invalid alignments.  */
6280 	if (align < BITS_PER_UNIT || maxalign < align)
6281 	  {
6282 	    error_at (ARG_LOCATION (1),
6283 		      "second argument to function %qE must be a constant "
6284 		      "integer power of 2 between %qi and %qu bits",
6285 		      fndecl, BITS_PER_UNIT, maxalign);
6286 	    return false;
6287 	  }
6288 	return true;
6289       }
6290 
6291     case BUILT_IN_CONSTANT_P:
6292       return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
6293 
6294     case BUILT_IN_ISFINITE:
6295     case BUILT_IN_ISINF:
6296     case BUILT_IN_ISINF_SIGN:
6297     case BUILT_IN_ISNAN:
6298     case BUILT_IN_ISNORMAL:
6299     case BUILT_IN_SIGNBIT:
6300       if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6301 	{
6302 	  if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
6303 	    {
6304 	      error_at (ARG_LOCATION (0), "non-floating-point argument in "
6305 			"call to function %qE", fndecl);
6306 	      return false;
6307 	    }
6308 	  return true;
6309 	}
6310       return false;
6311 
6312     case BUILT_IN_ISGREATER:
6313     case BUILT_IN_ISGREATEREQUAL:
6314     case BUILT_IN_ISLESS:
6315     case BUILT_IN_ISLESSEQUAL:
6316     case BUILT_IN_ISLESSGREATER:
6317     case BUILT_IN_ISUNORDERED:
6318       if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
6319 	{
6320 	  enum tree_code code0, code1;
6321 	  code0 = TREE_CODE (TREE_TYPE (args[0]));
6322 	  code1 = TREE_CODE (TREE_TYPE (args[1]));
6323 	  if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
6324 		|| (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
6325 		|| (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
6326 	    {
6327 	      error_at (loc, "non-floating-point arguments in call to "
6328 			"function %qE", fndecl);
6329 	      return false;
6330 	    }
6331 	  return true;
6332 	}
6333       return false;
6334 
6335     case BUILT_IN_FPCLASSIFY:
6336       if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
6337 	{
6338 	  for (unsigned int i = 0; i < 5; i++)
6339 	    if (TREE_CODE (args[i]) != INTEGER_CST)
6340 	      {
6341 		error_at (ARG_LOCATION (i), "non-const integer argument %u in "
6342 			  "call to function %qE", i + 1, fndecl);
6343 		return false;
6344 	      }
6345 
6346 	  if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
6347 	    {
6348 	      error_at (ARG_LOCATION (5), "non-floating-point argument in "
6349 			"call to function %qE", fndecl);
6350 	      return false;
6351 	    }
6352 	  return true;
6353 	}
6354       return false;
6355 
6356     case BUILT_IN_ASSUME_ALIGNED:
6357       if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
6358 	{
6359 	  if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
6360 	    {
6361 	      error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
6362 			"function %qE", fndecl);
6363 	      return false;
6364 	    }
6365 	  return true;
6366 	}
6367       return false;
6368 
6369     case BUILT_IN_ADD_OVERFLOW:
6370     case BUILT_IN_SUB_OVERFLOW:
6371     case BUILT_IN_MUL_OVERFLOW:
6372       if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6373 	{
6374 	  unsigned i;
6375 	  for (i = 0; i < 2; i++)
6376 	    if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6377 	      {
6378 		error_at (ARG_LOCATION (i), "argument %u in call to function "
6379 			  "%qE does not have integral type", i + 1, fndecl);
6380 		return false;
6381 	      }
6382 	  if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
6383 	      || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
6384 	    {
6385 	      error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6386 			"does not have pointer to integral type", fndecl);
6387 	      return false;
6388 	    }
6389 	  else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
6390 	    {
6391 	      error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6392 			"has pointer to enumerated type", fndecl);
6393 	      return false;
6394 	    }
6395 	  else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
6396 	    {
6397 	      error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6398 			"has pointer to boolean type", fndecl);
6399 	      return false;
6400 	    }
6401 	  else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[2]))))
6402 	    {
6403 	      error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6404 			"has pointer to %qs type (%qT)", 3, fndecl, "const",
6405 			TREE_TYPE (args[2]));
6406 	      return false;
6407 	    }
6408 	  else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[2]))))
6409 	    {
6410 	      error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6411 			"has pointer to %qs type (%qT)", 3, fndecl,
6412 			"_Atomic", TREE_TYPE (args[2]));
6413 	      return false;
6414 	    }
6415 	  return true;
6416 	}
6417       return false;
6418 
6419     case BUILT_IN_ADD_OVERFLOW_P:
6420     case BUILT_IN_SUB_OVERFLOW_P:
6421     case BUILT_IN_MUL_OVERFLOW_P:
6422       if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6423 	{
6424 	  unsigned i;
6425 	  for (i = 0; i < 3; i++)
6426 	    if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6427 	      {
6428 		error_at (ARG_LOCATION (i), "argument %u in call to function "
6429 			  "%qE does not have integral type", i + 1, fndecl);
6430 		return false;
6431 	      }
6432 	  if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
6433 	    {
6434 	      error_at (ARG_LOCATION (2), "argument 3 in call to function "
6435 			"%qE has enumerated type", fndecl);
6436 	      return false;
6437 	    }
6438 	  else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
6439 	    {
6440 	      error_at (ARG_LOCATION (2), "argument 3 in call to function "
6441 			"%qE has boolean type", fndecl);
6442 	      return false;
6443 	    }
6444 	  return true;
6445 	}
6446       return false;
6447 
6448     case BUILT_IN_CLEAR_PADDING:
6449       if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6450 	{
6451 	  if (!POINTER_TYPE_P (TREE_TYPE (args[0])))
6452 	    {
6453 	      error_at (ARG_LOCATION (0), "argument %u in call to function "
6454 			"%qE does not have pointer type", 1, fndecl);
6455 	      return false;
6456 	    }
6457 	  else if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (args[0]))))
6458 	    {
6459 	      error_at (ARG_LOCATION (0), "argument %u in call to function "
6460 			"%qE points to incomplete type", 1, fndecl);
6461 	      return false;
6462 	    }
6463 	  else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[0]))))
6464 	    {
6465 	      error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6466 			"has pointer to %qs type (%qT)", 1, fndecl, "const",
6467 			TREE_TYPE (args[0]));
6468 	      return false;
6469 	    }
6470 	  else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[0]))))
6471 	    {
6472 	      error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6473 			"has pointer to %qs type (%qT)", 1, fndecl,
6474 			"_Atomic", TREE_TYPE (args[0]));
6475 	      return false;
6476 	    }
6477 	  return true;
6478 	}
6479       return false;
6480 
6481     default:
6482       return true;
6483     }
6484 }
6485 
6486 /* Subroutine of c_parse_error.
6487    Return the result of concatenating LHS and RHS. RHS is really
6488    a string literal, its first character is indicated by RHS_START and
6489    RHS_SIZE is its length (including the terminating NUL character).
6490 
6491    The caller is responsible for deleting the returned pointer.  */
6492 
6493 static char *
catenate_strings(const char * lhs,const char * rhs_start,int rhs_size)6494 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
6495 {
6496   const size_t lhs_size = strlen (lhs);
6497   char *result = XNEWVEC (char, lhs_size + rhs_size);
6498   memcpy (result, lhs, lhs_size);
6499   memcpy (result + lhs_size, rhs_start, rhs_size);
6500   return result;
6501 }
6502 
6503 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
6504    before TOKEN, which had the associated VALUE.  */
6505 
6506 void
c_parse_error(const char * gmsgid,enum cpp_ttype token_type,tree value,unsigned char token_flags,rich_location * richloc)6507 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
6508 	       tree value, unsigned char token_flags,
6509 	       rich_location *richloc)
6510 {
6511 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
6512 
6513   char *message = NULL;
6514 
6515   if (token_type == CPP_EOF)
6516     message = catenate_messages (gmsgid, " at end of input");
6517   else if (token_type == CPP_CHAR
6518 	   || token_type == CPP_WCHAR
6519 	   || token_type == CPP_CHAR16
6520 	   || token_type == CPP_CHAR32
6521 	   || token_type == CPP_UTF8CHAR)
6522     {
6523       unsigned int val = TREE_INT_CST_LOW (value);
6524       const char *prefix;
6525 
6526       switch (token_type)
6527 	{
6528 	default:
6529 	  prefix = "";
6530 	  break;
6531 	case CPP_WCHAR:
6532 	  prefix = "L";
6533 	  break;
6534 	case CPP_CHAR16:
6535 	  prefix = "u";
6536 	  break;
6537 	case CPP_CHAR32:
6538 	  prefix = "U";
6539 	  break;
6540 	case CPP_UTF8CHAR:
6541 	  prefix = "u8";
6542 	  break;
6543         }
6544 
6545       if (val <= UCHAR_MAX && ISGRAPH (val))
6546 	message = catenate_messages (gmsgid, " before %s'%c'");
6547       else
6548 	message = catenate_messages (gmsgid, " before %s'\\x%x'");
6549 
6550       error_at (richloc, message, prefix, val);
6551       free (message);
6552       message = NULL;
6553     }
6554   else if (token_type == CPP_CHAR_USERDEF
6555 	   || token_type == CPP_WCHAR_USERDEF
6556 	   || token_type == CPP_CHAR16_USERDEF
6557 	   || token_type == CPP_CHAR32_USERDEF
6558 	   || token_type == CPP_UTF8CHAR_USERDEF)
6559     message = catenate_messages (gmsgid,
6560 				 " before user-defined character literal");
6561   else if (token_type == CPP_STRING_USERDEF
6562 	   || token_type == CPP_WSTRING_USERDEF
6563 	   || token_type == CPP_STRING16_USERDEF
6564 	   || token_type == CPP_STRING32_USERDEF
6565 	   || token_type == CPP_UTF8STRING_USERDEF)
6566     message = catenate_messages (gmsgid, " before user-defined string literal");
6567   else if (token_type == CPP_STRING
6568 	   || token_type == CPP_WSTRING
6569 	   || token_type == CPP_STRING16
6570 	   || token_type == CPP_STRING32
6571 	   || token_type == CPP_UTF8STRING)
6572     message = catenate_messages (gmsgid, " before string constant");
6573   else if (token_type == CPP_NUMBER)
6574     message = catenate_messages (gmsgid, " before numeric constant");
6575   else if (token_type == CPP_NAME)
6576     {
6577       message = catenate_messages (gmsgid, " before %qE");
6578       error_at (richloc, message, value);
6579       free (message);
6580       message = NULL;
6581     }
6582   else if (token_type == CPP_PRAGMA)
6583     message = catenate_messages (gmsgid, " before %<#pragma%>");
6584   else if (token_type == CPP_PRAGMA_EOL)
6585     message = catenate_messages (gmsgid, " before end of line");
6586   else if (token_type == CPP_DECLTYPE)
6587     message = catenate_messages (gmsgid, " before %<decltype%>");
6588   else if (token_type < N_TTYPES)
6589     {
6590       message = catenate_messages (gmsgid, " before %qs token");
6591       error_at (richloc, message, cpp_type2name (token_type, token_flags));
6592       free (message);
6593       message = NULL;
6594     }
6595   else
6596     error_at (richloc, gmsgid);
6597 
6598   if (message)
6599     {
6600       error_at (richloc, message);
6601       free (message);
6602     }
6603 #undef catenate_messages
6604 }
6605 
6606 /* Return the gcc option code associated with the reason for a cpp
6607    message, or 0 if none.  */
6608 
6609 static int
c_option_controlling_cpp_diagnostic(enum cpp_warning_reason reason)6610 c_option_controlling_cpp_diagnostic (enum cpp_warning_reason reason)
6611 {
6612   const struct cpp_reason_option_codes_t *entry;
6613 
6614   for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6615     {
6616       if (entry->reason == reason)
6617 	return entry->option_code;
6618     }
6619   return 0;
6620 }
6621 
6622 /* Callback from cpp_diagnostic for PFILE to print diagnostics from the
6623    preprocessor.  The diagnostic is of type LEVEL, with REASON set
6624    to the reason code if LEVEL is represents a warning, at location
6625    RICHLOC unless this is after lexing and the compiler's location
6626    should be used instead; MSG is the translated message and AP
6627    the arguments.  Returns true if a diagnostic was emitted, false
6628    otherwise.  */
6629 
6630 bool
c_cpp_diagnostic(cpp_reader * pfile ATTRIBUTE_UNUSED,enum cpp_diagnostic_level level,enum cpp_warning_reason reason,rich_location * richloc,const char * msg,va_list * ap)6631 c_cpp_diagnostic (cpp_reader *pfile ATTRIBUTE_UNUSED,
6632 		  enum cpp_diagnostic_level level,
6633 		  enum cpp_warning_reason reason,
6634 		  rich_location *richloc,
6635 		  const char *msg, va_list *ap)
6636 {
6637   diagnostic_info diagnostic;
6638   diagnostic_t dlevel;
6639   bool save_warn_system_headers = global_dc->dc_warn_system_headers;
6640   bool ret;
6641 
6642   switch (level)
6643     {
6644     case CPP_DL_WARNING_SYSHDR:
6645       if (flag_no_output)
6646 	return false;
6647       global_dc->dc_warn_system_headers = 1;
6648       /* Fall through.  */
6649     case CPP_DL_WARNING:
6650       if (flag_no_output)
6651 	return false;
6652       dlevel = DK_WARNING;
6653       break;
6654     case CPP_DL_PEDWARN:
6655       if (flag_no_output && !flag_pedantic_errors)
6656 	return false;
6657       dlevel = DK_PEDWARN;
6658       break;
6659     case CPP_DL_ERROR:
6660       dlevel = DK_ERROR;
6661       break;
6662     case CPP_DL_ICE:
6663       dlevel = DK_ICE;
6664       break;
6665     case CPP_DL_NOTE:
6666       dlevel = DK_NOTE;
6667       break;
6668     case CPP_DL_FATAL:
6669       dlevel = DK_FATAL;
6670       break;
6671     default:
6672       gcc_unreachable ();
6673     }
6674   if (done_lexing)
6675     richloc->set_range (0, input_location, SHOW_RANGE_WITH_CARET);
6676   diagnostic_set_info_translated (&diagnostic, msg, ap,
6677 				  richloc, dlevel);
6678   diagnostic_override_option_index
6679     (&diagnostic,
6680      c_option_controlling_cpp_diagnostic (reason));
6681   ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6682   if (level == CPP_DL_WARNING_SYSHDR)
6683     global_dc->dc_warn_system_headers = save_warn_system_headers;
6684   return ret;
6685 }
6686 
6687 /* Convert a character from the host to the target execution character
6688    set.  cpplib handles this, mostly.  */
6689 
6690 HOST_WIDE_INT
c_common_to_target_charset(HOST_WIDE_INT c)6691 c_common_to_target_charset (HOST_WIDE_INT c)
6692 {
6693   /* Character constants in GCC proper are sign-extended under -fsigned-char,
6694      zero-extended under -fno-signed-char.  cpplib insists that characters
6695      and character constants are always unsigned.  Hence we must convert
6696      back and forth.  */
6697   cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6698 
6699   uc = cpp_host_to_exec_charset (parse_in, uc);
6700 
6701   if (flag_signed_char)
6702     return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6703 			       >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6704   else
6705     return uc;
6706 }
6707 
6708 /* Fold an offsetof-like expression.  EXPR is a nested sequence of component
6709    references with an INDIRECT_REF of a constant at the bottom; much like the
6710    traditional rendering of offsetof as a macro.  TYPE is the desired type of
6711    the whole expression.  Return the folded result.  */
6712 
6713 tree
fold_offsetof(tree expr,tree type,enum tree_code ctx)6714 fold_offsetof (tree expr, tree type, enum tree_code ctx)
6715 {
6716   tree base, off, t;
6717   tree_code code = TREE_CODE (expr);
6718   switch (code)
6719     {
6720     case ERROR_MARK:
6721       return expr;
6722 
6723     case VAR_DECL:
6724       error ("cannot apply %<offsetof%> to static data member %qD", expr);
6725       return error_mark_node;
6726 
6727     case CALL_EXPR:
6728     case TARGET_EXPR:
6729       error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6730       return error_mark_node;
6731 
6732     case NOP_EXPR:
6733     case INDIRECT_REF:
6734       if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6735 	{
6736 	  error ("cannot apply %<offsetof%> to a non constant address");
6737 	  return error_mark_node;
6738 	}
6739       return convert (type, TREE_OPERAND (expr, 0));
6740 
6741     case COMPONENT_REF:
6742       base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6743       if (base == error_mark_node)
6744 	return base;
6745 
6746       t = TREE_OPERAND (expr, 1);
6747       if (DECL_C_BIT_FIELD (t))
6748 	{
6749 	  error ("attempt to take address of bit-field structure "
6750 		 "member %qD", t);
6751 	  return error_mark_node;
6752 	}
6753       off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6754 			    size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6755 				      / BITS_PER_UNIT));
6756       break;
6757 
6758     case ARRAY_REF:
6759       base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6760       if (base == error_mark_node)
6761 	return base;
6762 
6763       t = TREE_OPERAND (expr, 1);
6764       STRIP_ANY_LOCATION_WRAPPER (t);
6765 
6766       /* Check if the offset goes beyond the upper bound of the array.  */
6767       if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6768 	{
6769 	  tree upbound = array_ref_up_bound (expr);
6770 	  if (upbound != NULL_TREE
6771 	      && TREE_CODE (upbound) == INTEGER_CST
6772 	      && !tree_int_cst_equal (upbound,
6773 				      TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6774 	    {
6775 	      if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6776 	        upbound = size_binop (PLUS_EXPR, upbound,
6777 				      build_int_cst (TREE_TYPE (upbound), 1));
6778 	      if (tree_int_cst_lt (upbound, t))
6779 		{
6780 		  tree v;
6781 
6782 		  for (v = TREE_OPERAND (expr, 0);
6783 		       TREE_CODE (v) == COMPONENT_REF;
6784 		       v = TREE_OPERAND (v, 0))
6785 		    if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6786 			== RECORD_TYPE)
6787 		      {
6788 			tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6789 			for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6790 			  if (TREE_CODE (fld_chain) == FIELD_DECL)
6791 			    break;
6792 
6793 			if (fld_chain)
6794 			  break;
6795 		      }
6796 		  /* Don't warn if the array might be considered a poor
6797 		     man's flexible array member with a very permissive
6798 		     definition thereof.  */
6799 		  if (TREE_CODE (v) == ARRAY_REF
6800 		      || TREE_CODE (v) == COMPONENT_REF)
6801 		    warning (OPT_Warray_bounds,
6802 			     "index %E denotes an offset "
6803 			     "greater than size of %qT",
6804 			     t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6805 		}
6806 	    }
6807 	}
6808 
6809       t = convert (sizetype, t);
6810       off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6811       break;
6812 
6813     case COMPOUND_EXPR:
6814       /* Handle static members of volatile structs.  */
6815       t = TREE_OPERAND (expr, 1);
6816       gcc_checking_assert (VAR_P (get_base_address (t)));
6817       return fold_offsetof (t, type);
6818 
6819     default:
6820       gcc_unreachable ();
6821     }
6822 
6823   if (!POINTER_TYPE_P (type))
6824     return size_binop (PLUS_EXPR, base, convert (type, off));
6825   return fold_build_pointer_plus (base, off);
6826 }
6827 
6828 /* *PTYPE is an incomplete array.  Complete it with a domain based on
6829    INITIAL_VALUE.  If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6830    is true.  Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6831    2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty.  */
6832 
6833 int
complete_array_type(tree * ptype,tree initial_value,bool do_default)6834 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6835 {
6836   tree maxindex, type, main_type, elt, unqual_elt;
6837   int failure = 0, quals;
6838   bool overflow_p = false;
6839 
6840   maxindex = size_zero_node;
6841   if (initial_value)
6842     {
6843       STRIP_ANY_LOCATION_WRAPPER (initial_value);
6844 
6845       if (TREE_CODE (initial_value) == STRING_CST)
6846 	{
6847 	  int eltsize
6848 	    = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6849 	  maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6850 	}
6851       else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6852 	{
6853 	  vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6854 
6855 	  if (vec_safe_is_empty (v))
6856 	    {
6857 	      if (pedantic)
6858 		failure = 3;
6859 	      maxindex = ssize_int (-1);
6860 	    }
6861 	  else
6862 	    {
6863 	      tree curindex;
6864 	      unsigned HOST_WIDE_INT cnt;
6865 	      constructor_elt *ce;
6866 	      bool fold_p = false;
6867 
6868 	      if ((*v)[0].index)
6869 		maxindex = (*v)[0].index, fold_p = true;
6870 
6871 	      curindex = maxindex;
6872 
6873 	      for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
6874 		{
6875 		  bool curfold_p = false;
6876 		  if (ce->index)
6877 		    curindex = ce->index, curfold_p = true;
6878 		  else
6879 		    {
6880 		      if (fold_p)
6881 			{
6882 			  /* Since we treat size types now as ordinary
6883 			     unsigned types, we need an explicit overflow
6884 			     check.  */
6885 			  tree orig = curindex;
6886 		          curindex = fold_convert (sizetype, curindex);
6887 			  overflow_p |= tree_int_cst_lt (curindex, orig);
6888 			}
6889 		      curindex = size_binop (PLUS_EXPR, curindex,
6890 					     size_one_node);
6891 		    }
6892 		  if (tree_int_cst_lt (maxindex, curindex))
6893 		    maxindex = curindex, fold_p = curfold_p;
6894 		}
6895 	      if (fold_p)
6896 		{
6897 		  tree orig = maxindex;
6898 	          maxindex = fold_convert (sizetype, maxindex);
6899 		  overflow_p |= tree_int_cst_lt (maxindex, orig);
6900 		}
6901 	    }
6902 	}
6903       else
6904 	{
6905 	  /* Make an error message unless that happened already.  */
6906 	  if (initial_value != error_mark_node)
6907 	    failure = 1;
6908 	}
6909     }
6910   else
6911     {
6912       failure = 2;
6913       if (!do_default)
6914 	return failure;
6915     }
6916 
6917   type = *ptype;
6918   elt = TREE_TYPE (type);
6919   quals = TYPE_QUALS (strip_array_types (elt));
6920   if (quals == 0)
6921     unqual_elt = elt;
6922   else
6923     unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
6924 
6925   /* Using build_distinct_type_copy and modifying things afterward instead
6926      of using build_array_type to create a new type preserves all of the
6927      TYPE_LANG_FLAG_? bits that the front end may have set.  */
6928   main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
6929   TREE_TYPE (main_type) = unqual_elt;
6930   TYPE_DOMAIN (main_type)
6931     = build_range_type (TREE_TYPE (maxindex),
6932 			build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
6933   TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
6934   layout_type (main_type);
6935 
6936   /* Make sure we have the canonical MAIN_TYPE. */
6937   hashval_t hashcode = type_hash_canon_hash (main_type);
6938   main_type = type_hash_canon (hashcode, main_type);
6939 
6940   /* Fix the canonical type.  */
6941   if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
6942       || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
6943     SET_TYPE_STRUCTURAL_EQUALITY (main_type);
6944   else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
6945 	   || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
6946 	       != TYPE_DOMAIN (main_type)))
6947     TYPE_CANONICAL (main_type)
6948       = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
6949 			  TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
6950 			  TYPE_TYPELESS_STORAGE (main_type));
6951   else
6952     TYPE_CANONICAL (main_type) = main_type;
6953 
6954   if (quals == 0)
6955     type = main_type;
6956   else
6957     type = c_build_qualified_type (main_type, quals);
6958 
6959   if (COMPLETE_TYPE_P (type)
6960       && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
6961       && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
6962     {
6963       error ("size of array is too large");
6964       /* If we proceed with the array type as it is, we'll eventually
6965 	 crash in tree_to_[su]hwi().  */
6966       type = error_mark_node;
6967     }
6968 
6969   *ptype = type;
6970   return failure;
6971 }
6972 
6973 /* INIT is an constructor of a structure with a flexible array member.
6974    Complete the flexible array member with a domain based on it's value.  */
6975 void
complete_flexible_array_elts(tree init)6976 complete_flexible_array_elts (tree init)
6977 {
6978   tree elt, type;
6979 
6980   if (init == NULL_TREE || TREE_CODE (init) != CONSTRUCTOR)
6981     return;
6982 
6983   if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
6984     return;
6985 
6986   elt = CONSTRUCTOR_ELTS (init)->last ().value;
6987   type = TREE_TYPE (elt);
6988   if (TREE_CODE (type) == ARRAY_TYPE
6989       && TYPE_SIZE (type) == NULL_TREE)
6990     complete_array_type (&TREE_TYPE (elt), elt, false);
6991   else
6992     complete_flexible_array_elts (elt);
6993 }
6994 
6995 /* Like c_mark_addressable but don't check register qualifier.  */
6996 void
c_common_mark_addressable_vec(tree t)6997 c_common_mark_addressable_vec (tree t)
6998 {
6999   while (handled_component_p (t) || TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7000     {
7001       if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7002 	t = C_MAYBE_CONST_EXPR_EXPR (t);
7003       else
7004 	t = TREE_OPERAND (t, 0);
7005     }
7006   if (!VAR_P (t)
7007       && TREE_CODE (t) != PARM_DECL
7008       && TREE_CODE (t) != COMPOUND_LITERAL_EXPR
7009       && TREE_CODE (t) != TARGET_EXPR)
7010     return;
7011   if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
7012     TREE_ADDRESSABLE (t) = 1;
7013   if (TREE_CODE (t) == COMPOUND_LITERAL_EXPR)
7014     TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (t)) = 1;
7015   else if (TREE_CODE (t) == TARGET_EXPR)
7016     TREE_ADDRESSABLE (TARGET_EXPR_SLOT (t)) = 1;
7017 }
7018 
7019 
7020 
7021 /* Used to help initialize the builtin-types.def table.  When a type of
7022    the correct size doesn't exist, use error_mark_node instead of NULL.
7023    The later results in segfaults even when a decl using the type doesn't
7024    get invoked.  */
7025 
7026 tree
builtin_type_for_size(int size,bool unsignedp)7027 builtin_type_for_size (int size, bool unsignedp)
7028 {
7029   tree type = c_common_type_for_size (size, unsignedp);
7030   return type ? type : error_mark_node;
7031 }
7032 
7033 /* Work out the size of the first argument of a call to
7034    __builtin_speculation_safe_value.  Only pointers and integral types
7035    are permitted.  Return -1 if the argument type is not supported or
7036    the size is too large; 0 if the argument type is a pointer or the
7037    size if it is integral.  */
7038 static enum built_in_function
speculation_safe_value_resolve_call(tree function,vec<tree,va_gc> * params)7039 speculation_safe_value_resolve_call (tree function, vec<tree, va_gc> *params)
7040 {
7041   /* Type of the argument.  */
7042   tree type;
7043   int size;
7044 
7045   if (vec_safe_is_empty (params))
7046     {
7047       error ("too few arguments to function %qE", function);
7048       return BUILT_IN_NONE;
7049     }
7050 
7051   type = TREE_TYPE ((*params)[0]);
7052   if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7053     {
7054       /* Force array-to-pointer decay for C++.   */
7055       (*params)[0] = default_conversion ((*params)[0]);
7056       type = TREE_TYPE ((*params)[0]);
7057     }
7058 
7059   if (POINTER_TYPE_P (type))
7060     return BUILT_IN_SPECULATION_SAFE_VALUE_PTR;
7061 
7062   if (!INTEGRAL_TYPE_P (type))
7063     goto incompatible;
7064 
7065   if (!COMPLETE_TYPE_P (type))
7066     goto incompatible;
7067 
7068   size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7069   if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7070     return ((enum built_in_function)
7071 	    ((int) BUILT_IN_SPECULATION_SAFE_VALUE_1 + exact_log2 (size)));
7072 
7073  incompatible:
7074   /* Issue the diagnostic only if the argument is valid, otherwise
7075      it would be redundant at best and could be misleading.  */
7076   if (type != error_mark_node)
7077     error ("operand type %qT is incompatible with argument %d of %qE",
7078 	   type, 1, function);
7079 
7080   return BUILT_IN_NONE;
7081 }
7082 
7083 /* Validate and coerce PARAMS, the arguments to ORIG_FUNCTION to fit
7084    the prototype for FUNCTION.  The first argument is mandatory, a second
7085    argument, if present, must be type compatible with the first.  */
7086 static bool
speculation_safe_value_resolve_params(location_t loc,tree orig_function,vec<tree,va_gc> * params)7087 speculation_safe_value_resolve_params (location_t loc, tree orig_function,
7088 				       vec<tree, va_gc> *params)
7089 {
7090   tree val;
7091 
7092   if (params->length () == 0)
7093     {
7094       error_at (loc, "too few arguments to function %qE", orig_function);
7095       return false;
7096     }
7097 
7098   else if (params->length () > 2)
7099     {
7100       error_at (loc, "too many arguments to function %qE", orig_function);
7101       return false;
7102     }
7103 
7104   val = (*params)[0];
7105   if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE)
7106     val = default_conversion (val);
7107   if (!(TREE_CODE (TREE_TYPE (val)) == POINTER_TYPE
7108 	|| TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE))
7109     {
7110       error_at (loc,
7111 		"expecting argument of type pointer or of type integer "
7112 		"for argument 1");
7113       return false;
7114     }
7115   (*params)[0] = val;
7116 
7117   if (params->length () == 2)
7118     {
7119       tree val2 = (*params)[1];
7120       if (TREE_CODE (TREE_TYPE (val2)) == ARRAY_TYPE)
7121 	val2 = default_conversion (val2);
7122       if (error_operand_p (val2))
7123 	return false;
7124       if (!(TREE_TYPE (val) == TREE_TYPE (val2)
7125 	    || useless_type_conversion_p (TREE_TYPE (val), TREE_TYPE (val2))))
7126 	{
7127 	  error_at (loc, "both arguments must be compatible");
7128 	  return false;
7129 	}
7130       (*params)[1] = val2;
7131     }
7132 
7133   return true;
7134 }
7135 
7136 /* Cast the result of the builtin back to the type of the first argument,
7137    preserving any qualifiers that it might have.  */
7138 static tree
speculation_safe_value_resolve_return(tree first_param,tree result)7139 speculation_safe_value_resolve_return (tree first_param, tree result)
7140 {
7141   tree ptype = TREE_TYPE (first_param);
7142   tree rtype = TREE_TYPE (result);
7143   ptype = TYPE_MAIN_VARIANT (ptype);
7144 
7145   if (tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7146     return convert (ptype, result);
7147 
7148   return result;
7149 }
7150 
7151 /* A helper function for resolve_overloaded_builtin in resolving the
7152    overloaded __sync_ builtins.  Returns a positive power of 2 if the
7153    first operand of PARAMS is a pointer to a supported data type.
7154    Returns 0 if an error is encountered.
7155    FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
7156    built-ins.  */
7157 
7158 static int
sync_resolve_size(tree function,vec<tree,va_gc> * params,bool fetch)7159 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch)
7160 {
7161   /* Type of the argument.  */
7162   tree argtype;
7163   /* Type the argument points to.  */
7164   tree type;
7165   int size;
7166 
7167   if (vec_safe_is_empty (params))
7168     {
7169       error ("too few arguments to function %qE", function);
7170       return 0;
7171     }
7172 
7173   argtype = type = TREE_TYPE ((*params)[0]);
7174   if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7175     {
7176       /* Force array-to-pointer decay for C++.  */
7177       (*params)[0] = default_conversion ((*params)[0]);
7178       type = TREE_TYPE ((*params)[0]);
7179     }
7180   if (TREE_CODE (type) != POINTER_TYPE)
7181     goto incompatible;
7182 
7183   type = TREE_TYPE (type);
7184   if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
7185     goto incompatible;
7186 
7187   if (!COMPLETE_TYPE_P (type))
7188     goto incompatible;
7189 
7190   if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
7191     goto incompatible;
7192 
7193   size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7194   if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7195     return size;
7196 
7197  incompatible:
7198   /* Issue the diagnostic only if the argument is valid, otherwise
7199      it would be redundant at best and could be misleading.  */
7200   if (argtype != error_mark_node)
7201     error ("operand type %qT is incompatible with argument %d of %qE",
7202 	   argtype, 1, function);
7203   return 0;
7204 }
7205 
7206 /* A helper function for resolve_overloaded_builtin.  Adds casts to
7207    PARAMS to make arguments match up with those of FUNCTION.  Drops
7208    the variadic arguments at the end.  Returns false if some error
7209    was encountered; true on success.  */
7210 
7211 static bool
sync_resolve_params(location_t loc,tree orig_function,tree function,vec<tree,va_gc> * params,bool orig_format)7212 sync_resolve_params (location_t loc, tree orig_function, tree function,
7213 		     vec<tree, va_gc> *params, bool orig_format)
7214 {
7215   function_args_iterator iter;
7216   tree ptype;
7217   unsigned int parmnum;
7218 
7219   function_args_iter_init (&iter, TREE_TYPE (function));
7220   /* We've declared the implementation functions to use "volatile void *"
7221      as the pointer parameter, so we shouldn't get any complaints from the
7222      call to check_function_arguments what ever type the user used.  */
7223   function_args_iter_next (&iter);
7224   ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
7225   ptype = TYPE_MAIN_VARIANT (ptype);
7226 
7227   /* For the rest of the values, we need to cast these to FTYPE, so that we
7228      don't get warnings for passing pointer types, etc.  */
7229   parmnum = 0;
7230   while (1)
7231     {
7232       tree val, arg_type;
7233 
7234       arg_type = function_args_iter_cond (&iter);
7235       /* XXX void_type_node belies the abstraction.  */
7236       if (arg_type == void_type_node)
7237 	break;
7238 
7239       ++parmnum;
7240       if (params->length () <= parmnum)
7241 	{
7242 	  error_at (loc, "too few arguments to function %qE", orig_function);
7243 	  return false;
7244 	}
7245 
7246       /* Only convert parameters if arg_type is unsigned integer type with
7247 	 new format sync routines, i.e. don't attempt to convert pointer
7248 	 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
7249 	 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
7250 	 kinds).  */
7251       if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
7252 	{
7253 	  /* Ideally for the first conversion we'd use convert_for_assignment
7254 	     so that we get warnings for anything that doesn't match the pointer
7255 	     type.  This isn't portable across the C and C++ front ends atm.  */
7256 	  val = (*params)[parmnum];
7257 	  val = convert (ptype, val);
7258 	  val = convert (arg_type, val);
7259 	  (*params)[parmnum] = val;
7260 	}
7261 
7262       function_args_iter_next (&iter);
7263     }
7264 
7265   /* __atomic routines are not variadic.  */
7266   if (!orig_format && params->length () != parmnum + 1)
7267     {
7268       error_at (loc, "too many arguments to function %qE", orig_function);
7269       return false;
7270     }
7271 
7272   /* The definition of these primitives is variadic, with the remaining
7273      being "an optional list of variables protected by the memory barrier".
7274      No clue what that's supposed to mean, precisely, but we consider all
7275      call-clobbered variables to be protected so we're safe.  */
7276   params->truncate (parmnum + 1);
7277 
7278   return true;
7279 }
7280 
7281 /* A helper function for resolve_overloaded_builtin.  Adds a cast to
7282    RESULT to make it match the type of the first pointer argument in
7283    PARAMS.  */
7284 
7285 static tree
sync_resolve_return(tree first_param,tree result,bool orig_format)7286 sync_resolve_return (tree first_param, tree result, bool orig_format)
7287 {
7288   tree ptype = TREE_TYPE (TREE_TYPE (first_param));
7289   tree rtype = TREE_TYPE (result);
7290   ptype = TYPE_MAIN_VARIANT (ptype);
7291 
7292   /* New format doesn't require casting unless the types are the same size.  */
7293   if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7294     return convert (ptype, result);
7295   else
7296     return result;
7297 }
7298 
7299 /* This function verifies the PARAMS to generic atomic FUNCTION.
7300    It returns the size if all the parameters are the same size, otherwise
7301    0 is returned if the parameters are invalid.  */
7302 
7303 static int
get_atomic_generic_size(location_t loc,tree function,vec<tree,va_gc> * params)7304 get_atomic_generic_size (location_t loc, tree function,
7305 			 vec<tree, va_gc> *params)
7306 {
7307   unsigned int n_param;
7308   unsigned int n_model;
7309   unsigned int outputs = 0; // bitset of output parameters
7310   unsigned int x;
7311   int size_0;
7312   tree type_0;
7313 
7314   /* Determine the parameter makeup.  */
7315   switch (DECL_FUNCTION_CODE (function))
7316     {
7317     case BUILT_IN_ATOMIC_EXCHANGE:
7318       n_param = 4;
7319       n_model = 1;
7320       outputs = 5;
7321       break;
7322     case BUILT_IN_ATOMIC_LOAD:
7323       n_param = 3;
7324       n_model = 1;
7325       outputs = 2;
7326       break;
7327     case BUILT_IN_ATOMIC_STORE:
7328       n_param = 3;
7329       n_model = 1;
7330       outputs = 1;
7331       break;
7332     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7333       n_param = 6;
7334       n_model = 2;
7335       outputs = 3;
7336       break;
7337     default:
7338       gcc_unreachable ();
7339     }
7340 
7341   if (vec_safe_length (params) != n_param)
7342     {
7343       error_at (loc, "incorrect number of arguments to function %qE", function);
7344       return 0;
7345     }
7346 
7347   /* Get type of first parameter, and determine its size.  */
7348   type_0 = TREE_TYPE ((*params)[0]);
7349   if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
7350     {
7351       /* Force array-to-pointer decay for C++.  */
7352       (*params)[0] = default_conversion ((*params)[0]);
7353       type_0 = TREE_TYPE ((*params)[0]);
7354     }
7355   if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
7356     {
7357       error_at (loc, "argument 1 of %qE must be a non-void pointer type",
7358 		function);
7359       return 0;
7360     }
7361 
7362   if (!COMPLETE_TYPE_P (TREE_TYPE (type_0)))
7363     {
7364       error_at (loc, "argument 1 of %qE must be a pointer to a complete type",
7365 		function);
7366       return 0;
7367     }
7368 
7369   /* Types must be compile time constant sizes. */
7370   if (!tree_fits_uhwi_p ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))))
7371     {
7372       error_at (loc,
7373 		"argument 1 of %qE must be a pointer to a constant size type",
7374 		function);
7375       return 0;
7376     }
7377 
7378   size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
7379 
7380   /* Zero size objects are not allowed.  */
7381   if (size_0 == 0)
7382     {
7383       error_at (loc,
7384 		"argument 1 of %qE must be a pointer to a nonzero size object",
7385 		function);
7386       return 0;
7387     }
7388 
7389   /* Check each other parameter is a pointer and the same size.  */
7390   for (x = 0; x < n_param - n_model; x++)
7391     {
7392       int size;
7393       tree type = TREE_TYPE ((*params)[x]);
7394       /* __atomic_compare_exchange has a bool in the 4th position, skip it.  */
7395       if (n_param == 6 && x == 3)
7396         continue;
7397       if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7398 	{
7399 	  /* Force array-to-pointer decay for C++.  */
7400 	  (*params)[x] = default_conversion ((*params)[x]);
7401 	  type = TREE_TYPE ((*params)[x]);
7402 	}
7403       if (!POINTER_TYPE_P (type))
7404 	{
7405 	  error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
7406 		    function);
7407 	  return 0;
7408 	}
7409       else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
7410 	       && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
7411 		  != INTEGER_CST)
7412 	{
7413 	  error_at (loc, "argument %d of %qE must be a pointer to a constant "
7414 		    "size type", x + 1, function);
7415 	  return 0;
7416 	}
7417       else if (FUNCTION_POINTER_TYPE_P (type))
7418 	{
7419 	  error_at (loc, "argument %d of %qE must not be a pointer to a "
7420 		    "function", x + 1, function);
7421 	  return 0;
7422 	}
7423       tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
7424       size = type_size ? tree_to_uhwi (type_size) : 0;
7425       if (size != size_0)
7426 	{
7427 	  error_at (loc, "size mismatch in argument %d of %qE", x + 1,
7428 		    function);
7429 	  return 0;
7430 	}
7431 
7432       {
7433 	auto_diagnostic_group d;
7434 	int quals = TYPE_QUALS (TREE_TYPE (type));
7435 	/* Must not write to an argument of a const-qualified type.  */
7436 	if (outputs & (1 << x) && quals & TYPE_QUAL_CONST)
7437 	  {
7438 	    if (c_dialect_cxx ())
7439 	      {
7440 		error_at (loc, "argument %d of %qE must not be a pointer to "
7441 			  "a %<const%> type", x + 1, function);
7442 		return 0;
7443 	      }
7444 	    else
7445 	      pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7446 		       "of %qE discards %<const%> qualifier", x + 1,
7447 		       function);
7448 	  }
7449 	/* Only the first argument is allowed to be volatile.  */
7450 	if (x > 0 && quals & TYPE_QUAL_VOLATILE)
7451 	  {
7452 	    if (c_dialect_cxx ())
7453 	      {
7454 		error_at (loc, "argument %d of %qE must not be a pointer to "
7455 			  "a %<volatile%> type", x + 1, function);
7456 		return 0;
7457 	      }
7458 	    else
7459 	      pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7460 		       "of %qE discards %<volatile%> qualifier", x + 1,
7461 		       function);
7462 	  }
7463       }
7464     }
7465 
7466   /* Check memory model parameters for validity.  */
7467   for (x = n_param - n_model ; x < n_param; x++)
7468     {
7469       tree p = (*params)[x];
7470       if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
7471 	{
7472 	  error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
7473 		    function);
7474 	  return 0;
7475 	}
7476       p = fold_for_warn (p);
7477       if (TREE_CODE (p) == INTEGER_CST)
7478 	{
7479 	  /* memmodel_base masks the low 16 bits, thus ignore any bits above
7480 	     it by using TREE_INT_CST_LOW instead of tree_to_*hwi.  Those high
7481 	     bits will be checked later during expansion in target specific
7482 	     way.  */
7483 	  if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
7484 	    warning_at (loc, OPT_Winvalid_memory_model,
7485 			"invalid memory model argument %d of %qE", x + 1,
7486 			function);
7487 	}
7488     }
7489 
7490   return size_0;
7491 }
7492 
7493 
7494 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
7495    at the beginning of the parameter list PARAMS representing the size of the
7496    objects.  This is to match the library ABI requirement.  LOC is the location
7497    of the function call.
7498    The new function is returned if it needed rebuilding, otherwise NULL_TREE is
7499    returned to allow the external call to be constructed.  */
7500 
7501 static tree
add_atomic_size_parameter(unsigned n,location_t loc,tree function,vec<tree,va_gc> * params)7502 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
7503 			   vec<tree, va_gc> *params)
7504 {
7505   tree size_node;
7506 
7507   /* Insert a SIZE_T parameter as the first param.  If there isn't
7508      enough space, allocate a new vector and recursively re-build with that.  */
7509   if (!params->space (1))
7510     {
7511       unsigned int z, len;
7512       vec<tree, va_gc> *v;
7513       tree f;
7514 
7515       len = params->length ();
7516       vec_alloc (v, len + 1);
7517       v->quick_push (build_int_cst (size_type_node, n));
7518       for (z = 0; z < len; z++)
7519 	v->quick_push ((*params)[z]);
7520       f = build_function_call_vec (loc, vNULL, function, v, NULL);
7521       vec_free (v);
7522       return f;
7523     }
7524 
7525   /* Add the size parameter and leave as a function call for processing.  */
7526   size_node = build_int_cst (size_type_node, n);
7527   params->quick_insert (0, size_node);
7528   return NULL_TREE;
7529 }
7530 
7531 
7532 /* Return whether atomic operations for naturally aligned N-byte
7533    arguments are supported, whether inline or through libatomic.  */
7534 static bool
atomic_size_supported_p(int n)7535 atomic_size_supported_p (int n)
7536 {
7537   switch (n)
7538     {
7539     case 1:
7540     case 2:
7541     case 4:
7542     case 8:
7543       return true;
7544 
7545     case 16:
7546       return targetm.scalar_mode_supported_p (TImode);
7547 
7548     default:
7549       return false;
7550     }
7551 }
7552 
7553 /* This will process an __atomic_exchange function call, determine whether it
7554    needs to be mapped to the _N variation, or turned into a library call.
7555    LOC is the location of the builtin call.
7556    FUNCTION is the DECL that has been invoked;
7557    PARAMS is the argument list for the call.  The return value is non-null
7558    TRUE is returned if it is translated into the proper format for a call to the
7559    external library, and NEW_RETURN is set the tree for that function.
7560    FALSE is returned if processing for the _N variation is required, and
7561    NEW_RETURN is set to the return value the result is copied into.  */
7562 static bool
resolve_overloaded_atomic_exchange(location_t loc,tree function,vec<tree,va_gc> * params,tree * new_return)7563 resolve_overloaded_atomic_exchange (location_t loc, tree function,
7564 				    vec<tree, va_gc> *params, tree *new_return)
7565 {
7566   tree p0, p1, p2, p3;
7567   tree I_type, I_type_ptr;
7568   int n = get_atomic_generic_size (loc, function, params);
7569 
7570   /* Size of 0 is an error condition.  */
7571   if (n == 0)
7572     {
7573       *new_return = error_mark_node;
7574       return true;
7575     }
7576 
7577   /* If not a lock-free size, change to the library generic format.  */
7578   if (!atomic_size_supported_p (n))
7579     {
7580       *new_return = add_atomic_size_parameter (n, loc, function, params);
7581       return true;
7582     }
7583 
7584   /* Otherwise there is a lockfree match, transform the call from:
7585        void fn(T* mem, T* desired, T* return, model)
7586      into
7587        *return = (T) (fn (In* mem, (In) *desired, model))  */
7588 
7589   p0 = (*params)[0];
7590   p1 = (*params)[1];
7591   p2 = (*params)[2];
7592   p3 = (*params)[3];
7593 
7594   /* Create pointer to appropriate size.  */
7595   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7596   I_type_ptr = build_pointer_type (I_type);
7597 
7598   /* Convert object pointer to required type.  */
7599   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7600   (*params)[0] = p0;
7601   /* Convert new value to required type, and dereference it.  */
7602   p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7603   p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7604   (*params)[1] = p1;
7605 
7606   /* Move memory model to the 3rd position, and end param list.  */
7607   (*params)[2] = p3;
7608   params->truncate (3);
7609 
7610   /* Convert return pointer and dereference it for later assignment.  */
7611   *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7612 
7613   return false;
7614 }
7615 
7616 
7617 /* This will process an __atomic_compare_exchange function call, determine
7618    whether it needs to be mapped to the _N variation, or turned into a lib call.
7619    LOC is the location of the builtin call.
7620    FUNCTION is the DECL that has been invoked;
7621    PARAMS is the argument list for the call.  The return value is non-null
7622    TRUE is returned if it is translated into the proper format for a call to the
7623    external library, and NEW_RETURN is set the tree for that function.
7624    FALSE is returned if processing for the _N variation is required.  */
7625 
7626 static bool
resolve_overloaded_atomic_compare_exchange(location_t loc,tree function,vec<tree,va_gc> * params,tree * new_return)7627 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
7628 					    vec<tree, va_gc> *params,
7629 					    tree *new_return)
7630 {
7631   tree p0, p1, p2;
7632   tree I_type, I_type_ptr;
7633   int n = get_atomic_generic_size (loc, function, params);
7634 
7635   /* Size of 0 is an error condition.  */
7636   if (n == 0)
7637     {
7638       *new_return = error_mark_node;
7639       return true;
7640     }
7641 
7642   /* If not a lock-free size, change to the library generic format.  */
7643   if (!atomic_size_supported_p (n))
7644     {
7645       /* The library generic format does not have the weak parameter, so
7646 	 remove it from the param list.  Since a parameter has been removed,
7647 	 we can be sure that there is room for the SIZE_T parameter, meaning
7648 	 there will not be a recursive rebuilding of the parameter list, so
7649 	 there is no danger this will be done twice.  */
7650       if (n > 0)
7651         {
7652 	  (*params)[3] = (*params)[4];
7653 	  (*params)[4] = (*params)[5];
7654 	  params->truncate (5);
7655 	}
7656       *new_return = add_atomic_size_parameter (n, loc, function, params);
7657       return true;
7658     }
7659 
7660   /* Otherwise, there is a match, so the call needs to be transformed from:
7661        bool fn(T* mem, T* desired, T* return, weak, success, failure)
7662      into
7663        bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail)  */
7664 
7665   p0 = (*params)[0];
7666   p1 = (*params)[1];
7667   p2 = (*params)[2];
7668 
7669   /* Create pointer to appropriate size.  */
7670   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7671   I_type_ptr = build_pointer_type (I_type);
7672 
7673   /* Convert object pointer to required type.  */
7674   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7675   (*params)[0] = p0;
7676 
7677   /* Convert expected pointer to required type.  */
7678   p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
7679   (*params)[1] = p1;
7680 
7681   /* Convert desired value to required type, and dereference it.  */
7682   p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7683   p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
7684   (*params)[2] = p2;
7685 
7686   /* The rest of the parameters are fine. NULL means no special return value
7687      processing.*/
7688   *new_return = NULL;
7689   return false;
7690 }
7691 
7692 
7693 /* This will process an __atomic_load function call, determine whether it
7694    needs to be mapped to the _N variation, or turned into a library call.
7695    LOC is the location of the builtin call.
7696    FUNCTION is the DECL that has been invoked;
7697    PARAMS is the argument list for the call.  The return value is non-null
7698    TRUE is returned if it is translated into the proper format for a call to the
7699    external library, and NEW_RETURN is set the tree for that function.
7700    FALSE is returned if processing for the _N variation is required, and
7701    NEW_RETURN is set to the return value the result is copied into.  */
7702 
7703 static bool
resolve_overloaded_atomic_load(location_t loc,tree function,vec<tree,va_gc> * params,tree * new_return)7704 resolve_overloaded_atomic_load (location_t loc, tree function,
7705 				vec<tree, va_gc> *params, tree *new_return)
7706 {
7707   tree p0, p1, p2;
7708   tree I_type, I_type_ptr;
7709   int n = get_atomic_generic_size (loc, function, params);
7710 
7711   /* Size of 0 is an error condition.  */
7712   if (n == 0)
7713     {
7714       *new_return = error_mark_node;
7715       return true;
7716     }
7717 
7718   /* If not a lock-free size, change to the library generic format.  */
7719   if (!atomic_size_supported_p (n))
7720     {
7721       *new_return = add_atomic_size_parameter (n, loc, function, params);
7722       return true;
7723     }
7724 
7725   /* Otherwise, there is a match, so the call needs to be transformed from:
7726        void fn(T* mem, T* return, model)
7727      into
7728        *return = (T) (fn ((In *) mem, model))  */
7729 
7730   p0 = (*params)[0];
7731   p1 = (*params)[1];
7732   p2 = (*params)[2];
7733 
7734   /* Create pointer to appropriate size.  */
7735   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7736   I_type_ptr = build_pointer_type (I_type);
7737 
7738   /* Convert object pointer to required type.  */
7739   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7740   (*params)[0] = p0;
7741 
7742   /* Move memory model to the 2nd position, and end param list.  */
7743   (*params)[1] = p2;
7744   params->truncate (2);
7745 
7746   /* Convert return pointer and dereference it for later assignment.  */
7747   *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7748 
7749   return false;
7750 }
7751 
7752 
7753 /* This will process an __atomic_store function call, determine whether it
7754    needs to be mapped to the _N variation, or turned into a library call.
7755    LOC is the location of the builtin call.
7756    FUNCTION is the DECL that has been invoked;
7757    PARAMS is the argument list for the call.  The return value is non-null
7758    TRUE is returned if it is translated into the proper format for a call to the
7759    external library, and NEW_RETURN is set the tree for that function.
7760    FALSE is returned if processing for the _N variation is required, and
7761    NEW_RETURN is set to the return value the result is copied into.  */
7762 
7763 static bool
resolve_overloaded_atomic_store(location_t loc,tree function,vec<tree,va_gc> * params,tree * new_return)7764 resolve_overloaded_atomic_store (location_t loc, tree function,
7765 				 vec<tree, va_gc> *params, tree *new_return)
7766 {
7767   tree p0, p1;
7768   tree I_type, I_type_ptr;
7769   int n = get_atomic_generic_size (loc, function, params);
7770 
7771   /* Size of 0 is an error condition.  */
7772   if (n == 0)
7773     {
7774       *new_return = error_mark_node;
7775       return true;
7776     }
7777 
7778   /* If not a lock-free size, change to the library generic format.  */
7779   if (!atomic_size_supported_p (n))
7780     {
7781       *new_return = add_atomic_size_parameter (n, loc, function, params);
7782       return true;
7783     }
7784 
7785   /* Otherwise, there is a match, so the call needs to be transformed from:
7786        void fn(T* mem, T* value, model)
7787      into
7788        fn ((In *) mem, (In) *value, model)  */
7789 
7790   p0 = (*params)[0];
7791   p1 = (*params)[1];
7792 
7793   /* Create pointer to appropriate size.  */
7794   I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7795   I_type_ptr = build_pointer_type (I_type);
7796 
7797   /* Convert object pointer to required type.  */
7798   p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7799   (*params)[0] = p0;
7800 
7801   /* Convert new value to required type, and dereference it.  */
7802   p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7803   p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7804   (*params)[1] = p1;
7805 
7806   /* The memory model is in the right spot already. Return is void.  */
7807   *new_return = NULL_TREE;
7808 
7809   return false;
7810 }
7811 
7812 
7813 /* Some builtin functions are placeholders for other expressions.  This
7814    function should be called immediately after parsing the call expression
7815    before surrounding code has committed to the type of the expression.
7816 
7817    LOC is the location of the builtin call.
7818 
7819    FUNCTION is the DECL that has been invoked; it is known to be a builtin.
7820    PARAMS is the argument list for the call.  The return value is non-null
7821    when expansion is complete, and null if normal processing should
7822    continue.  */
7823 
7824 tree
resolve_overloaded_builtin(location_t loc,tree function,vec<tree,va_gc> * params)7825 resolve_overloaded_builtin (location_t loc, tree function,
7826 			    vec<tree, va_gc> *params)
7827 {
7828   /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
7829      Those are not valid to call with a pointer to _Bool (or C++ bool)
7830      and so must be rejected.  */
7831   bool fetch_op = true;
7832   bool orig_format = true;
7833   tree new_return = NULL_TREE;
7834 
7835   switch (DECL_BUILT_IN_CLASS (function))
7836     {
7837     case BUILT_IN_NORMAL:
7838       break;
7839     case BUILT_IN_MD:
7840       if (targetm.resolve_overloaded_builtin)
7841 	return targetm.resolve_overloaded_builtin (loc, function, params);
7842       else
7843 	return NULL_TREE;
7844     default:
7845       return NULL_TREE;
7846     }
7847 
7848   /* Handle BUILT_IN_NORMAL here.  */
7849   enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
7850   switch (orig_code)
7851     {
7852     case BUILT_IN_SPECULATION_SAFE_VALUE_N:
7853       {
7854 	tree new_function, first_param, result;
7855 	enum built_in_function fncode
7856 	  = speculation_safe_value_resolve_call (function, params);
7857 
7858 	if (fncode == BUILT_IN_NONE)
7859 	  return error_mark_node;
7860 
7861 	first_param = (*params)[0];
7862 	if (!speculation_safe_value_resolve_params (loc, function, params))
7863 	  return error_mark_node;
7864 
7865 	if (targetm.have_speculation_safe_value (true))
7866 	  {
7867 	    new_function = builtin_decl_explicit (fncode);
7868 	    result = build_function_call_vec (loc, vNULL, new_function, params,
7869 					      NULL);
7870 
7871 	    if (result == error_mark_node)
7872 	      return result;
7873 
7874 	    return speculation_safe_value_resolve_return (first_param, result);
7875 	  }
7876 	else
7877 	  {
7878 	    /* This target doesn't have, or doesn't need, active mitigation
7879 	       against incorrect speculative execution.  Simply return the
7880 	       first parameter to the builtin.  */
7881 	    if (!targetm.have_speculation_safe_value (false))
7882 	      /* The user has invoked __builtin_speculation_safe_value
7883 		 even though __HAVE_SPECULATION_SAFE_VALUE is not
7884 		 defined: emit a warning.  */
7885 	      warning_at (input_location, 0,
7886 			  "this target does not define a speculation barrier; "
7887 			  "your program will still execute correctly, "
7888 			  "but incorrect speculation may not be "
7889 			  "restricted");
7890 
7891 	    /* If the optional second argument is present, handle any side
7892 	       effects now.  */
7893 	    if (params->length () == 2
7894 		&& TREE_SIDE_EFFECTS ((*params)[1]))
7895 	      return build2 (COMPOUND_EXPR, TREE_TYPE (first_param),
7896 			     (*params)[1], first_param);
7897 
7898 	    return first_param;
7899 	  }
7900       }
7901 
7902     case BUILT_IN_ATOMIC_EXCHANGE:
7903     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7904     case BUILT_IN_ATOMIC_LOAD:
7905     case BUILT_IN_ATOMIC_STORE:
7906       {
7907 	/* Handle these 4 together so that they can fall through to the next
7908 	   case if the call is transformed to an _N variant.  */
7909         switch (orig_code)
7910 	  {
7911 	  case BUILT_IN_ATOMIC_EXCHANGE:
7912 	    {
7913 	      if (resolve_overloaded_atomic_exchange (loc, function, params,
7914 						      &new_return))
7915 		return new_return;
7916 	      /* Change to the _N variant.  */
7917 	      orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
7918 	      break;
7919 	    }
7920 
7921 	  case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7922 	    {
7923 	      if (resolve_overloaded_atomic_compare_exchange (loc, function,
7924 							      params,
7925 							      &new_return))
7926 		return new_return;
7927 	      /* Change to the _N variant.  */
7928 	      orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
7929 	      break;
7930 	    }
7931 	  case BUILT_IN_ATOMIC_LOAD:
7932 	    {
7933 	      if (resolve_overloaded_atomic_load (loc, function, params,
7934 						  &new_return))
7935 		return new_return;
7936 	      /* Change to the _N variant.  */
7937 	      orig_code = BUILT_IN_ATOMIC_LOAD_N;
7938 	      break;
7939 	    }
7940 	  case BUILT_IN_ATOMIC_STORE:
7941 	    {
7942 	      if (resolve_overloaded_atomic_store (loc, function, params,
7943 						   &new_return))
7944 		return new_return;
7945 	      /* Change to the _N variant.  */
7946 	      orig_code = BUILT_IN_ATOMIC_STORE_N;
7947 	      break;
7948 	    }
7949 	  default:
7950 	    gcc_unreachable ();
7951 	  }
7952       }
7953       /* FALLTHRU */
7954     case BUILT_IN_ATOMIC_EXCHANGE_N:
7955     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
7956     case BUILT_IN_ATOMIC_LOAD_N:
7957     case BUILT_IN_ATOMIC_STORE_N:
7958       fetch_op = false;
7959       /* FALLTHRU */
7960     case BUILT_IN_ATOMIC_ADD_FETCH_N:
7961     case BUILT_IN_ATOMIC_SUB_FETCH_N:
7962     case BUILT_IN_ATOMIC_AND_FETCH_N:
7963     case BUILT_IN_ATOMIC_NAND_FETCH_N:
7964     case BUILT_IN_ATOMIC_XOR_FETCH_N:
7965     case BUILT_IN_ATOMIC_OR_FETCH_N:
7966     case BUILT_IN_ATOMIC_FETCH_ADD_N:
7967     case BUILT_IN_ATOMIC_FETCH_SUB_N:
7968     case BUILT_IN_ATOMIC_FETCH_AND_N:
7969     case BUILT_IN_ATOMIC_FETCH_NAND_N:
7970     case BUILT_IN_ATOMIC_FETCH_XOR_N:
7971     case BUILT_IN_ATOMIC_FETCH_OR_N:
7972       orig_format = false;
7973       /* FALLTHRU */
7974     case BUILT_IN_SYNC_FETCH_AND_ADD_N:
7975     case BUILT_IN_SYNC_FETCH_AND_SUB_N:
7976     case BUILT_IN_SYNC_FETCH_AND_OR_N:
7977     case BUILT_IN_SYNC_FETCH_AND_AND_N:
7978     case BUILT_IN_SYNC_FETCH_AND_XOR_N:
7979     case BUILT_IN_SYNC_FETCH_AND_NAND_N:
7980     case BUILT_IN_SYNC_ADD_AND_FETCH_N:
7981     case BUILT_IN_SYNC_SUB_AND_FETCH_N:
7982     case BUILT_IN_SYNC_OR_AND_FETCH_N:
7983     case BUILT_IN_SYNC_AND_AND_FETCH_N:
7984     case BUILT_IN_SYNC_XOR_AND_FETCH_N:
7985     case BUILT_IN_SYNC_NAND_AND_FETCH_N:
7986     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
7987     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
7988     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
7989     case BUILT_IN_SYNC_LOCK_RELEASE_N:
7990       {
7991 	/* The following are not _FETCH_OPs and must be accepted with
7992 	   pointers to _Bool (or C++ bool).  */
7993 	if (fetch_op)
7994 	  fetch_op =
7995 	    (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7996 	     && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
7997 	     && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
7998 	     && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
7999 
8000 	int n = sync_resolve_size (function, params, fetch_op);
8001 	tree new_function, first_param, result;
8002 	enum built_in_function fncode;
8003 
8004 	if (n == 0)
8005 	  return error_mark_node;
8006 
8007 	fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
8008 	new_function = builtin_decl_explicit (fncode);
8009 	if (!sync_resolve_params (loc, function, new_function, params,
8010 				  orig_format))
8011 	  return error_mark_node;
8012 
8013 	first_param = (*params)[0];
8014 	result = build_function_call_vec (loc, vNULL, new_function, params,
8015 					  NULL);
8016 	if (result == error_mark_node)
8017 	  return result;
8018 	if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8019 	    && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
8020 	    && orig_code != BUILT_IN_ATOMIC_STORE_N
8021 	    && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
8022 	  result = sync_resolve_return (first_param, result, orig_format);
8023 
8024 	if (fetch_op)
8025 	  /* Prevent -Wunused-value warning.  */
8026 	  TREE_USED (result) = true;
8027 
8028 	/* If new_return is set, assign function to that expr and cast the
8029 	   result to void since the generic interface returned void.  */
8030 	if (new_return)
8031 	  {
8032 	    /* Cast function result from I{1,2,4,8,16} to the required type.  */
8033 	    result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
8034 	    result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
8035 			     result);
8036 	    TREE_SIDE_EFFECTS (result) = 1;
8037 	    protected_set_expr_location (result, loc);
8038 	    result = convert (void_type_node, result);
8039 	  }
8040 	return result;
8041       }
8042 
8043     default:
8044       return NULL_TREE;
8045     }
8046 }
8047 
8048 /* vector_types_compatible_elements_p is used in type checks of vectors
8049    values used as operands of binary operators.  Where it returns true, and
8050    the other checks of the caller succeed (being vector types in he first
8051    place, and matching number of elements), we can just treat the types
8052    as essentially the same.
8053    Contrast with vector_targets_convertible_p, which is used for vector
8054    pointer types,  and vector_types_convertible_p, which will allow
8055    language-specific matches under the control of flag_lax_vector_conversions,
8056    and might still require a conversion.  */
8057 /* True if vector types T1 and T2 can be inputs to the same binary
8058    operator without conversion.
8059    We don't check the overall vector size here because some of our callers
8060    want to give different error messages when the vectors are compatible
8061    except for the element count.  */
8062 
8063 bool
vector_types_compatible_elements_p(tree t1,tree t2)8064 vector_types_compatible_elements_p (tree t1, tree t2)
8065 {
8066   bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
8067   t1 = TREE_TYPE (t1);
8068   t2 = TREE_TYPE (t2);
8069 
8070   enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
8071 
8072   gcc_assert ((INTEGRAL_TYPE_P (t1)
8073 	       || c1 == REAL_TYPE
8074 	       || c1 == FIXED_POINT_TYPE)
8075 	      && (INTEGRAL_TYPE_P (t2)
8076 		  || c2 == REAL_TYPE
8077 		  || c2 == FIXED_POINT_TYPE));
8078 
8079   t1 = c_common_signed_type (t1);
8080   t2 = c_common_signed_type (t2);
8081   /* Equality works here because c_common_signed_type uses
8082      TYPE_MAIN_VARIANT.  */
8083   if (t1 == t2)
8084     return true;
8085   if (opaque && c1 == c2
8086       && (INTEGRAL_TYPE_P (t1) || c1 == REAL_TYPE)
8087       && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
8088     return true;
8089   return false;
8090 }
8091 
8092 /* Check for missing format attributes on function pointers.  LTYPE is
8093    the new type or left-hand side type.  RTYPE is the old type or
8094    right-hand side type.  Returns TRUE if LTYPE is missing the desired
8095    attribute.  */
8096 
8097 bool
check_missing_format_attribute(tree ltype,tree rtype)8098 check_missing_format_attribute (tree ltype, tree rtype)
8099 {
8100   tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
8101   tree ra;
8102 
8103   for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
8104     if (is_attribute_p ("format", get_attribute_name (ra)))
8105       break;
8106   if (ra)
8107     {
8108       tree la;
8109       for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
8110 	if (is_attribute_p ("format", get_attribute_name (la)))
8111 	  break;
8112       return !la;
8113     }
8114   else
8115     return false;
8116 }
8117 
8118 /* Setup a TYPE_DECL node as a typedef representation.
8119 
8120    X is a TYPE_DECL for a typedef statement.  Create a brand new
8121    ..._TYPE node (which will be just a variant of the existing
8122    ..._TYPE node with identical properties) and then install X
8123    as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
8124 
8125    The whole point here is to end up with a situation where each
8126    and every ..._TYPE node the compiler creates will be uniquely
8127    associated with AT MOST one node representing a typedef name.
8128    This way, even though the compiler substitutes corresponding
8129    ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
8130    early on, later parts of the compiler can always do the reverse
8131    translation and get back the corresponding typedef name.  For
8132    example, given:
8133 
8134 	typedef struct S MY_TYPE;
8135 	MY_TYPE object;
8136 
8137    Later parts of the compiler might only know that `object' was of
8138    type `struct S' if it were not for code just below.  With this
8139    code however, later parts of the compiler see something like:
8140 
8141 	struct S' == struct S
8142 	typedef struct S' MY_TYPE;
8143 	struct S' object;
8144 
8145     And they can then deduce (from the node for type struct S') that
8146     the original object declaration was:
8147 
8148 		MY_TYPE object;
8149 
8150     Being able to do this is important for proper support of protoize,
8151     and also for generating precise symbolic debugging information
8152     which takes full account of the programmer's (typedef) vocabulary.
8153 
8154     Obviously, we don't want to generate a duplicate ..._TYPE node if
8155     the TYPE_DECL node that we are now processing really represents a
8156     standard built-in type.  */
8157 
8158 void
set_underlying_type(tree x)8159 set_underlying_type (tree x)
8160 {
8161   if (x == error_mark_node)
8162     return;
8163   if (DECL_IS_UNDECLARED_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
8164     {
8165       if (TYPE_NAME (TREE_TYPE (x)) == 0)
8166 	TYPE_NAME (TREE_TYPE (x)) = x;
8167     }
8168   else if (TREE_TYPE (x) != error_mark_node
8169 	   && DECL_ORIGINAL_TYPE (x) == NULL_TREE)
8170     {
8171       tree tt = TREE_TYPE (x);
8172       DECL_ORIGINAL_TYPE (x) = tt;
8173       tt = build_variant_type_copy (tt);
8174       TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
8175       TYPE_NAME (tt) = x;
8176 
8177       /* Mark the type as used only when its type decl is decorated
8178 	 with attribute unused.  */
8179       if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
8180 	TREE_USED (tt) = 1;
8181 
8182       TREE_TYPE (x) = tt;
8183     }
8184 }
8185 
8186 /* Return true if it is worth exposing the DECL_ORIGINAL_TYPE of TYPE to
8187    the user in diagnostics, false if it would be better to use TYPE itself.
8188    TYPE is known to satisfy typedef_variant_p.  */
8189 
8190 bool
user_facing_original_type_p(const_tree type)8191 user_facing_original_type_p (const_tree type)
8192 {
8193   gcc_assert (typedef_variant_p (type));
8194   tree decl = TYPE_NAME (type);
8195 
8196   /* Look through any typedef in "user" code.  */
8197   if (!DECL_IN_SYSTEM_HEADER (decl) && !DECL_IS_UNDECLARED_BUILTIN (decl))
8198     return true;
8199 
8200   /* If the original type is also named and is in the user namespace,
8201      assume it too is a user-facing type.  */
8202   tree orig_type = DECL_ORIGINAL_TYPE (decl);
8203   if (tree orig_id = TYPE_IDENTIFIER (orig_type))
8204     if (!name_reserved_for_implementation_p (IDENTIFIER_POINTER (orig_id)))
8205       return true;
8206 
8207   switch (TREE_CODE (orig_type))
8208     {
8209     /* Don't look through to an anonymous vector type, since the syntax
8210        we use for them in diagnostics isn't real C or C++ syntax.
8211        And if ORIG_TYPE is named but in the implementation namespace,
8212        TYPE is likely to be more meaningful to the user.  */
8213     case VECTOR_TYPE:
8214       return false;
8215 
8216     /* Don't expose anonymous tag types that are presumably meant to be
8217        known by their typedef name.  Also don't expose tags that are in
8218        the implementation namespace, such as:
8219 
8220          typedef struct __foo foo;  */
8221     case RECORD_TYPE:
8222     case UNION_TYPE:
8223     case ENUMERAL_TYPE:
8224       return false;
8225 
8226     /* Look through to anything else.  */
8227     default:
8228       return true;
8229     }
8230 }
8231 
8232 /* Record the types used by the current global variable declaration
8233    being parsed, so that we can decide later to emit their debug info.
8234    Those types are in types_used_by_cur_var_decl, and we are going to
8235    store them in the types_used_by_vars_hash hash table.
8236    DECL is the declaration of the global variable that has been parsed.  */
8237 
8238 void
record_types_used_by_current_var_decl(tree decl)8239 record_types_used_by_current_var_decl (tree decl)
8240 {
8241   gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
8242 
8243   while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
8244     {
8245       tree type = types_used_by_cur_var_decl->pop ();
8246       types_used_by_var_decl_insert (type, decl);
8247     }
8248 }
8249 
8250 /* The C and C++ parsers both use vectors to hold function arguments.
8251    For efficiency, we keep a cache of unused vectors.  This is the
8252    cache.  */
8253 
8254 typedef vec<tree, va_gc> *tree_gc_vec;
8255 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
8256 
8257 /* Return a new vector from the cache.  If the cache is empty,
8258    allocate a new vector.  These vectors are GC'ed, so it is OK if the
8259    pointer is not released..  */
8260 
8261 vec<tree, va_gc> *
make_tree_vector(void)8262 make_tree_vector (void)
8263 {
8264   if (tree_vector_cache && !tree_vector_cache->is_empty ())
8265     return tree_vector_cache->pop ();
8266   else
8267     {
8268       /* Passing 0 to vec::alloc returns NULL, and our callers require
8269 	 that we always return a non-NULL value.  The vector code uses
8270 	 4 when growing a NULL vector, so we do too.  */
8271       vec<tree, va_gc> *v;
8272       vec_alloc (v, 4);
8273       return v;
8274     }
8275 }
8276 
8277 /* Release a vector of trees back to the cache.  */
8278 
8279 void
release_tree_vector(vec<tree,va_gc> * vec)8280 release_tree_vector (vec<tree, va_gc> *vec)
8281 {
8282   if (vec != NULL)
8283     {
8284       if (vec->allocated () >= 16)
8285 	/* Don't cache vecs that have expanded more than once.  On a p64
8286 	   target, vecs double in alloc size with each power of 2 elements, e.g
8287 	   at 16 elements the alloc increases from 128 to 256 bytes.  */
8288 	vec_free (vec);
8289       else
8290 	{
8291 	  vec->truncate (0);
8292 	  vec_safe_push (tree_vector_cache, vec);
8293 	}
8294     }
8295 }
8296 
8297 /* Get a new tree vector holding a single tree.  */
8298 
8299 vec<tree, va_gc> *
make_tree_vector_single(tree t)8300 make_tree_vector_single (tree t)
8301 {
8302   vec<tree, va_gc> *ret = make_tree_vector ();
8303   ret->quick_push (t);
8304   return ret;
8305 }
8306 
8307 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain.  */
8308 
8309 vec<tree, va_gc> *
make_tree_vector_from_list(tree list)8310 make_tree_vector_from_list (tree list)
8311 {
8312   vec<tree, va_gc> *ret = make_tree_vector ();
8313   for (; list; list = TREE_CHAIN (list))
8314     vec_safe_push (ret, TREE_VALUE (list));
8315   return ret;
8316 }
8317 
8318 /* Get a new tree vector of the values of a CONSTRUCTOR.  */
8319 
8320 vec<tree, va_gc> *
make_tree_vector_from_ctor(tree ctor)8321 make_tree_vector_from_ctor (tree ctor)
8322 {
8323   vec<tree,va_gc> *ret = make_tree_vector ();
8324   vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
8325   for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
8326     ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
8327   return ret;
8328 }
8329 
8330 /* Get a new tree vector which is a copy of an existing one.  */
8331 
8332 vec<tree, va_gc> *
make_tree_vector_copy(const vec<tree,va_gc> * orig)8333 make_tree_vector_copy (const vec<tree, va_gc> *orig)
8334 {
8335   vec<tree, va_gc> *ret;
8336   unsigned int ix;
8337   tree t;
8338 
8339   ret = make_tree_vector ();
8340   vec_safe_reserve (ret, vec_safe_length (orig));
8341   FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
8342     ret->quick_push (t);
8343   return ret;
8344 }
8345 
8346 /* Return true if KEYWORD starts a type specifier.  */
8347 
8348 bool
keyword_begins_type_specifier(enum rid keyword)8349 keyword_begins_type_specifier (enum rid keyword)
8350 {
8351   switch (keyword)
8352     {
8353     case RID_AUTO_TYPE:
8354     case RID_INT:
8355     case RID_CHAR:
8356     case RID_FLOAT:
8357     case RID_DOUBLE:
8358     case RID_VOID:
8359     case RID_UNSIGNED:
8360     case RID_LONG:
8361     case RID_SHORT:
8362     case RID_SIGNED:
8363     CASE_RID_FLOATN_NX:
8364     case RID_DFLOAT32:
8365     case RID_DFLOAT64:
8366     case RID_DFLOAT128:
8367     case RID_FRACT:
8368     case RID_ACCUM:
8369     case RID_BOOL:
8370     case RID_WCHAR:
8371     case RID_CHAR8:
8372     case RID_CHAR16:
8373     case RID_CHAR32:
8374     case RID_SAT:
8375     case RID_COMPLEX:
8376     case RID_TYPEOF:
8377     case RID_STRUCT:
8378     case RID_CLASS:
8379     case RID_UNION:
8380     case RID_ENUM:
8381       return true;
8382     default:
8383       if (keyword >= RID_FIRST_INT_N
8384 	  && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
8385 	  && int_n_enabled_p[keyword-RID_FIRST_INT_N])
8386 	return true;
8387       return false;
8388     }
8389 }
8390 
8391 /* Return true if KEYWORD names a type qualifier.  */
8392 
8393 bool
keyword_is_type_qualifier(enum rid keyword)8394 keyword_is_type_qualifier (enum rid keyword)
8395 {
8396   switch (keyword)
8397     {
8398     case RID_CONST:
8399     case RID_VOLATILE:
8400     case RID_RESTRICT:
8401     case RID_ATOMIC:
8402       return true;
8403     default:
8404       return false;
8405     }
8406 }
8407 
8408 /* Return true if KEYWORD names a storage class specifier.
8409 
8410    RID_TYPEDEF is not included in this list despite `typedef' being
8411    listed in C99 6.7.1.1.  6.7.1.3 indicates that `typedef' is listed as
8412    such for syntactic convenience only.  */
8413 
8414 bool
keyword_is_storage_class_specifier(enum rid keyword)8415 keyword_is_storage_class_specifier (enum rid keyword)
8416 {
8417   switch (keyword)
8418     {
8419     case RID_STATIC:
8420     case RID_EXTERN:
8421     case RID_REGISTER:
8422     case RID_AUTO:
8423     case RID_MUTABLE:
8424     case RID_THREAD:
8425       return true;
8426     default:
8427       return false;
8428     }
8429 }
8430 
8431 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec].  */
8432 
8433 static bool
keyword_is_function_specifier(enum rid keyword)8434 keyword_is_function_specifier (enum rid keyword)
8435 {
8436   switch (keyword)
8437     {
8438     case RID_INLINE:
8439     case RID_NORETURN:
8440     case RID_VIRTUAL:
8441     case RID_EXPLICIT:
8442       return true;
8443     default:
8444       return false;
8445     }
8446 }
8447 
8448 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
8449    declaration-specifier (C99 6.7).  */
8450 
8451 bool
keyword_is_decl_specifier(enum rid keyword)8452 keyword_is_decl_specifier (enum rid keyword)
8453 {
8454   if (keyword_is_storage_class_specifier (keyword)
8455       || keyword_is_type_qualifier (keyword)
8456       || keyword_is_function_specifier (keyword))
8457     return true;
8458 
8459   switch (keyword)
8460     {
8461     case RID_TYPEDEF:
8462     case RID_FRIEND:
8463     case RID_CONSTEXPR:
8464     case RID_CONSTINIT:
8465       return true;
8466     default:
8467       return false;
8468     }
8469 }
8470 
8471 /* Initialize language-specific-bits of tree_contains_struct.  */
8472 
8473 void
c_common_init_ts(void)8474 c_common_init_ts (void)
8475 {
8476   MARK_TS_EXP (SIZEOF_EXPR);
8477   MARK_TS_EXP (PAREN_SIZEOF_EXPR);
8478   MARK_TS_EXP (C_MAYBE_CONST_EXPR);
8479   MARK_TS_EXP (EXCESS_PRECISION_EXPR);
8480   MARK_TS_EXP (BREAK_STMT);
8481   MARK_TS_EXP (CONTINUE_STMT);
8482   MARK_TS_EXP (DO_STMT);
8483   MARK_TS_EXP (FOR_STMT);
8484   MARK_TS_EXP (SWITCH_STMT);
8485   MARK_TS_EXP (WHILE_STMT);
8486 }
8487 
8488 /* Build a user-defined numeric literal out of an integer constant type VALUE
8489    with identifier SUFFIX.  */
8490 
8491 tree
build_userdef_literal(tree suffix_id,tree value,enum overflow_type overflow,tree num_string)8492 build_userdef_literal (tree suffix_id, tree value,
8493 		       enum overflow_type overflow, tree num_string)
8494 {
8495   tree literal = make_node (USERDEF_LITERAL);
8496   USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
8497   USERDEF_LITERAL_VALUE (literal) = value;
8498   USERDEF_LITERAL_OVERFLOW (literal) = overflow;
8499   USERDEF_LITERAL_NUM_STRING (literal) = num_string;
8500   return literal;
8501 }
8502 
8503 /* For vector[index], convert the vector to an array of the underlying type.
8504    Return true if the resulting ARRAY_REF should not be an lvalue.  */
8505 
8506 bool
convert_vector_to_array_for_subscript(location_t loc,tree * vecp,tree index)8507 convert_vector_to_array_for_subscript (location_t loc,
8508 				       tree *vecp, tree index)
8509 {
8510   bool ret = false;
8511   if (gnu_vector_type_p (TREE_TYPE (*vecp)))
8512     {
8513       tree type = TREE_TYPE (*vecp);
8514 
8515       ret = !lvalue_p (*vecp);
8516 
8517       index = fold_for_warn (index);
8518       if (TREE_CODE (index) == INTEGER_CST)
8519         if (!tree_fits_uhwi_p (index)
8520 	    || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
8521           warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
8522 
8523       /* We are building an ARRAY_REF so mark the vector as addressable
8524          to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
8525 	 for function parameters.  */
8526       c_common_mark_addressable_vec (*vecp);
8527 
8528       *vecp = build1 (VIEW_CONVERT_EXPR,
8529 		      build_array_type_nelts (TREE_TYPE (type),
8530 					      TYPE_VECTOR_SUBPARTS (type)),
8531 		      *vecp);
8532     }
8533   return ret;
8534 }
8535 
8536 /* Determine which of the operands, if any, is a scalar that needs to be
8537    converted to a vector, for the range of operations.  */
8538 enum stv_conv
scalar_to_vector(location_t loc,enum tree_code code,tree op0,tree op1,bool complain)8539 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
8540 		  bool complain)
8541 {
8542   tree type0 = TREE_TYPE (op0);
8543   tree type1 = TREE_TYPE (op1);
8544   bool integer_only_op = false;
8545   enum stv_conv ret = stv_firstarg;
8546 
8547   gcc_assert (gnu_vector_type_p (type0) || gnu_vector_type_p (type1));
8548   switch (code)
8549     {
8550       /* Most GENERIC binary expressions require homogeneous arguments.
8551 	 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
8552 	 argument that is a vector and a second one that is a scalar, so
8553 	 we never return stv_secondarg for them.  */
8554       case RSHIFT_EXPR:
8555       case LSHIFT_EXPR:
8556 	if (TREE_CODE (type0) == INTEGER_TYPE
8557 	    && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8558 	  {
8559 	    if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8560 				     NULL_TREE, false))
8561 	      {
8562 		if (complain)
8563 		  error_at (loc, "conversion of scalar %qT to vector %qT "
8564 			    "involves truncation", type0, type1);
8565 		return stv_error;
8566 	      }
8567 	    else
8568 	      return stv_firstarg;
8569 	  }
8570 	break;
8571 
8572       case BIT_IOR_EXPR:
8573       case BIT_XOR_EXPR:
8574       case BIT_AND_EXPR:
8575 	integer_only_op = true;
8576 	/* fall through */
8577 
8578       case VEC_COND_EXPR:
8579 
8580       case PLUS_EXPR:
8581       case MINUS_EXPR:
8582       case MULT_EXPR:
8583       case TRUNC_DIV_EXPR:
8584       case CEIL_DIV_EXPR:
8585       case FLOOR_DIV_EXPR:
8586       case ROUND_DIV_EXPR:
8587       case EXACT_DIV_EXPR:
8588       case TRUNC_MOD_EXPR:
8589       case FLOOR_MOD_EXPR:
8590       case RDIV_EXPR:
8591       case EQ_EXPR:
8592       case NE_EXPR:
8593       case LE_EXPR:
8594       case GE_EXPR:
8595       case LT_EXPR:
8596       case GT_EXPR:
8597       /* What about UNLT_EXPR?  */
8598 	if (gnu_vector_type_p (type0))
8599 	  {
8600 	    ret = stv_secondarg;
8601 	    std::swap (type0, type1);
8602 	    std::swap (op0, op1);
8603 	  }
8604 
8605 	if (TREE_CODE (type0) == INTEGER_TYPE
8606 	    && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8607 	  {
8608 	    if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8609 				     NULL_TREE, false))
8610 	      {
8611 		if (complain)
8612 		  error_at (loc, "conversion of scalar %qT to vector %qT "
8613 			    "involves truncation", type0, type1);
8614 		return stv_error;
8615 	      }
8616 	    return ret;
8617 	  }
8618 	else if (!integer_only_op
8619 		    /* Allow integer --> real conversion if safe.  */
8620 		 && (TREE_CODE (type0) == REAL_TYPE
8621 		     || TREE_CODE (type0) == INTEGER_TYPE)
8622 		 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
8623 	  {
8624 	    if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8625 				     NULL_TREE, false))
8626 	      {
8627 		if (complain)
8628 		  error_at (loc, "conversion of scalar %qT to vector %qT "
8629 			    "involves truncation", type0, type1);
8630 		return stv_error;
8631 	      }
8632 	    return ret;
8633 	  }
8634       default:
8635 	break;
8636     }
8637 
8638   return stv_nothing;
8639 }
8640 
8641 /* Return the alignment of std::max_align_t.
8642 
8643    [support.types.layout] The type max_align_t is a POD type whose alignment
8644    requirement is at least as great as that of every scalar type, and whose
8645    alignment requirement is supported in every context.  */
8646 
8647 unsigned
max_align_t_align()8648 max_align_t_align ()
8649 {
8650   unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
8651 				TYPE_ALIGN (long_double_type_node));
8652   if (float128_type_node != NULL_TREE)
8653     max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
8654   return max_align;
8655 }
8656 
8657 /* Return true iff ALIGN is an integral constant that is a fundamental
8658    alignment, as defined by [basic.align] in the c++-11
8659    specifications.
8660 
8661    That is:
8662 
8663        [A fundamental alignment is represented by an alignment less than or
8664         equal to the greatest alignment supported by the implementation
8665         in all contexts, which is equal to alignof(max_align_t)].  */
8666 
8667 bool
cxx_fundamental_alignment_p(unsigned align)8668 cxx_fundamental_alignment_p (unsigned align)
8669 {
8670   return (align <= max_align_t_align ());
8671 }
8672 
8673 /* Return true if T is a pointer to a zero-sized aggregate.  */
8674 
8675 bool
pointer_to_zero_sized_aggr_p(tree t)8676 pointer_to_zero_sized_aggr_p (tree t)
8677 {
8678   if (!POINTER_TYPE_P (t))
8679     return false;
8680   t = TREE_TYPE (t);
8681   return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
8682 }
8683 
8684 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
8685    with no library fallback or for an ADDR_EXPR whose operand is such type
8686    issues an error pointing to the location LOC.
8687    Returns true when the expression has been diagnosed and false
8688    otherwise.  */
8689 
8690 bool
reject_gcc_builtin(const_tree expr,location_t loc)8691 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
8692 {
8693   if (TREE_CODE (expr) == ADDR_EXPR)
8694     expr = TREE_OPERAND (expr, 0);
8695 
8696   STRIP_ANY_LOCATION_WRAPPER (expr);
8697 
8698   if (TREE_TYPE (expr)
8699       && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
8700       && TREE_CODE (expr) == FUNCTION_DECL
8701       /* The intersection of DECL_BUILT_IN and DECL_IS_UNDECLARED_BUILTIN avoids
8702 	 false positives for user-declared built-ins such as abs or
8703 	 strlen, and for C++ operators new and delete.
8704 	 The c_decl_implicit() test avoids false positives for implicitly
8705 	 declared built-ins with library fallbacks (such as abs).  */
8706       && fndecl_built_in_p (expr)
8707       && DECL_IS_UNDECLARED_BUILTIN (expr)
8708       && !c_decl_implicit (expr)
8709       && !DECL_ASSEMBLER_NAME_SET_P (expr))
8710     {
8711       if (loc == UNKNOWN_LOCATION)
8712 	loc = EXPR_LOC_OR_LOC (expr, input_location);
8713 
8714       /* Reject arguments that are built-in functions with
8715 	 no library fallback.  */
8716       error_at (loc, "built-in function %qE must be directly called", expr);
8717 
8718       return true;
8719     }
8720 
8721   return false;
8722 }
8723 
8724 /* Issue an ERROR for an invalid SIZE of array NAME which is null
8725    for unnamed arrays.  */
8726 
8727 void
invalid_array_size_error(location_t loc,cst_size_error error,const_tree size,const_tree name)8728 invalid_array_size_error (location_t loc, cst_size_error error,
8729 			  const_tree size, const_tree name)
8730 {
8731   tree maxsize = max_object_size ();
8732   switch (error)
8733     {
8734     case cst_size_not_constant:
8735       if (name)
8736 	error_at (loc, "size of array %qE is not a constant expression",
8737 		  name);
8738       else
8739 	error_at (loc, "size of array is not a constant expression");
8740       break;
8741     case cst_size_negative:
8742       if (name)
8743 	error_at (loc, "size %qE of array %qE is negative",
8744 		  size, name);
8745       else
8746 	error_at (loc, "size %qE of array is negative",
8747 		  size);
8748       break;
8749     case cst_size_too_big:
8750       if (name)
8751 	error_at (loc, "size %qE of array %qE exceeds maximum "
8752 		  "object size %qE", size, name, maxsize);
8753       else
8754 	error_at (loc, "size %qE of array exceeds maximum "
8755 		  "object size %qE", size, maxsize);
8756       break;
8757     case cst_size_overflow:
8758       if (name)
8759 	error_at (loc, "size of array %qE exceeds maximum "
8760 		  "object size %qE", name, maxsize);
8761       else
8762 	error_at (loc, "size of array exceeds maximum "
8763 		  "object size %qE", maxsize);
8764       break;
8765     default:
8766       gcc_unreachable ();
8767     }
8768 }
8769 
8770 /* Check if array size calculations overflow or if the array covers more
8771    than half of the address space.  Return true if the size of the array
8772    is valid, false otherwise.  T is either the type of the array or its
8773    size, and NAME is the name of the array, or null for unnamed arrays.  */
8774 
8775 bool
valid_array_size_p(location_t loc,const_tree t,tree name,bool complain)8776 valid_array_size_p (location_t loc, const_tree t, tree name, bool complain)
8777 {
8778   if (t == error_mark_node)
8779     return true;
8780 
8781   const_tree size;
8782   if (TYPE_P (t))
8783     {
8784       if (!COMPLETE_TYPE_P (t))
8785 	return true;
8786       size = TYPE_SIZE_UNIT (t);
8787     }
8788   else
8789     size = t;
8790 
8791   if (TREE_CODE (size) != INTEGER_CST)
8792     return true;
8793 
8794   cst_size_error error;
8795   if (valid_constant_size_p (size, &error))
8796     return true;
8797 
8798   if (!complain)
8799     return false;
8800 
8801   if (TREE_CODE (TREE_TYPE (size)) == ENUMERAL_TYPE)
8802     /* Show the value of the enumerator rather than its name.  */
8803     size = convert (ssizetype, const_cast<tree> (size));
8804 
8805   invalid_array_size_error (loc, error, size, name);
8806   return false;
8807 }
8808 
8809 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
8810    timestamp to replace embedded current dates to get reproducible
8811    results.  Returns -1 if SOURCE_DATE_EPOCH is not defined.  */
8812 
8813 time_t
cb_get_source_date_epoch(cpp_reader * pfile ATTRIBUTE_UNUSED)8814 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
8815 {
8816   char *source_date_epoch;
8817   int64_t epoch;
8818   char *endptr;
8819 
8820   source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
8821   if (!source_date_epoch)
8822     return (time_t) -1;
8823 
8824   errno = 0;
8825 #if defined(INT64_T_IS_LONG)
8826   epoch = strtol (source_date_epoch, &endptr, 10);
8827 #else
8828   epoch = strtoll (source_date_epoch, &endptr, 10);
8829 #endif
8830   if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
8831       || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
8832     {
8833       error_at (input_location, "environment variable %qs must "
8834 	        "expand to a non-negative integer less than or equal to %wd",
8835 		"SOURCE_DATE_EPOCH", MAX_SOURCE_DATE_EPOCH);
8836       return (time_t) -1;
8837     }
8838 
8839   return (time_t) epoch;
8840 }
8841 
8842 /* Callback for libcpp for offering spelling suggestions for misspelled
8843    directives.  GOAL is an unrecognized string; CANDIDATES is a
8844    NULL-terminated array of candidate strings.  Return the closest
8845    match to GOAL within CANDIDATES, or NULL if none are good
8846    suggestions.  */
8847 
8848 const char *
cb_get_suggestion(cpp_reader *,const char * goal,const char * const * candidates)8849 cb_get_suggestion (cpp_reader *, const char *goal,
8850 		   const char *const *candidates)
8851 {
8852   best_match<const char *, const char *> bm (goal);
8853   while (*candidates)
8854     bm.consider (*candidates++);
8855   return bm.get_best_meaningful_candidate ();
8856 }
8857 
8858 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
8859    modes X, Y.  This isn't just  >, as the FLT_EVAL_METHOD values added
8860    by C TS 18661-3 for interchange  types that are computed in their
8861    native precision are larger than the C11 values for evaluating in the
8862    precision of float/double/long double.  If either mode is
8863    FLT_EVAL_METHOD_UNPREDICTABLE, return that.  */
8864 
8865 enum flt_eval_method
excess_precision_mode_join(enum flt_eval_method x,enum flt_eval_method y)8866 excess_precision_mode_join (enum flt_eval_method x,
8867 			    enum flt_eval_method y)
8868 {
8869   if (x == FLT_EVAL_METHOD_UNPREDICTABLE
8870       || y == FLT_EVAL_METHOD_UNPREDICTABLE)
8871     return FLT_EVAL_METHOD_UNPREDICTABLE;
8872 
8873   /* GCC only supports one interchange type right now, _Float16.  If
8874      we're evaluating _Float16 in 16-bit precision, then flt_eval_method
8875      will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16.  */
8876   if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
8877     return y;
8878   if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
8879     return x;
8880 
8881   /* Other values for flt_eval_method are directly comparable, and we want
8882      the maximum.  */
8883   return MAX (x, y);
8884 }
8885 
8886 /* Return the value that should be set for FLT_EVAL_METHOD in the
8887    context of ISO/IEC TS 18861-3.
8888 
8889    This relates to the effective excess precision seen by the user,
8890    which is the join point of the precision the target requests for
8891    -fexcess-precision={standard,fast,16} and the implicit excess precision
8892    the target uses.  */
8893 
8894 static enum flt_eval_method
c_ts18661_flt_eval_method(void)8895 c_ts18661_flt_eval_method (void)
8896 {
8897   enum flt_eval_method implicit
8898     = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
8899 
8900   enum excess_precision_type flag_type
8901     = (flag_excess_precision == EXCESS_PRECISION_STANDARD
8902        ? EXCESS_PRECISION_TYPE_STANDARD
8903        : (flag_excess_precision == EXCESS_PRECISION_FLOAT16
8904 	  ? EXCESS_PRECISION_TYPE_FLOAT16
8905 	  : EXCESS_PRECISION_TYPE_FAST));
8906 
8907   enum flt_eval_method requested
8908     = targetm.c.excess_precision (flag_type);
8909 
8910   return excess_precision_mode_join (implicit, requested);
8911 }
8912 
8913 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
8914    those that were permitted by C11.  That is to say, eliminates
8915    FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16.  */
8916 
8917 static enum flt_eval_method
c_c11_flt_eval_method(void)8918 c_c11_flt_eval_method (void)
8919 {
8920   return excess_precision_mode_join (c_ts18661_flt_eval_method (),
8921 				     FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
8922 }
8923 
8924 /* Return the value that should be set for FLT_EVAL_METHOD.
8925    MAYBE_C11_ONLY_P is TRUE if we should check
8926    FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
8927    values we can return to those from C99/C11, and FALSE otherwise.
8928    See the comments on c_ts18661_flt_eval_method for what value we choose
8929    to set here.  */
8930 
8931 int
c_flt_eval_method(bool maybe_c11_only_p)8932 c_flt_eval_method (bool maybe_c11_only_p)
8933 {
8934   if (maybe_c11_only_p
8935       && flag_permitted_flt_eval_methods
8936 	  == PERMITTED_FLT_EVAL_METHODS_C11)
8937     return c_c11_flt_eval_method ();
8938   else
8939     return c_ts18661_flt_eval_method ();
8940 }
8941 
8942 /* An enum for get_missing_token_insertion_kind for describing the best
8943    place to insert a missing token, if there is one.  */
8944 
8945 enum missing_token_insertion_kind
8946 {
8947   MTIK_IMPOSSIBLE,
8948   MTIK_INSERT_BEFORE_NEXT,
8949   MTIK_INSERT_AFTER_PREV
8950 };
8951 
8952 /* Given a missing token of TYPE, determine if it is reasonable to
8953    emit a fix-it hint suggesting the insertion of the token, and,
8954    if so, where the token should be inserted relative to other tokens.
8955 
8956    It only makes sense to do this for values of TYPE that are symbols.
8957 
8958    Some symbols should go before the next token, e.g. in:
8959      if flag)
8960    we want to insert the missing '(' immediately before "flag",
8961    giving:
8962      if (flag)
8963    rather than:
8964      if( flag)
8965    These use MTIK_INSERT_BEFORE_NEXT.
8966 
8967    Other symbols should go after the previous token, e.g. in:
8968      if (flag
8969        do_something ();
8970    we want to insert the missing ')' immediately after the "flag",
8971    giving:
8972      if (flag)
8973        do_something ();
8974    rather than:
8975      if (flag
8976        )do_something ();
8977    These use MTIK_INSERT_AFTER_PREV.  */
8978 
8979 static enum missing_token_insertion_kind
get_missing_token_insertion_kind(enum cpp_ttype type)8980 get_missing_token_insertion_kind (enum cpp_ttype type)
8981 {
8982   switch (type)
8983     {
8984       /* Insert missing "opening" brackets immediately
8985 	 before the next token.  */
8986     case CPP_OPEN_SQUARE:
8987     case CPP_OPEN_PAREN:
8988       return MTIK_INSERT_BEFORE_NEXT;
8989 
8990       /* Insert other missing symbols immediately after
8991 	 the previous token.  */
8992     case CPP_CLOSE_PAREN:
8993     case CPP_CLOSE_SQUARE:
8994     case CPP_SEMICOLON:
8995     case CPP_COMMA:
8996     case CPP_COLON:
8997       return MTIK_INSERT_AFTER_PREV;
8998 
8999       /* Other kinds of token don't get fix-it hints.  */
9000     default:
9001       return MTIK_IMPOSSIBLE;
9002     }
9003 }
9004 
9005 /* Given RICHLOC, a location for a diagnostic describing a missing token
9006    of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
9007    insertion of the token.
9008 
9009    The location of the attempted fix-it hint depends on TOKEN_TYPE:
9010    it will either be:
9011      (a) immediately after PREV_TOKEN_LOC, or
9012 
9013      (b) immediately before the primary location within RICHLOC (taken to
9014 	 be that of the token following where the token was expected).
9015 
9016    If we manage to add a fix-it hint, then the location of the
9017    fix-it hint is likely to be more useful as the primary location
9018    of the diagnostic than that of the following token, so we swap
9019    these locations.
9020 
9021    For example, given this bogus code:
9022        123456789012345678901234567890
9023    1 | int missing_semicolon (void)
9024    2 | {
9025    3 |   return 42
9026    4 | }
9027 
9028    we will emit:
9029 
9030      "expected ';' before '}'"
9031 
9032    RICHLOC's primary location is at the closing brace, so before "swapping"
9033    we would emit the error at line 4 column 1:
9034 
9035        123456789012345678901234567890
9036    3 |   return 42  |< fix-it hint emitted for this line
9037      |            ; |
9038    4 | }            |< "expected ';' before '}'" emitted at this line
9039      | ^            |
9040 
9041    It's more useful for the location of the diagnostic to be at the
9042    fix-it hint, so we swap the locations, so the primary location
9043    is at the fix-it hint, with the old primary location inserted
9044    as a secondary location, giving this, with the error at line 3
9045    column 12:
9046 
9047        123456789012345678901234567890
9048    3 |   return 42   |< "expected ';' before '}'" emitted at this line,
9049      |            ^  |   with fix-it hint
9050    4 |            ;  |
9051      | }             |< secondary range emitted here
9052      | ~             |.  */
9053 
9054 void
maybe_suggest_missing_token_insertion(rich_location * richloc,enum cpp_ttype token_type,location_t prev_token_loc)9055 maybe_suggest_missing_token_insertion (rich_location *richloc,
9056 				       enum cpp_ttype token_type,
9057 				       location_t prev_token_loc)
9058 {
9059   gcc_assert (richloc);
9060 
9061   enum missing_token_insertion_kind mtik
9062     = get_missing_token_insertion_kind (token_type);
9063 
9064   switch (mtik)
9065     {
9066     default:
9067       gcc_unreachable ();
9068       break;
9069 
9070     case MTIK_IMPOSSIBLE:
9071       return;
9072 
9073     case MTIK_INSERT_BEFORE_NEXT:
9074       /* Attempt to add the fix-it hint before the primary location
9075 	 of RICHLOC.  */
9076       richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
9077       break;
9078 
9079     case MTIK_INSERT_AFTER_PREV:
9080       /* Attempt to add the fix-it hint after PREV_TOKEN_LOC.  */
9081       richloc->add_fixit_insert_after (prev_token_loc,
9082 				       cpp_type2name (token_type, 0));
9083       break;
9084     }
9085 
9086   /* If we were successful, use the fix-it hint's location as the
9087      primary location within RICHLOC, adding the old primary location
9088      back as a secondary location.  */
9089   if (!richloc->seen_impossible_fixit_p ())
9090     {
9091       fixit_hint *hint = richloc->get_last_fixit_hint ();
9092       location_t hint_loc = hint->get_start_loc ();
9093       location_t old_loc = richloc->get_loc ();
9094 
9095       richloc->set_range (0, hint_loc, SHOW_RANGE_WITH_CARET);
9096       richloc->add_range (old_loc);
9097     }
9098 }
9099 
9100 #if CHECKING_P
9101 
9102 namespace selftest {
9103 
9104 /* Verify that fold_for_warn on error_mark_node is safe.  */
9105 
9106 static void
test_fold_for_warn()9107 test_fold_for_warn ()
9108 {
9109   ASSERT_EQ (error_mark_node, fold_for_warn (error_mark_node));
9110 }
9111 
9112 /* Run all of the selftests within this file.  */
9113 
9114 static void
c_common_cc_tests()9115 c_common_cc_tests ()
9116 {
9117   test_fold_for_warn ();
9118 }
9119 
9120 /* Run all of the tests within c-family.  */
9121 
9122 void
c_family_tests(void)9123 c_family_tests (void)
9124 {
9125   c_common_cc_tests ();
9126   c_format_cc_tests ();
9127   c_indentation_cc_tests ();
9128   c_pretty_print_cc_tests ();
9129   c_spellcheck_cc_tests ();
9130   c_diagnostic_cc_tests ();
9131   c_opt_problem_cc_tests ();
9132 }
9133 
9134 } // namespace selftest
9135 
9136 #endif /* #if CHECKING_P */
9137 
9138 /* Attempt to locate a suitable location within FILE for a
9139    #include directive to be inserted before.
9140    LOC is the location of the relevant diagnostic.
9141 
9142    Attempt to return the location within FILE immediately
9143    after the last #include within that file, or the start of
9144    that file if it has no #include directives.
9145 
9146    Return UNKNOWN_LOCATION if no suitable location is found,
9147    or if an error occurs.  */
9148 
9149 static location_t
try_to_locate_new_include_insertion_point(const char * file,location_t loc)9150 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
9151 {
9152   /* Locate the last ordinary map within FILE that ended with a #include.  */
9153   const line_map_ordinary *last_include_ord_map = NULL;
9154 
9155   /* ...and the next ordinary map within FILE after that one.  */
9156   const line_map_ordinary *last_ord_map_after_include = NULL;
9157 
9158   /* ...and the first ordinary map within FILE.  */
9159   const line_map_ordinary *first_ord_map_in_file = NULL;
9160 
9161   /*  Get ordinary map containing LOC (or its expansion).  */
9162   const line_map_ordinary *ord_map_for_loc = NULL;
9163   linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
9164 			    &ord_map_for_loc);
9165   gcc_assert (ord_map_for_loc);
9166 
9167   for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
9168     {
9169       const line_map_ordinary *ord_map
9170 	= LINEMAPS_ORDINARY_MAP_AT (line_table, i);
9171 
9172       if (const line_map_ordinary *from
9173 	  = linemap_included_from_linemap (line_table, ord_map))
9174 	/* We cannot use pointer equality, because with preprocessed
9175 	   input all filename strings are unique.  */
9176 	if (0 == strcmp (from->to_file, file))
9177 	  {
9178 	    last_include_ord_map = from;
9179 	    last_ord_map_after_include = NULL;
9180 	  }
9181 
9182       /* Likewise, use strcmp, and reject any line-zero introductory
9183 	 map.  */
9184       if (ord_map->to_line && 0 == strcmp (ord_map->to_file, file))
9185 	{
9186 	  if (!first_ord_map_in_file)
9187 	    first_ord_map_in_file = ord_map;
9188 	  if (last_include_ord_map && !last_ord_map_after_include)
9189 	    last_ord_map_after_include = ord_map;
9190 	}
9191 
9192       /* Stop searching when reaching the ord_map containing LOC,
9193 	 as it makes no sense to provide fix-it hints that appear
9194 	 after the diagnostic in question.  */
9195       if (ord_map == ord_map_for_loc)
9196 	break;
9197     }
9198 
9199   /* Determine where to insert the #include.  */
9200   const line_map_ordinary *ord_map_for_insertion;
9201 
9202   /* We want the next ordmap in the file after the last one that's a
9203      #include, but failing that, the start of the file.  */
9204   if (last_ord_map_after_include)
9205     ord_map_for_insertion = last_ord_map_after_include;
9206   else
9207     ord_map_for_insertion = first_ord_map_in_file;
9208 
9209   if (!ord_map_for_insertion)
9210     return UNKNOWN_LOCATION;
9211 
9212   /* The "start_location" is column 0, meaning "the whole line".
9213      rich_location and edit_context can't cope with this, so use
9214      column 1 instead.  */
9215   location_t col_0 = ord_map_for_insertion->start_location;
9216   return linemap_position_for_loc_and_offset (line_table, col_0, 1);
9217 }
9218 
9219 /* A map from filenames to sets of headers added to them, for
9220    ensuring idempotency within maybe_add_include_fixit.  */
9221 
9222 /* The values within the map.  We need string comparison as there's
9223    no guarantee that two different diagnostics that are recommending
9224    adding e.g. "<stdio.h>" are using the same buffer.  */
9225 
9226 typedef hash_set <const char *, false, nofree_string_hash> per_file_includes_t;
9227 
9228 /* The map itself.  We don't need string comparison for the filename keys,
9229    as they come from libcpp.  */
9230 
9231 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
9232 static added_includes_t *added_includes;
9233 
9234 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
9235    in a suitable location within the file of RICHLOC's primary
9236    location.
9237 
9238    This function is idempotent: a header will be added at most once to
9239    any given file.
9240 
9241    If OVERRIDE_LOCATION is true, then if a fix-it is added and will be
9242    printed, then RICHLOC's primary location will be replaced by that of
9243    the fix-it hint (for use by "inform" notes where the location of the
9244    issue has already been reported).  */
9245 
9246 void
maybe_add_include_fixit(rich_location * richloc,const char * header,bool override_location)9247 maybe_add_include_fixit (rich_location *richloc, const char *header,
9248 			 bool override_location)
9249 {
9250   location_t loc = richloc->get_loc ();
9251   const char *file = LOCATION_FILE (loc);
9252   if (!file)
9253     return;
9254 
9255   /* Idempotency: don't add the same header more than once to a given file.  */
9256   if (!added_includes)
9257     added_includes = new added_includes_t ();
9258   per_file_includes_t *&set = added_includes->get_or_insert (file);
9259   if (set)
9260     if (set->contains (header))
9261       /* ...then we've already added HEADER to that file.  */
9262       return;
9263   if (!set)
9264     set = new per_file_includes_t ();
9265   set->add (header);
9266 
9267   /* Attempt to locate a suitable place for the new directive.  */
9268   location_t include_insert_loc
9269     = try_to_locate_new_include_insertion_point (file, loc);
9270   if (include_insert_loc == UNKNOWN_LOCATION)
9271     return;
9272 
9273   char *text = xasprintf ("#include %s\n", header);
9274   richloc->add_fixit_insert_before (include_insert_loc, text);
9275   free (text);
9276 
9277   if (override_location && global_dc->show_caret)
9278     {
9279       /* Replace the primary location with that of the insertion point for the
9280 	 fix-it hint.
9281 
9282 	 We use SHOW_LINES_WITHOUT_RANGE so that we don't meaningless print a
9283 	 caret for the insertion point (or colorize it).
9284 
9285 	 Hence we print e.g.:
9286 
9287 	 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9288 	  73 | # include <debug/vector>
9289 	 +++ |+#include <vector>
9290 	  74 | #endif
9291 
9292 	 rather than:
9293 
9294 	 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9295 	  73 | # include <debug/vector>
9296 	 +++ |+#include <vector>
9297 	  74 | #endif
9298 	     | ^
9299 
9300 	 avoiding the caret on the first column of line 74.  */
9301       richloc->set_range (0, include_insert_loc, SHOW_LINES_WITHOUT_RANGE);
9302     }
9303 }
9304 
9305 /* Attempt to convert a braced array initializer list CTOR for array
9306    TYPE into a STRING_CST for convenience and efficiency.  Return
9307    the converted string on success or the original ctor on failure.  */
9308 
9309 static tree
braced_list_to_string(tree type,tree ctor,bool member)9310 braced_list_to_string (tree type, tree ctor, bool member)
9311 {
9312   /* Ignore non-members with unknown size like arrays with unspecified
9313      bound.  */
9314   tree typesize = TYPE_SIZE_UNIT (type);
9315   if (!member && !tree_fits_uhwi_p (typesize))
9316     return ctor;
9317 
9318   /* If the target char size differes from the host char size, we'd risk
9319      loosing data and getting object sizes wrong by converting to
9320      host chars.  */
9321   if (TYPE_PRECISION (char_type_node) != CHAR_BIT)
9322     return ctor;
9323 
9324   /* If the array has an explicit bound, use it to constrain the size
9325      of the string.  If it doesn't, be sure to create a string that's
9326      as long as implied by the index of the last zero specified via
9327      a designator, as in:
9328        const char a[] = { [7] = 0 };  */
9329   unsigned HOST_WIDE_INT maxelts;
9330   if (typesize)
9331     {
9332       maxelts = tree_to_uhwi (typesize);
9333       maxelts /= tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type)));
9334     }
9335   else
9336     maxelts = HOST_WIDE_INT_M1U;
9337 
9338   /* Avoid converting initializers for zero-length arrays (but do
9339      create them for flexible array members).  */
9340   if (!maxelts)
9341     return ctor;
9342 
9343   unsigned HOST_WIDE_INT nelts = CONSTRUCTOR_NELTS (ctor);
9344 
9345   auto_vec<char> str;
9346   str.reserve (nelts + 1);
9347 
9348   unsigned HOST_WIDE_INT i;
9349   tree index, value;
9350 
9351   FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, index, value)
9352     {
9353       unsigned HOST_WIDE_INT idx = i;
9354       if (index)
9355 	{
9356 	  if (!tree_fits_uhwi_p (index))
9357 	    return ctor;
9358 	  idx = tree_to_uhwi (index);
9359 	}
9360 
9361       /* auto_vec is limited to UINT_MAX elements.  */
9362       if (idx > UINT_MAX)
9363 	return ctor;
9364 
9365      /* Avoid non-constant initializers.  */
9366      if (!tree_fits_shwi_p (value))
9367 	return ctor;
9368 
9369       /* Skip over embedded nuls except the last one (initializer
9370 	 elements are in ascending order of indices).  */
9371       HOST_WIDE_INT val = tree_to_shwi (value);
9372       if (!val && i + 1 < nelts)
9373 	continue;
9374 
9375       if (idx < str.length())
9376 	return ctor;
9377 
9378       /* Bail if the CTOR has a block of more than 256 embedded nuls
9379 	 due to implicitly initialized elements.  */
9380       unsigned nchars = (idx - str.length ()) + 1;
9381       if (nchars > 256)
9382 	return ctor;
9383 
9384       if (nchars > 1)
9385 	{
9386 	  str.reserve (idx);
9387 	  str.quick_grow_cleared (idx);
9388 	}
9389 
9390       if (idx >= maxelts)
9391 	return ctor;
9392 
9393       str.safe_insert (idx, val);
9394     }
9395 
9396   /* Append a nul string termination.  */
9397   if (maxelts != HOST_WIDE_INT_M1U && str.length () < maxelts)
9398     str.safe_push (0);
9399 
9400   /* Build a STRING_CST with the same type as the array.  */
9401   tree res = build_string (str.length (), str.begin ());
9402   TREE_TYPE (res) = type;
9403   return res;
9404 }
9405 
9406 /* Implementation of the two-argument braced_lists_to_string withe
9407    the same arguments plus MEMBER which is set for struct members
9408    to allow initializers for flexible member arrays.  */
9409 
9410 static tree
braced_lists_to_strings(tree type,tree ctor,bool member)9411 braced_lists_to_strings (tree type, tree ctor, bool member)
9412 {
9413   if (TREE_CODE (ctor) != CONSTRUCTOR)
9414     return ctor;
9415 
9416   tree_code code = TREE_CODE (type);
9417 
9418   tree ttp;
9419   if (code == ARRAY_TYPE)
9420     ttp = TREE_TYPE (type);
9421   else if (code == RECORD_TYPE)
9422     {
9423       ttp = TREE_TYPE (ctor);
9424       if (TREE_CODE (ttp) == ARRAY_TYPE)
9425 	{
9426 	  type = ttp;
9427 	  ttp = TREE_TYPE (ttp);
9428 	}
9429     }
9430   else
9431     return ctor;
9432 
9433   if ((TREE_CODE (ttp) == ARRAY_TYPE || TREE_CODE (ttp) == INTEGER_TYPE)
9434       && TYPE_STRING_FLAG (ttp))
9435     return braced_list_to_string (type, ctor, member);
9436 
9437   code = TREE_CODE (ttp);
9438   if (code == ARRAY_TYPE || RECORD_OR_UNION_TYPE_P (ttp))
9439     {
9440       bool rec = RECORD_OR_UNION_TYPE_P (ttp);
9441 
9442       /* Handle array of arrays or struct member initializers.  */
9443       tree val;
9444       unsigned HOST_WIDE_INT idx;
9445       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, val)
9446 	{
9447 	  val = braced_lists_to_strings (ttp, val, rec);
9448 	  CONSTRUCTOR_ELT (ctor, idx)->value = val;
9449 	}
9450     }
9451 
9452   return ctor;
9453 }
9454 
9455 /* Attempt to convert a CTOR containing braced array initializer lists
9456    for array TYPE into one containing STRING_CSTs, for convenience and
9457    efficiency.  Recurse for arrays of arrays and member initializers.
9458    Return the converted CTOR or STRING_CST on success or the original
9459    CTOR otherwise.  */
9460 
9461 tree
braced_lists_to_strings(tree type,tree ctor)9462 braced_lists_to_strings (tree type, tree ctor)
9463 {
9464   return braced_lists_to_strings (type, ctor, false);
9465 }
9466 
9467 
9468 /* Emit debug for functions before finalizing early debug.  */
9469 
9470 void
c_common_finalize_early_debug(void)9471 c_common_finalize_early_debug (void)
9472 {
9473   /* Emit early debug for reachable functions, and by consequence,
9474      locally scoped symbols.  Also emit debug for extern declared
9475      functions that are still reachable at this point.  */
9476   struct cgraph_node *cnode;
9477   FOR_EACH_FUNCTION (cnode)
9478     if (!cnode->alias && !cnode->thunk
9479 	&& (cnode->has_gimple_body_p ()
9480 	    || !DECL_IS_UNDECLARED_BUILTIN (cnode->decl)))
9481       (*debug_hooks->early_global_decl) (cnode->decl);
9482 }
9483 
9484 #include "gt-c-family-c-common.h"
9485