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