Fix ICE with SLP and -fdbg-cnt
[official-gcc.git] / gcc / c-family / c-common.cc
blob0ea0c4f4bef5cc91531abd04d897453fa85a6a39
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 C23 dialect of C. */
229 int flag_isoc23;
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_C23 | D_CXXONLY | D_OBJC | D_CXX_OBJC
328 C --std=c99: D_C23 | D_CXXONLY | D_OBJC
329 C --std=c17: D_C23 | D_CXXONLY | D_OBJC
330 C --std=c23: 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 { "_BitInt", RID_BITINT, D_CONLY },
353 { "_Bool", RID_BOOL, D_CONLY },
354 { "_Complex", RID_COMPLEX, 0 },
355 { "_Imaginary", RID_IMAGINARY, D_CONLY },
356 { "_Float16", RID_FLOAT16, 0 },
357 { "_Float32", RID_FLOAT32, 0 },
358 { "_Float64", RID_FLOAT64, 0 },
359 { "_Float128", RID_FLOAT128, 0 },
360 { "_Float32x", RID_FLOAT32X, 0 },
361 { "_Float64x", RID_FLOAT64X, 0 },
362 { "_Float128x", RID_FLOAT128X, 0 },
363 { "_Decimal32", RID_DFLOAT32, D_CONLY },
364 { "_Decimal64", RID_DFLOAT64, D_CONLY },
365 { "_Decimal128", RID_DFLOAT128, D_CONLY },
366 { "_Fract", RID_FRACT, D_CONLY | D_EXT },
367 { "_Accum", RID_ACCUM, D_CONLY | D_EXT },
368 { "_Sat", RID_SAT, D_CONLY | D_EXT },
369 { "_Static_assert", RID_STATIC_ASSERT, D_CONLY },
370 { "_Noreturn", RID_NORETURN, D_CONLY },
371 { "_Generic", RID_GENERIC, D_CONLY },
372 { "_Thread_local", RID_THREAD, D_CONLY },
373 { "__FUNCTION__", RID_FUNCTION_NAME, 0 },
374 { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
375 { "__alignof", RID_ALIGNOF, 0 },
376 { "__alignof__", RID_ALIGNOF, 0 },
377 { "__asm", RID_ASM, 0 },
378 { "__asm__", RID_ASM, 0 },
379 { "__attribute", RID_ATTRIBUTE, 0 },
380 { "__attribute__", RID_ATTRIBUTE, 0 },
381 { "__auto_type", RID_AUTO_TYPE, D_CONLY },
382 { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
383 { "__builtin_bit_cast", RID_BUILTIN_BIT_CAST, D_CXXONLY },
384 { "__builtin_call_with_static_chain",
385 RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
386 { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
387 { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
388 { "__builtin_convertvector", RID_BUILTIN_CONVERTVECTOR, 0 },
389 { "__builtin_has_attribute", RID_BUILTIN_HAS_ATTRIBUTE, 0 },
390 { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
391 { "__builtin_assoc_barrier", RID_BUILTIN_ASSOC_BARRIER, 0 },
392 { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
393 { "__builtin_shufflevector", RID_BUILTIN_SHUFFLEVECTOR, 0 },
394 { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
395 { "__builtin_offsetof", RID_OFFSETOF, 0 },
396 { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
397 { "__builtin_va_arg", RID_VA_ARG, 0 },
398 { "__complex", RID_COMPLEX, 0 },
399 { "__complex__", RID_COMPLEX, 0 },
400 { "__const", RID_CONST, 0 },
401 { "__const__", RID_CONST, 0 },
402 { "__constinit", RID_CONSTINIT, D_CXXONLY },
403 { "__decltype", RID_DECLTYPE, D_CXXONLY },
404 { "__extension__", RID_EXTENSION, 0 },
405 { "__func__", RID_C99_FUNCTION_NAME, 0 },
406 { "__imag", RID_IMAGPART, 0 },
407 { "__imag__", RID_IMAGPART, 0 },
408 { "__inline", RID_INLINE, 0 },
409 { "__inline__", RID_INLINE, 0 },
410 { "__label__", RID_LABEL, 0 },
411 { "__null", RID_NULL, 0 },
412 { "__real", RID_REALPART, 0 },
413 { "__real__", RID_REALPART, 0 },
414 { "__restrict", RID_RESTRICT, 0 },
415 { "__restrict__", RID_RESTRICT, 0 },
416 { "__signed", RID_SIGNED, 0 },
417 { "__signed__", RID_SIGNED, 0 },
418 { "__thread", RID_THREAD, 0 },
419 { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
420 { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
421 { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
422 { "__typeof", RID_TYPEOF, 0 },
423 { "__typeof__", RID_TYPEOF, 0 },
424 { "__typeof_unqual", RID_TYPEOF_UNQUAL, D_CONLY },
425 { "__typeof_unqual__", RID_TYPEOF_UNQUAL, D_CONLY },
426 { "__volatile", RID_VOLATILE, 0 },
427 { "__volatile__", RID_VOLATILE, 0 },
428 { "__GIMPLE", RID_GIMPLE, D_CONLY },
429 { "__PHI", RID_PHI, D_CONLY },
430 { "__RTL", RID_RTL, D_CONLY },
431 { "alignas", RID_ALIGNAS, D_C23 | D_CXX11 | D_CXXWARN },
432 { "alignof", RID_ALIGNOF, D_C23 | D_CXX11 | D_CXXWARN },
433 { "asm", RID_ASM, D_ASM },
434 { "auto", RID_AUTO, 0 },
435 { "bool", RID_BOOL, D_C23 | D_CXXWARN },
436 { "break", RID_BREAK, 0 },
437 { "case", RID_CASE, 0 },
438 { "catch", RID_CATCH, D_CXX_OBJC | D_CXXWARN },
439 { "char", RID_CHAR, 0 },
440 { "char8_t", RID_CHAR8, D_CXX_CHAR8_T_FLAGS | D_CXXWARN },
441 { "char16_t", RID_CHAR16, D_CXXONLY | D_CXX11 | D_CXXWARN },
442 { "char32_t", RID_CHAR32, D_CXXONLY | D_CXX11 | D_CXXWARN },
443 { "class", RID_CLASS, D_CXX_OBJC | D_CXXWARN },
444 { "const", RID_CONST, 0 },
445 { "consteval", RID_CONSTEVAL, D_CXXONLY | D_CXX20 | D_CXXWARN },
446 { "constexpr", RID_CONSTEXPR, D_C23 | D_CXX11 | D_CXXWARN },
447 { "constinit", RID_CONSTINIT, D_CXXONLY | D_CXX20 | D_CXXWARN },
448 { "const_cast", RID_CONSTCAST, D_CXXONLY | D_CXXWARN },
449 { "continue", RID_CONTINUE, 0 },
450 { "decltype", RID_DECLTYPE, D_CXXONLY | D_CXX11 | D_CXXWARN },
451 { "default", RID_DEFAULT, 0 },
452 { "delete", RID_DELETE, D_CXXONLY | D_CXXWARN },
453 { "do", RID_DO, 0 },
454 { "double", RID_DOUBLE, 0 },
455 { "dynamic_cast", RID_DYNCAST, D_CXXONLY | D_CXXWARN },
456 { "else", RID_ELSE, 0 },
457 { "enum", RID_ENUM, 0 },
458 { "explicit", RID_EXPLICIT, D_CXXONLY | D_CXXWARN },
459 { "export", RID_EXPORT, D_CXXONLY | D_CXXWARN },
460 { "extern", RID_EXTERN, 0 },
461 { "false", RID_FALSE, D_C23 | D_CXXWARN },
462 { "float", RID_FLOAT, 0 },
463 { "for", RID_FOR, 0 },
464 { "friend", RID_FRIEND, D_CXXONLY | D_CXXWARN },
465 { "goto", RID_GOTO, 0 },
466 { "if", RID_IF, 0 },
467 { "inline", RID_INLINE, D_EXT89 },
468 { "int", RID_INT, 0 },
469 { "long", RID_LONG, 0 },
470 { "mutable", RID_MUTABLE, D_CXXONLY | D_CXXWARN },
471 { "namespace", RID_NAMESPACE, D_CXXONLY | D_CXXWARN },
472 { "new", RID_NEW, D_CXXONLY | D_CXXWARN },
473 { "noexcept", RID_NOEXCEPT, D_CXXONLY | D_CXX11 | D_CXXWARN },
474 { "nullptr", RID_NULLPTR, D_C23 | D_CXX11 | D_CXXWARN },
475 { "operator", RID_OPERATOR, D_CXXONLY | D_CXXWARN },
476 { "private", RID_PRIVATE, D_CXX_OBJC | D_CXXWARN },
477 { "protected", RID_PROTECTED, D_CXX_OBJC | D_CXXWARN },
478 { "public", RID_PUBLIC, D_CXX_OBJC | D_CXXWARN },
479 { "register", RID_REGISTER, 0 },
480 { "reinterpret_cast", RID_REINTCAST, D_CXXONLY | D_CXXWARN },
481 { "restrict", RID_RESTRICT, D_CONLY | D_C99 },
482 { "return", RID_RETURN, 0 },
483 { "short", RID_SHORT, 0 },
484 { "signed", RID_SIGNED, 0 },
485 { "sizeof", RID_SIZEOF, 0 },
486 { "static", RID_STATIC, 0 },
487 { "static_assert", RID_STATIC_ASSERT, D_C23 | D_CXX11 | D_CXXWARN },
488 { "static_cast", RID_STATCAST, D_CXXONLY | D_CXXWARN },
489 { "struct", RID_STRUCT, 0 },
490 { "switch", RID_SWITCH, 0 },
491 { "template", RID_TEMPLATE, D_CXXONLY | D_CXXWARN },
492 { "this", RID_THIS, D_CXXONLY | D_CXXWARN },
493 { "thread_local", RID_THREAD, D_C23 | D_CXX11 | D_CXXWARN },
494 { "throw", RID_THROW, D_CXX_OBJC | D_CXXWARN },
495 { "true", RID_TRUE, D_C23 | D_CXXWARN },
496 { "try", RID_TRY, D_CXX_OBJC | D_CXXWARN },
497 { "typedef", RID_TYPEDEF, 0 },
498 { "typename", RID_TYPENAME, D_CXXONLY | D_CXXWARN },
499 { "typeid", RID_TYPEID, D_CXXONLY | D_CXXWARN },
500 { "typeof", RID_TYPEOF, D_EXT11 },
501 { "typeof_unqual", RID_TYPEOF_UNQUAL, D_CONLY | D_C23 },
502 { "union", RID_UNION, 0 },
503 { "unsigned", RID_UNSIGNED, 0 },
504 { "using", RID_USING, D_CXXONLY | D_CXXWARN },
505 { "virtual", RID_VIRTUAL, D_CXXONLY | D_CXXWARN },
506 { "void", RID_VOID, 0 },
507 { "volatile", RID_VOLATILE, 0 },
508 { "wchar_t", RID_WCHAR, D_CXXONLY },
509 { "while", RID_WHILE, 0 },
511 #define DEFTRAIT(TCC, CODE, NAME, ARITY) \
512 { NAME, RID_##CODE, D_CXXONLY },
513 #include "cp/cp-trait.def"
514 #undef DEFTRAIT
515 /* An alias for __is_same. */
516 { "__is_same_as", RID_IS_SAME, D_CXXONLY },
518 /* C++ transactional memory. */
519 { "synchronized", RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
520 { "atomic_noexcept", RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
521 { "atomic_cancel", RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
522 { "atomic_commit", RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
524 /* Concepts-related keywords */
525 { "concept", RID_CONCEPT, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
526 { "requires", RID_REQUIRES, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
528 /* Modules-related keywords, these are internal unspellable tokens,
529 created by the preprocessor. */
530 { "module ", RID__MODULE, D_CXX_MODULES_FLAGS | D_CXXWARN },
531 { "import ", RID__IMPORT, D_CXX_MODULES_FLAGS | D_CXXWARN },
532 { "export ", RID__EXPORT, D_CXX_MODULES_FLAGS | D_CXXWARN },
534 /* Coroutines-related keywords */
535 { "co_await", RID_CO_AWAIT, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
536 { "co_yield", RID_CO_YIELD, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
537 { "co_return", RID_CO_RETURN, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
539 /* These Objective-C keywords are recognized only immediately after
540 an '@'. */
541 { "compatibility_alias", RID_AT_ALIAS, D_OBJC },
542 { "defs", RID_AT_DEFS, D_OBJC },
543 { "encode", RID_AT_ENCODE, D_OBJC },
544 { "end", RID_AT_END, D_OBJC },
545 { "implementation", RID_AT_IMPLEMENTATION, D_OBJC },
546 { "interface", RID_AT_INTERFACE, D_OBJC },
547 { "protocol", RID_AT_PROTOCOL, D_OBJC },
548 { "selector", RID_AT_SELECTOR, D_OBJC },
549 { "finally", RID_AT_FINALLY, D_OBJC },
550 { "optional", RID_AT_OPTIONAL, D_OBJC },
551 { "required", RID_AT_REQUIRED, D_OBJC },
552 { "property", RID_AT_PROPERTY, D_OBJC },
553 { "package", RID_AT_PACKAGE, D_OBJC },
554 { "synthesize", RID_AT_SYNTHESIZE, D_OBJC },
555 { "dynamic", RID_AT_DYNAMIC, D_OBJC },
556 /* These are recognized only in protocol-qualifier context
557 (see above) */
558 { "bycopy", RID_BYCOPY, D_OBJC },
559 { "byref", RID_BYREF, D_OBJC },
560 { "in", RID_IN, D_OBJC },
561 { "inout", RID_INOUT, D_OBJC },
562 { "oneway", RID_ONEWAY, D_OBJC },
563 { "out", RID_OUT, D_OBJC },
564 /* These are recognized inside a property attribute list */
565 { "assign", RID_ASSIGN, D_OBJC },
566 { "atomic", RID_PROPATOMIC, D_OBJC },
567 { "copy", RID_COPY, D_OBJC },
568 { "getter", RID_GETTER, D_OBJC },
569 { "nonatomic", RID_NONATOMIC, D_OBJC },
570 { "readonly", RID_READONLY, D_OBJC },
571 { "readwrite", RID_READWRITE, D_OBJC },
572 { "retain", RID_RETAIN, D_OBJC },
573 { "setter", RID_SETTER, D_OBJC },
574 /* These are Objective C implementation of nullability, accepted only in
575 specific contexts. */
576 { "null_unspecified", RID_NULL_UNSPECIFIED, D_OBJC },
577 { "nullable", RID_NULLABLE, D_OBJC },
578 { "nonnull", RID_NONNULL, D_OBJC },
579 { "null_resettable", RID_NULL_RESETTABLE, D_OBJC },
582 const unsigned int num_c_common_reswords = ARRAY_SIZE (c_common_reswords);
584 /* Return identifier for address space AS. */
586 const char *
587 c_addr_space_name (addr_space_t as)
589 int rid = RID_FIRST_ADDR_SPACE + as;
590 gcc_assert (ridpointers [rid]);
591 return IDENTIFIER_POINTER (ridpointers [rid]);
594 /* Push current bindings for the function name VAR_DECLS. */
596 void
597 start_fname_decls (void)
599 unsigned ix;
600 tree saved = NULL_TREE;
602 for (ix = 0; fname_vars[ix].decl; ix++)
604 tree decl = *fname_vars[ix].decl;
606 if (decl)
608 saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
609 saved);
610 *fname_vars[ix].decl = NULL_TREE;
613 if (saved || saved_function_name_decls)
614 /* Normally they'll have been NULL, so only push if we've got a
615 stack, or they are non-NULL. */
616 saved_function_name_decls = tree_cons (saved, NULL_TREE,
617 saved_function_name_decls);
620 /* Finish up the current bindings, adding them into the current function's
621 statement tree. This must be done _before_ finish_stmt_tree is called.
622 If there is no current function, we must be at file scope and no statements
623 are involved. Pop the previous bindings. */
625 void
626 finish_fname_decls (void)
628 unsigned ix;
629 tree stmts = NULL_TREE;
630 tree stack = saved_function_name_decls;
632 for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
633 append_to_statement_list (TREE_VALUE (stack), &stmts);
635 if (stmts)
637 tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
639 if (TREE_CODE (*bodyp) == BIND_EXPR)
640 bodyp = &BIND_EXPR_BODY (*bodyp);
642 append_to_statement_list_force (*bodyp, &stmts);
643 *bodyp = stmts;
646 for (ix = 0; fname_vars[ix].decl; ix++)
647 *fname_vars[ix].decl = NULL_TREE;
649 if (stack)
651 /* We had saved values, restore them. */
652 tree saved;
654 for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
656 tree decl = TREE_PURPOSE (saved);
657 unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
659 *fname_vars[ix].decl = decl;
661 stack = TREE_CHAIN (stack);
663 saved_function_name_decls = stack;
666 /* Return the text name of the current function, suitably prettified
667 by PRETTY_P. Return string must be freed by caller. */
669 const char *
670 fname_as_string (int pretty_p)
672 const char *name = "top level";
673 char *namep;
674 int vrb = 2, len;
675 cpp_string cstr = { 0, 0 }, strname;
677 if (!pretty_p)
679 name = "";
680 vrb = 0;
683 if (current_function_decl)
684 name = lang_hooks.decl_printable_name (current_function_decl, vrb);
686 len = strlen (name) + 3; /* Two for '"'s. One for NULL. */
688 namep = XNEWVEC (char, len);
689 snprintf (namep, len, "\"%s\"", name);
690 strname.text = (unsigned char *) namep;
691 strname.len = len - 1;
693 if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
695 XDELETEVEC (namep);
696 return (const char *) cstr.text;
699 return namep;
702 /* Return the VAR_DECL for a const char array naming the current
703 function. If the VAR_DECL has not yet been created, create it
704 now. RID indicates how it should be formatted and IDENTIFIER_NODE
705 ID is its name (unfortunately C and C++ hold the RID values of
706 keywords in different places, so we can't derive RID from ID in
707 this language independent code. LOC is the location of the
708 function. */
710 tree
711 fname_decl (location_t loc, unsigned int rid, tree id)
713 unsigned ix;
714 tree decl = NULL_TREE;
716 for (ix = 0; fname_vars[ix].decl; ix++)
717 if (fname_vars[ix].rid == rid)
718 break;
720 decl = *fname_vars[ix].decl;
721 if (!decl)
723 /* If a tree is built here, it would normally have the lineno of
724 the current statement. Later this tree will be moved to the
725 beginning of the function and this line number will be wrong.
726 To avoid this problem set the lineno to 0 here; that prevents
727 it from appearing in the RTL. */
728 tree stmts;
729 location_t saved_location = input_location;
730 input_location = UNKNOWN_LOCATION;
732 stmts = push_stmt_list ();
733 decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
734 stmts = pop_stmt_list (stmts);
735 if (!IS_EMPTY_STMT (stmts))
736 saved_function_name_decls
737 = tree_cons (decl, stmts, saved_function_name_decls);
738 *fname_vars[ix].decl = decl;
739 input_location = saved_location;
741 if (!ix && !current_function_decl)
742 pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
744 return decl;
747 /* Given a STRING_CST, give it a suitable array-of-chars data type. */
749 tree
750 fix_string_type (tree value)
752 int length = TREE_STRING_LENGTH (value);
753 int nchars, charsz;
754 tree e_type, i_type, a_type;
756 /* Compute the number of elements, for the array type. */
757 if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
759 charsz = 1;
760 e_type = char_type_node;
762 else if (flag_char8_t && TREE_TYPE (value) == char8_array_type_node)
764 charsz = TYPE_PRECISION (char8_type_node) / BITS_PER_UNIT;
765 e_type = char8_type_node;
767 else if (TREE_TYPE (value) == char16_array_type_node)
769 charsz = TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT;
770 e_type = char16_type_node;
772 else if (TREE_TYPE (value) == char32_array_type_node)
774 charsz = TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT;
775 e_type = char32_type_node;
777 else
779 charsz = TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT;
780 e_type = wchar_type_node;
783 /* This matters only for targets where ssizetype has smaller precision
784 than 32 bits. */
785 if (wi::lts_p (wi::to_wide (TYPE_MAX_VALUE (ssizetype)), length))
787 error ("size of string literal is too large");
788 length = tree_to_shwi (TYPE_MAX_VALUE (ssizetype)) / charsz * charsz;
789 char *str = CONST_CAST (char *, TREE_STRING_POINTER (value));
790 memset (str + length, '\0',
791 MIN (TREE_STRING_LENGTH (value) - length, charsz));
792 TREE_STRING_LENGTH (value) = length;
794 nchars = length / charsz;
796 /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits). The analogous
797 limit in C++98 Annex B is very large (65536) and is not normative,
798 so we do not diagnose it (warn_overlength_strings is forced off
799 in c_common_post_options). */
800 if (warn_overlength_strings)
802 const int nchars_max = flag_isoc99 ? 4095 : 509;
803 const int relevant_std = flag_isoc99 ? 99 : 90;
804 if (nchars - 1 > nchars_max)
805 /* Translators: The %d after 'ISO C' will be 90 or 99. Do not
806 separate the %d from the 'C'. 'ISO' should not be
807 translated, but it may be moved after 'C%d' in languages
808 where modifiers follow nouns. */
809 pedwarn (input_location, OPT_Woverlength_strings,
810 "string length %qd is greater than the length %qd "
811 "ISO C%d compilers are required to support",
812 nchars - 1, nchars_max, relevant_std);
815 /* Create the array type for the string constant. The ISO C++
816 standard says that a string literal has type `const char[N]' or
817 `const wchar_t[N]'. We use the same logic when invoked as a C
818 front-end with -Wwrite-strings.
819 ??? We should change the type of an expression depending on the
820 state of a warning flag. We should just be warning -- see how
821 this is handled in the C++ front-end for the deprecated implicit
822 conversion from string literals to `char*' or `wchar_t*'.
824 The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
825 array type being the unqualified version of that type.
826 Therefore, if we are constructing an array of const char, we must
827 construct the matching unqualified array type first. The C front
828 end does not require this, but it does no harm, so we do it
829 unconditionally. */
830 i_type = build_index_type (size_int (nchars - 1));
831 a_type = build_array_type (e_type, i_type);
832 if (c_dialect_cxx() || warn_write_strings)
833 a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
835 TREE_TYPE (value) = a_type;
836 TREE_CONSTANT (value) = 1;
837 TREE_READONLY (value) = 1;
838 TREE_STATIC (value) = 1;
839 return value;
842 /* Given a string of type STRING_TYPE, determine what kind of string
843 token would give an equivalent execution encoding: CPP_STRING,
844 CPP_STRING16, or CPP_STRING32. Return CPP_OTHER in case of error.
845 This may not be exactly the string token type that initially created
846 the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
847 string type, and CPP_UTF8STRING is indistinguishable from CPP_STRING
848 at this point.
850 This effectively reverses part of the logic in lex_string and
851 fix_string_type. */
853 static enum cpp_ttype
854 get_cpp_ttype_from_string_type (tree string_type)
856 gcc_assert (string_type);
857 if (TREE_CODE (string_type) == POINTER_TYPE)
858 string_type = TREE_TYPE (string_type);
860 if (TREE_CODE (string_type) != ARRAY_TYPE)
861 return CPP_OTHER;
863 tree element_type = TREE_TYPE (string_type);
864 if (TREE_CODE (element_type) != INTEGER_TYPE)
865 return CPP_OTHER;
867 int bits_per_character = TYPE_PRECISION (element_type);
868 switch (bits_per_character)
870 case 8:
871 return CPP_STRING; /* It could have also been CPP_UTF8STRING. */
872 case 16:
873 return CPP_STRING16;
874 case 32:
875 return CPP_STRING32;
878 return CPP_OTHER;
881 /* The global record of string concatentations, for use in
882 extracting locations within string literals. */
884 GTY(()) string_concat_db *g_string_concat_db;
886 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION. */
888 const char *
889 c_get_substring_location (const substring_loc &substr_loc,
890 location_t *out_loc)
892 enum cpp_ttype tok_type
893 = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
894 if (tok_type == CPP_OTHER)
895 return "unrecognized string type";
897 return get_location_within_string (parse_in,
898 global_dc->get_file_cache (),
899 g_string_concat_db,
900 substr_loc.get_fmt_string_loc (),
901 tok_type,
902 substr_loc.get_caret_idx (),
903 substr_loc.get_start_idx (),
904 substr_loc.get_end_idx (),
905 out_loc);
909 /* Return true iff T is a boolean promoted to int. */
911 bool
912 bool_promoted_to_int_p (tree t)
914 return (CONVERT_EXPR_P (t)
915 && TREE_TYPE (t) == integer_type_node
916 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
919 /* vector_targets_convertible_p is used for vector pointer types. The
920 callers perform various checks that the qualifiers are satisfactory,
921 while OTOH vector_targets_convertible_p ignores the number of elements
922 in the vectors. That's fine with vector pointers as we can consider,
923 say, a vector of 8 elements as two consecutive vectors of 4 elements,
924 and that does not require and conversion of the pointer values.
925 In contrast, vector_types_convertible_p and
926 vector_types_compatible_elements_p are used for vector value types. */
927 /* True if pointers to distinct types T1 and T2 can be converted to
928 each other without an explicit cast. Only returns true for opaque
929 vector types. */
930 bool
931 vector_targets_convertible_p (const_tree t1, const_tree t2)
933 if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
934 && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
935 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
936 return true;
938 return false;
941 /* vector_types_convertible_p is used for vector value types.
942 It could in principle call vector_targets_convertible_p as a subroutine,
943 but then the check for vector type would be duplicated with its callers,
944 and also the purpose of vector_targets_convertible_p would become
945 muddled.
946 Where vector_types_convertible_p returns true, a conversion might still be
947 needed to make the types match.
948 In contrast, vector_targets_convertible_p is used for vector pointer
949 values, and vector_types_compatible_elements_p is used specifically
950 in the context for binary operators, as a check if use is possible without
951 conversion. */
952 /* True if vector types T1 and T2 can be converted to each other
953 without an explicit cast. If EMIT_LAX_NOTE is true, and T1 and T2
954 can only be converted with -flax-vector-conversions yet that is not
955 in effect, emit a note telling the user about that option if such
956 a note has not previously been emitted. */
957 bool
958 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
960 static bool emitted_lax_note = false;
961 bool convertible_lax;
963 if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
964 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
965 return true;
967 convertible_lax =
968 (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
969 && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
970 || known_eq (TYPE_VECTOR_SUBPARTS (t1),
971 TYPE_VECTOR_SUBPARTS (t2)))
972 && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
973 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
975 if (!convertible_lax || flag_lax_vector_conversions)
976 return convertible_lax;
978 if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
979 && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
980 return true;
982 if (emit_lax_note && !emitted_lax_note)
984 emitted_lax_note = true;
985 inform (input_location, "use %<-flax-vector-conversions%> to permit "
986 "conversions between vectors with differing "
987 "element types or numbers of subparts");
990 return false;
993 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
994 and have vector types, V0 has the same type as V1, and the number of
995 elements of V0, V1, MASK is the same.
997 In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
998 called with two arguments. In this case implementation passes the
999 first argument twice in order to share the same tree code. This fact
1000 could enable the mask-values being twice the vector length. This is
1001 an implementation accident and this semantics is not guaranteed to
1002 the user. */
1003 tree
1004 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
1005 bool complain)
1007 tree ret;
1008 bool wrap = true;
1009 bool maybe_const = false;
1010 bool two_arguments = false;
1012 if (v1 == NULL_TREE)
1014 two_arguments = true;
1015 v1 = v0;
1018 if (v0 == error_mark_node || v1 == error_mark_node
1019 || mask == error_mark_node)
1020 return error_mark_node;
1022 if (!gnu_vector_type_p (TREE_TYPE (mask))
1023 || !VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
1025 if (complain)
1026 error_at (loc, "%<__builtin_shuffle%> last argument must "
1027 "be an integer vector");
1028 return error_mark_node;
1031 if (!gnu_vector_type_p (TREE_TYPE (v0))
1032 || !gnu_vector_type_p (TREE_TYPE (v1)))
1034 if (complain)
1035 error_at (loc, "%<__builtin_shuffle%> arguments must be vectors");
1036 return error_mark_node;
1039 if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1041 if (complain)
1042 error_at (loc, "%<__builtin_shuffle%> argument vectors must be of "
1043 "the same type");
1044 return error_mark_node;
1047 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1048 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1049 && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1050 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1052 if (complain)
1053 error_at (loc, "%<__builtin_shuffle%> number of elements of the "
1054 "argument vector(s) and the mask vector should "
1055 "be the same");
1056 return error_mark_node;
1059 if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1060 != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1062 if (complain)
1063 error_at (loc, "%<__builtin_shuffle%> argument vector(s) inner type "
1064 "must have the same size as inner type of the mask");
1065 return error_mark_node;
1068 if (!c_dialect_cxx ())
1070 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1071 v0 = c_fully_fold (v0, false, &maybe_const);
1072 wrap &= maybe_const;
1074 if (two_arguments)
1075 v1 = v0 = save_expr (v0);
1076 else
1078 v1 = c_fully_fold (v1, false, &maybe_const);
1079 wrap &= maybe_const;
1082 mask = c_fully_fold (mask, false, &maybe_const);
1083 wrap &= maybe_const;
1085 else if (two_arguments)
1086 v1 = v0 = save_expr (v0);
1088 ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1090 if (!c_dialect_cxx () && !wrap)
1091 ret = c_wrap_maybe_const (ret, true);
1093 return ret;
1096 /* Build a VEC_PERM_EXPR if V0, V1 are not error_mark_nodes
1097 and have vector types, V0 has the same element type as V1, and the
1098 number of elements the result is that of MASK. */
1099 tree
1100 c_build_shufflevector (location_t loc, tree v0, tree v1,
1101 const vec<tree> &mask, bool complain)
1103 tree ret;
1104 bool wrap = true;
1105 bool maybe_const = false;
1107 if (v0 == error_mark_node || v1 == error_mark_node)
1108 return error_mark_node;
1110 if (!gnu_vector_type_p (TREE_TYPE (v0))
1111 || !gnu_vector_type_p (TREE_TYPE (v1)))
1113 if (complain)
1114 error_at (loc, "%<__builtin_shufflevector%> arguments must be vectors");
1115 return error_mark_node;
1118 /* ??? In principle one could select a constant part of a variable size
1119 vector but things get a bit awkward with trying to support this here. */
1120 unsigned HOST_WIDE_INT v0n, v1n;
1121 if (!TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)).is_constant (&v0n)
1122 || !TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)).is_constant (&v1n))
1124 if (complain)
1125 error_at (loc, "%<__builtin_shufflevector%> arguments must be constant"
1126 " size vectors");
1127 return error_mark_node;
1130 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v0)))
1131 != TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (v1))))
1133 if (complain)
1134 error_at (loc, "%<__builtin_shufflevector%> argument vectors must "
1135 "have the same element type");
1136 return error_mark_node;
1139 if (!pow2p_hwi (mask.length ()))
1141 if (complain)
1142 error_at (loc, "%<__builtin_shufflevector%> must specify a result "
1143 "with a power of two number of elements");
1144 return error_mark_node;
1147 if (!c_dialect_cxx ())
1149 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1150 v0 = c_fully_fold (v0, false, &maybe_const);
1151 wrap &= maybe_const;
1153 v1 = c_fully_fold (v1, false, &maybe_const);
1154 wrap &= maybe_const;
1157 unsigned HOST_WIDE_INT maskl = MAX (mask.length (), MAX (v0n, v1n));
1158 unsigned HOST_WIDE_INT pad = (v0n < maskl ? maskl - v0n : 0);
1159 vec_perm_builder sel (maskl, maskl, 1);
1160 unsigned i;
1161 for (i = 0; i < mask.length (); ++i)
1163 tree idx = mask[i];
1164 if (!tree_fits_shwi_p (idx))
1166 if (complain)
1167 error_at (loc, "invalid element index %qE to "
1168 "%<__builtin_shufflevector%>", idx);
1169 return error_mark_node;
1171 HOST_WIDE_INT iidx = tree_to_shwi (idx);
1172 if (iidx < -1
1173 || (iidx != -1
1174 && (unsigned HOST_WIDE_INT) iidx >= v0n + v1n))
1176 if (complain)
1177 error_at (loc, "invalid element index %qE to "
1178 "%<__builtin_shufflevector%>", idx);
1179 return error_mark_node;
1181 /* ??? Our VEC_PERM_EXPR does not allow for -1 yet. */
1182 if (iidx == -1)
1183 iidx = i;
1184 /* ??? Our VEC_PERM_EXPR does not allow different sized inputs,
1185 so pad out a smaller v0. */
1186 else if ((unsigned HOST_WIDE_INT) iidx >= v0n)
1187 iidx += pad;
1188 sel.quick_push (iidx);
1190 /* ??? VEC_PERM_EXPR does not support a result that is smaller than
1191 the inputs, so we have to pad id out. */
1192 for (; i < maskl; ++i)
1193 sel.quick_push (i);
1195 vec_perm_indices indices (sel, 2, maskl);
1197 tree ret_type = build_vector_type (TREE_TYPE (TREE_TYPE (v0)), maskl);
1198 tree mask_type = build_vector_type (build_nonstandard_integer_type
1199 (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (ret_type))), 1),
1200 maskl);
1201 /* Pad out arguments to the common vector size. */
1202 if (v0n < maskl)
1204 constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v0)) };
1205 v0 = build_constructor_single (ret_type, NULL_TREE, v0);
1206 for (i = 1; i < maskl / v0n; ++i)
1207 vec_safe_push (CONSTRUCTOR_ELTS (v0), elt);
1209 if (v1n < maskl)
1211 constructor_elt elt = { NULL_TREE, build_zero_cst (TREE_TYPE (v1)) };
1212 v1 = build_constructor_single (ret_type, NULL_TREE, v1);
1213 for (i = 1; i < maskl / v1n; ++i)
1214 vec_safe_push (CONSTRUCTOR_ELTS (v1), elt);
1216 ret = build3_loc (loc, VEC_PERM_EXPR, ret_type, v0, v1,
1217 vec_perm_indices_to_tree (mask_type, indices));
1218 /* Get the lowpart we are interested in. */
1219 if (mask.length () < maskl)
1221 tree lpartt = build_vector_type (TREE_TYPE (ret_type), mask.length ());
1222 ret = build3_loc (loc, BIT_FIELD_REF,
1223 lpartt, ret, TYPE_SIZE (lpartt), bitsize_zero_node);
1224 /* Wrap the lowpart operation in a TARGET_EXPR so it gets a separate
1225 temporary during gimplification. See PR101530 for cases where
1226 we'd otherwise end up with non-toplevel BIT_FIELD_REFs. */
1227 tree tem = create_tmp_var_raw (lpartt);
1228 DECL_CONTEXT (tem) = current_function_decl;
1229 ret = build4 (TARGET_EXPR, lpartt, tem, ret, NULL_TREE, NULL_TREE);
1230 TREE_SIDE_EFFECTS (ret) = 1;
1233 if (!c_dialect_cxx () && !wrap)
1234 ret = c_wrap_maybe_const (ret, true);
1236 return ret;
1239 /* Build a VEC_CONVERT ifn for __builtin_convertvector builtin. */
1241 tree
1242 c_build_vec_convert (location_t loc1, tree expr, location_t loc2, tree type,
1243 bool complain)
1245 if (error_operand_p (type))
1246 return error_mark_node;
1247 if (error_operand_p (expr))
1248 return error_mark_node;
1250 if (!gnu_vector_type_p (TREE_TYPE (expr))
1251 || (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1252 && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (expr))))
1254 if (complain)
1255 error_at (loc1, "%<__builtin_convertvector%> first argument must "
1256 "be an integer or floating vector");
1257 return error_mark_node;
1260 if (!gnu_vector_type_p (type)
1261 || (!VECTOR_INTEGER_TYPE_P (type) && !VECTOR_FLOAT_TYPE_P (type)))
1263 if (complain)
1264 error_at (loc2, "%<__builtin_convertvector%> second argument must "
1265 "be an integer or floating vector type");
1266 return error_mark_node;
1269 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (expr)),
1270 TYPE_VECTOR_SUBPARTS (type)))
1272 if (complain)
1273 error_at (loc1, "%<__builtin_convertvector%> number of elements "
1274 "of the first argument vector and the second argument "
1275 "vector type should be the same");
1276 return error_mark_node;
1279 if ((TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (expr)))
1280 == TYPE_MAIN_VARIANT (TREE_TYPE (type)))
1281 || (VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1282 && VECTOR_INTEGER_TYPE_P (type)
1283 && (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (expr)))
1284 == TYPE_PRECISION (TREE_TYPE (type)))))
1285 return build1_loc (loc1, VIEW_CONVERT_EXPR, type, expr);
1287 bool wrap = true;
1288 bool maybe_const = false;
1289 tree ret;
1290 if (!c_dialect_cxx ())
1292 /* Avoid C_MAYBE_CONST_EXPRs inside of VEC_CONVERT argument. */
1293 expr = c_fully_fold (expr, false, &maybe_const);
1294 wrap &= maybe_const;
1297 ret = build_call_expr_internal_loc (loc1, IFN_VEC_CONVERT, type, 1, expr);
1299 if (!wrap)
1300 ret = c_wrap_maybe_const (ret, true);
1302 return ret;
1305 /* Like tree.cc:get_narrower, but retain conversion from C++0x scoped enum
1306 to integral type. */
1308 tree
1309 c_common_get_narrower (tree op, int *unsignedp_ptr)
1311 op = get_narrower (op, unsignedp_ptr);
1313 if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1314 && ENUM_IS_SCOPED (TREE_TYPE (op)))
1316 /* C++0x scoped enumerations don't implicitly convert to integral
1317 type; if we stripped an explicit conversion to a larger type we
1318 need to replace it so common_type will still work. */
1319 tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1320 TYPE_UNSIGNED (TREE_TYPE (op)));
1321 op = fold_convert (type, op);
1323 return op;
1326 /* This is a helper function of build_binary_op.
1328 For certain operations if both args were extended from the same
1329 smaller type, do the arithmetic in that type and then extend.
1331 BITWISE indicates a bitwise operation.
1332 For them, this optimization is safe only if
1333 both args are zero-extended or both are sign-extended.
1334 Otherwise, we might change the result.
1335 Eg, (short)-1 | (unsigned short)-1 is (int)-1
1336 but calculated in (unsigned short) it would be (unsigned short)-1.
1338 tree
1339 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1341 int unsigned0, unsigned1;
1342 tree arg0, arg1;
1343 int uns;
1344 tree type;
1346 /* Do not shorten vector operations. */
1347 if (VECTOR_TYPE_P (result_type))
1348 return result_type;
1350 /* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
1351 excessive narrowing when we call get_narrower below. For
1352 example, suppose that OP0 is of unsigned int extended
1353 from signed char and that RESULT_TYPE is long long int.
1354 If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1355 like
1357 (long long int) (unsigned int) signed_char
1359 which get_narrower would narrow down to
1361 (unsigned int) signed char
1363 If we do not cast OP0 first, get_narrower would return
1364 signed_char, which is inconsistent with the case of the
1365 explicit cast. */
1366 op0 = convert (result_type, op0);
1367 op1 = convert (result_type, op1);
1369 arg0 = c_common_get_narrower (op0, &unsigned0);
1370 arg1 = c_common_get_narrower (op1, &unsigned1);
1372 /* UNS is 1 if the operation to be done is an unsigned one. */
1373 uns = TYPE_UNSIGNED (result_type);
1375 /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1376 but it *requires* conversion to FINAL_TYPE. */
1378 if ((TYPE_PRECISION (TREE_TYPE (op0))
1379 == TYPE_PRECISION (TREE_TYPE (arg0)))
1380 && TREE_TYPE (op0) != result_type)
1381 unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1382 if ((TYPE_PRECISION (TREE_TYPE (op1))
1383 == TYPE_PRECISION (TREE_TYPE (arg1)))
1384 && TREE_TYPE (op1) != result_type)
1385 unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1387 /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
1389 /* For bitwise operations, signedness of nominal type
1390 does not matter. Consider only how operands were extended. */
1391 if (bitwise)
1392 uns = unsigned0;
1394 /* Note that in all three cases below we refrain from optimizing
1395 an unsigned operation on sign-extended args.
1396 That would not be valid. */
1398 /* Both args variable: if both extended in same way
1399 from same width, do it in that width.
1400 Do it unsigned if args were zero-extended. */
1401 if ((TYPE_PRECISION (TREE_TYPE (arg0))
1402 < TYPE_PRECISION (result_type))
1403 && (TYPE_PRECISION (TREE_TYPE (arg1))
1404 == TYPE_PRECISION (TREE_TYPE (arg0)))
1405 && unsigned0 == unsigned1
1406 && (unsigned0 || !uns))
1408 tree ctype = common_type (TREE_TYPE (arg0), TREE_TYPE (arg1));
1409 if (ctype != error_mark_node)
1410 return c_common_signed_or_unsigned_type (unsigned0, ctype);
1413 else if (TREE_CODE (arg0) == INTEGER_CST
1414 && (unsigned1 || !uns)
1415 && (TYPE_PRECISION (TREE_TYPE (arg1))
1416 < TYPE_PRECISION (result_type))
1417 && (type
1418 = c_common_signed_or_unsigned_type (unsigned1,
1419 TREE_TYPE (arg1)))
1420 && !POINTER_TYPE_P (type)
1421 && int_fits_type_p (arg0, type))
1422 return type;
1424 else if (TREE_CODE (arg1) == INTEGER_CST
1425 && (unsigned0 || !uns)
1426 && (TYPE_PRECISION (TREE_TYPE (arg0))
1427 < TYPE_PRECISION (result_type))
1428 && (type
1429 = c_common_signed_or_unsigned_type (unsigned0,
1430 TREE_TYPE (arg0)))
1431 && !POINTER_TYPE_P (type)
1432 && int_fits_type_p (arg1, type))
1433 return type;
1435 return result_type;
1438 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1439 real of type TO_TYPE. This is a helper function for unsafe_conversion_p. */
1441 static bool
1442 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1444 tree type_low_bound = TYPE_MIN_VALUE (from_type);
1445 tree type_high_bound = TYPE_MAX_VALUE (from_type);
1446 REAL_VALUE_TYPE real_low_bound =
1447 real_value_from_int_cst (0, type_low_bound);
1448 REAL_VALUE_TYPE real_high_bound =
1449 real_value_from_int_cst (0, type_high_bound);
1451 return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1452 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1455 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1456 to the complex/real/integer type TYPE. Function returns non-zero when:
1457 * EXPR is a constant which cannot be exactly converted to TYPE.
1458 * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1459 for EXPR type and TYPE being both integers or both real, or both
1460 complex.
1461 * EXPR is not a constant of complex type and TYPE is a real or
1462 an integer.
1463 * EXPR is not a constant of real type and TYPE is an integer.
1464 * EXPR is not a constant of integer type which cannot be
1465 exactly converted to real type.
1467 Function allows conversions between types of different signedness if
1468 CHECK_SIGN is false and can return SAFE_CONVERSION (zero) in that
1469 case. Function can return UNSAFE_SIGN if CHECK_SIGN is true.
1471 RESULT, when non-null is the result of the conversion. When constant
1472 it is included in the text of diagnostics.
1474 Function allows conversions from complex constants to non-complex types,
1475 provided that imaginary part is zero and real part can be safely converted
1476 to TYPE. */
1478 enum conversion_safety
1479 unsafe_conversion_p (tree type, tree expr, tree result, bool check_sign)
1481 enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1482 tree expr_type = TREE_TYPE (expr);
1484 expr = fold_for_warn (expr);
1486 if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1488 /* If type is complex, we are interested in compatibility with
1489 underlying type. */
1490 if (TREE_CODE (type) == COMPLEX_TYPE)
1491 type = TREE_TYPE (type);
1493 /* Warn for real constant that is not an exact integer converted
1494 to integer type. */
1495 if (SCALAR_FLOAT_TYPE_P (expr_type)
1496 && (TREE_CODE (type) == INTEGER_TYPE
1497 || TREE_CODE (type) == BITINT_TYPE))
1499 if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1500 give_warning = UNSAFE_REAL;
1502 /* Warn for an integer constant that does not fit into integer type. */
1503 else if ((TREE_CODE (expr_type) == INTEGER_TYPE
1504 || TREE_CODE (expr_type) == BITINT_TYPE)
1505 && (TREE_CODE (type) == INTEGER_TYPE
1506 || TREE_CODE (type) == BITINT_TYPE)
1507 && !int_fits_type_p (expr, type))
1509 if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1510 && tree_int_cst_sgn (expr) < 0)
1512 if (check_sign)
1513 give_warning = UNSAFE_SIGN;
1515 else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1517 if (check_sign)
1518 give_warning = UNSAFE_SIGN;
1520 else
1521 give_warning = UNSAFE_OTHER;
1523 else if (SCALAR_FLOAT_TYPE_P (type))
1525 /* Warn for an integer constant that does not fit into real type. */
1526 if (TREE_CODE (expr_type) == INTEGER_TYPE
1527 || TREE_CODE (expr_type) == BITINT_TYPE)
1529 REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1530 if (!exact_real_truncate (TYPE_MODE (type), &a))
1531 give_warning = UNSAFE_REAL;
1533 /* Warn for a real constant that does not fit into a smaller
1534 real type. */
1535 else if (SCALAR_FLOAT_TYPE_P (expr_type)
1536 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1538 REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1539 if (!exact_real_truncate (TYPE_MODE (type), &a))
1540 give_warning = UNSAFE_REAL;
1545 else if (TREE_CODE (expr) == COMPLEX_CST)
1547 tree imag_part = TREE_IMAGPART (expr);
1548 /* Conversion from complex constant with zero imaginary part,
1549 perform check for conversion of real part. */
1550 if ((TREE_CODE (imag_part) == REAL_CST
1551 && real_zerop (imag_part))
1552 || (TREE_CODE (imag_part) == INTEGER_CST
1553 && integer_zerop (imag_part)))
1554 /* Note: in this branch we use recursive call to unsafe_conversion_p
1555 with different type of EXPR, but it is still safe, because when EXPR
1556 is a constant, it's type is not used in text of generated warnings
1557 (otherwise they could sound misleading). */
1558 return unsafe_conversion_p (type, TREE_REALPART (expr), result,
1559 check_sign);
1560 /* Conversion from complex constant with non-zero imaginary part. */
1561 else
1563 /* Conversion to complex type.
1564 Perform checks for both real and imaginary parts. */
1565 if (TREE_CODE (type) == COMPLEX_TYPE)
1567 enum conversion_safety re_safety =
1568 unsafe_conversion_p (type, TREE_REALPART (expr),
1569 result, check_sign);
1570 enum conversion_safety im_safety =
1571 unsafe_conversion_p (type, imag_part, result, check_sign);
1573 /* Merge the results into appropriate single warning. */
1575 /* Note: this case includes SAFE_CONVERSION, i.e. success. */
1576 if (re_safety == im_safety)
1577 give_warning = re_safety;
1578 else if (!re_safety && im_safety)
1579 give_warning = im_safety;
1580 else if (re_safety && !im_safety)
1581 give_warning = re_safety;
1582 else
1583 give_warning = UNSAFE_OTHER;
1585 /* Warn about conversion from complex to real or integer type. */
1586 else
1587 give_warning = UNSAFE_IMAGINARY;
1591 /* Checks for remaining case: EXPR is not constant. */
1592 else
1594 /* Warn for real types converted to integer types. */
1595 if (SCALAR_FLOAT_TYPE_P (expr_type)
1596 && (TREE_CODE (type) == INTEGER_TYPE
1597 || TREE_CODE (type) == BITINT_TYPE))
1598 give_warning = UNSAFE_REAL;
1600 else if ((TREE_CODE (expr_type) == INTEGER_TYPE
1601 || TREE_CODE (expr_type) == BITINT_TYPE)
1602 && (TREE_CODE (type) == INTEGER_TYPE
1603 || TREE_CODE (type) == BITINT_TYPE))
1605 /* Don't warn about unsigned char y = 0xff, x = (int) y; */
1606 expr = get_unwidened (expr, 0);
1607 expr_type = TREE_TYPE (expr);
1609 /* Don't warn for short y; short x = ((int)y & 0xff); */
1610 if (TREE_CODE (expr) == BIT_AND_EXPR
1611 || TREE_CODE (expr) == BIT_IOR_EXPR
1612 || TREE_CODE (expr) == BIT_XOR_EXPR)
1614 /* If both args were extended from a shortest type,
1615 use that type if that is safe. */
1616 expr_type = shorten_binary_op (expr_type,
1617 TREE_OPERAND (expr, 0),
1618 TREE_OPERAND (expr, 1),
1619 /* bitwise */1);
1621 if (TREE_CODE (expr) == BIT_AND_EXPR)
1623 tree op0 = TREE_OPERAND (expr, 0);
1624 tree op1 = TREE_OPERAND (expr, 1);
1625 bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1626 bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1628 /* If one of the operands is a non-negative constant
1629 that fits in the target type, then the type of the
1630 other operand does not matter. */
1631 if ((TREE_CODE (op0) == INTEGER_CST
1632 && int_fits_type_p (op0, c_common_signed_type (type))
1633 && int_fits_type_p (op0, c_common_unsigned_type (type)))
1634 || (TREE_CODE (op1) == INTEGER_CST
1635 && int_fits_type_p (op1, c_common_signed_type (type))
1636 && int_fits_type_p (op1,
1637 c_common_unsigned_type (type))))
1638 return SAFE_CONVERSION;
1639 /* If constant is unsigned and fits in the target
1640 type, then the result will also fit. */
1641 else if ((TREE_CODE (op0) == INTEGER_CST
1642 && unsigned0
1643 && int_fits_type_p (op0, type))
1644 || (TREE_CODE (op1) == INTEGER_CST
1645 && unsigned1
1646 && int_fits_type_p (op1, type)))
1647 return SAFE_CONVERSION;
1650 /* Warn for integer types converted to smaller integer types. */
1651 if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1652 give_warning = UNSAFE_OTHER;
1654 /* When they are the same width but different signedness,
1655 then the value may change. */
1656 else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1657 && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1658 /* Even when converted to a bigger type, if the type is
1659 unsigned but expr is signed, then negative values
1660 will be changed. */
1661 || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1662 && check_sign)
1663 give_warning = UNSAFE_SIGN;
1666 /* Warn for integer types converted to real types if and only if
1667 all the range of values of the integer type cannot be
1668 represented by the real type. */
1669 else if ((TREE_CODE (expr_type) == INTEGER_TYPE
1670 || TREE_CODE (expr_type) == BITINT_TYPE)
1671 && SCALAR_FLOAT_TYPE_P (type))
1673 /* Don't warn about char y = 0xff; float x = (int) y; */
1674 expr = get_unwidened (expr, 0);
1675 expr_type = TREE_TYPE (expr);
1677 if (!int_safely_convertible_to_real_p (expr_type, type))
1678 give_warning = UNSAFE_OTHER;
1681 /* Warn for real types converted to smaller real types. */
1682 else if (SCALAR_FLOAT_TYPE_P (expr_type)
1683 && SCALAR_FLOAT_TYPE_P (type)
1684 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1685 give_warning = UNSAFE_REAL;
1687 /* Check conversion between two complex types. */
1688 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1689 && TREE_CODE (type) == COMPLEX_TYPE)
1691 /* Extract underlying types (i.e., type of real and imaginary
1692 parts) of expr_type and type. */
1693 tree from_type = TREE_TYPE (expr_type);
1694 tree to_type = TREE_TYPE (type);
1696 /* Warn for real types converted to integer types. */
1697 if (SCALAR_FLOAT_TYPE_P (from_type)
1698 && TREE_CODE (to_type) == INTEGER_TYPE)
1699 give_warning = UNSAFE_REAL;
1701 /* Warn for real types converted to smaller real types. */
1702 else if (SCALAR_FLOAT_TYPE_P (from_type)
1703 && SCALAR_FLOAT_TYPE_P (to_type)
1704 && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1705 give_warning = UNSAFE_REAL;
1707 /* Check conversion for complex integer types. Here implementation
1708 is simpler than for real-domain integers because it does not
1709 involve sophisticated cases, such as bitmasks, casts, etc. */
1710 else if (TREE_CODE (from_type) == INTEGER_TYPE
1711 && TREE_CODE (to_type) == INTEGER_TYPE)
1713 /* Warn for integer types converted to smaller integer types. */
1714 if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1715 give_warning = UNSAFE_OTHER;
1717 /* Check for different signedness, see case for real-domain
1718 integers (above) for a more detailed comment. */
1719 else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1720 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1721 || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1722 && check_sign)
1723 give_warning = UNSAFE_SIGN;
1725 else if (TREE_CODE (from_type) == INTEGER_TYPE
1726 && SCALAR_FLOAT_TYPE_P (to_type)
1727 && !int_safely_convertible_to_real_p (from_type, to_type))
1728 give_warning = UNSAFE_OTHER;
1731 /* Warn for complex types converted to real or integer types. */
1732 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1733 && TREE_CODE (type) != COMPLEX_TYPE)
1734 give_warning = UNSAFE_IMAGINARY;
1737 return give_warning;
1741 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1742 Invoke this function on every expression that is converted implicitly,
1743 i.e. because of language rules and not because of an explicit cast.
1744 INIT_CONST is true if the conversion is for arithmetic types for a static
1745 initializer and folding must apply accordingly (discarding floating-point
1746 exceptions and assuming the default rounding mode is in effect). */
1748 tree
1749 convert_and_check (location_t loc, tree type, tree expr, bool init_const)
1751 tree result;
1752 tree expr_for_warning;
1754 /* Convert from a value with possible excess precision rather than
1755 via the semantic type, but do not warn about values not fitting
1756 exactly in the semantic type. */
1757 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1759 tree orig_type = TREE_TYPE (expr);
1760 expr = TREE_OPERAND (expr, 0);
1761 expr_for_warning = (init_const
1762 ? convert_init (orig_type, expr)
1763 : convert (orig_type, expr));
1764 if (orig_type == type)
1765 return expr_for_warning;
1767 else
1768 expr_for_warning = expr;
1770 if (TREE_TYPE (expr) == type)
1771 return expr;
1773 result = init_const ? convert_init (type, expr) : convert (type, expr);
1775 if (c_inhibit_evaluation_warnings == 0
1776 && !TREE_OVERFLOW_P (expr)
1777 && result != error_mark_node)
1778 warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1780 return result;
1783 /* A node in a list that describes references to variables (EXPR), which are
1784 either read accesses if WRITER is zero, or write accesses, in which case
1785 WRITER is the parent of EXPR. */
1786 struct tlist
1788 struct tlist *next;
1789 tree expr, writer;
1792 /* Used to implement a cache the results of a call to verify_tree. We only
1793 use this for SAVE_EXPRs. */
1794 struct tlist_cache
1796 struct tlist_cache *next;
1797 struct tlist *cache_before_sp;
1798 struct tlist *cache_after_sp;
1799 tree expr;
1802 /* Obstack to use when allocating tlist structures, and corresponding
1803 firstobj. */
1804 static struct obstack tlist_obstack;
1805 static char *tlist_firstobj = 0;
1807 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1808 warnings. */
1809 static struct tlist *warned_ids;
1810 /* SAVE_EXPRs need special treatment. We process them only once and then
1811 cache the results. */
1812 static struct tlist_cache *save_expr_cache;
1814 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1815 static void merge_tlist (struct tlist **, struct tlist *, int);
1816 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1817 static bool warning_candidate_p (tree);
1818 static bool candidate_equal_p (const_tree, const_tree);
1819 static void warn_for_collisions (struct tlist *);
1820 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1821 static struct tlist *new_tlist (struct tlist *, tree, tree);
1823 /* Create a new struct tlist and fill in its fields. */
1824 static struct tlist *
1825 new_tlist (struct tlist *next, tree t, tree writer)
1827 struct tlist *l;
1828 l = XOBNEW (&tlist_obstack, struct tlist);
1829 l->next = next;
1830 l->expr = t;
1831 l->writer = writer;
1832 return l;
1835 /* Add duplicates of the nodes found in ADD to the list *TO. If EXCLUDE_WRITER
1836 is nonnull, we ignore any node we find which has a writer equal to it. */
1838 static void
1839 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1841 while (add)
1843 struct tlist *next = add->next;
1844 if (!copy)
1845 add->next = *to;
1846 if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1847 *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1848 add = next;
1852 /* Merge the nodes of ADD into TO. This merging process is done so that for
1853 each variable that already exists in TO, no new node is added; however if
1854 there is a write access recorded in ADD, and an occurrence on TO is only
1855 a read access, then the occurrence in TO will be modified to record the
1856 write. */
1858 static void
1859 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1861 struct tlist **end = to;
1863 while (*end)
1864 end = &(*end)->next;
1866 while (add)
1868 int found = 0;
1869 struct tlist *tmp2;
1870 struct tlist *next = add->next;
1872 for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1873 if (candidate_equal_p (tmp2->expr, add->expr))
1875 found = 1;
1876 if (!tmp2->writer)
1877 tmp2->writer = add->writer;
1879 if (!found)
1881 *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1882 end = &(*end)->next;
1883 *end = 0;
1885 add = next;
1889 /* WRITTEN is a variable, WRITER is its parent. Warn if any of the variable
1890 references in list LIST conflict with it, excluding reads if ONLY writers
1891 is nonzero. */
1893 static void
1894 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1895 int only_writes)
1897 struct tlist *tmp;
1899 /* Avoid duplicate warnings. */
1900 for (tmp = warned_ids; tmp; tmp = tmp->next)
1901 if (candidate_equal_p (tmp->expr, written))
1902 return;
1904 while (list)
1906 if (candidate_equal_p (list->expr, written)
1907 && !candidate_equal_p (list->writer, writer)
1908 && (!only_writes || list->writer))
1910 warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1911 warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1912 OPT_Wsequence_point, "operation on %qE may be undefined",
1913 list->expr);
1915 list = list->next;
1919 /* Given a list LIST of references to variables, find whether any of these
1920 can cause conflicts due to missing sequence points. */
1922 static void
1923 warn_for_collisions (struct tlist *list)
1925 struct tlist *tmp;
1927 for (tmp = list; tmp; tmp = tmp->next)
1929 if (tmp->writer)
1930 warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1934 /* Return nonzero if X is a tree that can be verified by the sequence point
1935 warnings. */
1937 static bool
1938 warning_candidate_p (tree x)
1940 if (DECL_P (x) && DECL_ARTIFICIAL (x))
1941 return false;
1943 if (TREE_CODE (x) == BLOCK)
1944 return false;
1946 /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.cc
1947 (lvalue_p) crash on TRY/CATCH. */
1948 if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1949 return false;
1951 if (!lvalue_p (x))
1952 return false;
1954 /* No point to track non-const calls, they will never satisfy
1955 operand_equal_p. */
1956 if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1957 return false;
1959 if (TREE_CODE (x) == STRING_CST)
1960 return false;
1962 return true;
1965 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1966 static bool
1967 candidate_equal_p (const_tree x, const_tree y)
1969 return (x == y) || (x && y && operand_equal_p (x, y, 0));
1972 /* Walk the tree X, and record accesses to variables. If X is written by the
1973 parent tree, WRITER is the parent.
1974 We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP. If this
1975 expression or its only operand forces a sequence point, then everything up
1976 to the sequence point is stored in PBEFORE_SP. Everything else gets stored
1977 in PNO_SP.
1978 Once we return, we will have emitted warnings if any subexpression before
1979 such a sequence point could be undefined. On a higher level, however, the
1980 sequence point may not be relevant, and we'll merge the two lists.
1982 Example: (b++, a) + b;
1983 The call that processes the COMPOUND_EXPR will store the increment of B
1984 in PBEFORE_SP, and the use of A in PNO_SP. The higher-level call that
1985 processes the PLUS_EXPR will need to merge the two lists so that
1986 eventually, all accesses end up on the same list (and we'll warn about the
1987 unordered subexpressions b++ and b.
1989 A note on merging. If we modify the former example so that our expression
1990 becomes
1991 (b++, b) + a
1992 care must be taken not simply to add all three expressions into the final
1993 PNO_SP list. The function merge_tlist takes care of that by merging the
1994 before-SP list of the COMPOUND_EXPR into its after-SP list in a special
1995 way, so that no more than one access to B is recorded. */
1997 static void
1998 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
1999 tree writer)
2001 struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
2002 enum tree_code code;
2003 enum tree_code_class cl;
2005 restart:
2006 /* X may be NULL if it is the operand of an empty statement expression
2007 ({ }). */
2008 if (x == NULL)
2009 return;
2011 code = TREE_CODE (x);
2012 cl = TREE_CODE_CLASS (code);
2014 if (warning_candidate_p (x))
2015 *pno_sp = new_tlist (*pno_sp, x, writer);
2017 switch (code)
2019 case CONSTRUCTOR:
2020 case SIZEOF_EXPR:
2021 case PAREN_SIZEOF_EXPR:
2022 return;
2024 case COMPOUND_EXPR:
2025 case TRUTH_ANDIF_EXPR:
2026 case TRUTH_ORIF_EXPR:
2027 sequenced_binary:
2028 tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
2029 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2030 warn_for_collisions (tmp_nosp);
2031 merge_tlist (pbefore_sp, tmp_before, 0);
2032 merge_tlist (pbefore_sp, tmp_nosp, 0);
2033 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
2034 warn_for_collisions (tmp_list2);
2035 merge_tlist (pbefore_sp, tmp_list3, 0);
2036 merge_tlist (pno_sp, tmp_list2, 0);
2037 return;
2039 case COND_EXPR:
2040 tmp_before = tmp_list2 = 0;
2041 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
2042 warn_for_collisions (tmp_list2);
2043 merge_tlist (pbefore_sp, tmp_before, 0);
2044 merge_tlist (pbefore_sp, tmp_list2, 0);
2046 tmp_list3 = tmp_nosp = 0;
2047 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
2048 warn_for_collisions (tmp_nosp);
2049 merge_tlist (pbefore_sp, tmp_list3, 0);
2051 tmp_list3 = tmp_list2 = 0;
2052 verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
2053 warn_for_collisions (tmp_list2);
2054 merge_tlist (pbefore_sp, tmp_list3, 0);
2055 /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
2056 two first, to avoid warning for (a ? b++ : b++). */
2057 merge_tlist (&tmp_nosp, tmp_list2, 0);
2058 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2059 return;
2061 case PREDECREMENT_EXPR:
2062 case PREINCREMENT_EXPR:
2063 case POSTDECREMENT_EXPR:
2064 case POSTINCREMENT_EXPR:
2065 verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
2066 return;
2068 case MODIFY_EXPR:
2069 tmp_before = tmp_nosp = tmp_list3 = 0;
2070 verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
2071 verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
2072 /* Expressions inside the LHS are not ordered wrt. the sequence points
2073 in the RHS. Example:
2074 *a = (a++, 2)
2075 Despite the fact that the modification of "a" is in the before_sp
2076 list (tmp_before), it conflicts with the use of "a" in the LHS.
2077 We can handle this by adding the contents of tmp_list3
2078 to those of tmp_before, and redoing the collision warnings for that
2079 list. */
2080 add_tlist (&tmp_before, tmp_list3, x, 1);
2081 warn_for_collisions (tmp_before);
2082 /* Exclude the LHS itself here; we first have to merge it into the
2083 tmp_nosp list. This is done to avoid warning for "a = a"; if we
2084 didn't exclude the LHS, we'd get it twice, once as a read and once
2085 as a write. */
2086 add_tlist (pno_sp, tmp_list3, x, 0);
2087 warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
2089 merge_tlist (pbefore_sp, tmp_before, 0);
2090 if (warning_candidate_p (TREE_OPERAND (x, 0)))
2091 merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
2092 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
2093 return;
2095 case CALL_EXPR:
2096 /* We need to warn about conflicts among arguments and conflicts between
2097 args and the function address. Side effects of the function address,
2098 however, are not ordered by the sequence point of the call. */
2100 call_expr_arg_iterator iter;
2101 tree arg;
2102 tmp_before = tmp_nosp = 0;
2103 verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
2104 FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
2106 tmp_list2 = tmp_list3 = 0;
2107 verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
2108 merge_tlist (&tmp_list3, tmp_list2, 0);
2109 add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
2111 add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
2112 warn_for_collisions (tmp_before);
2113 add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
2114 return;
2117 case TREE_LIST:
2118 /* Scan all the list, e.g. indices of multi dimensional array. */
2119 while (x)
2121 tmp_before = tmp_nosp = 0;
2122 verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
2123 merge_tlist (&tmp_nosp, tmp_before, 0);
2124 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2125 x = TREE_CHAIN (x);
2127 return;
2129 case SAVE_EXPR:
2131 struct tlist_cache *t;
2132 for (t = save_expr_cache; t; t = t->next)
2133 if (candidate_equal_p (t->expr, x))
2134 break;
2136 if (!t)
2138 t = XOBNEW (&tlist_obstack, struct tlist_cache);
2139 t->next = save_expr_cache;
2140 t->expr = x;
2141 save_expr_cache = t;
2143 tmp_before = tmp_nosp = 0;
2144 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
2145 warn_for_collisions (tmp_nosp);
2147 tmp_list3 = 0;
2148 merge_tlist (&tmp_list3, tmp_nosp, 0);
2149 t->cache_before_sp = tmp_before;
2150 t->cache_after_sp = tmp_list3;
2152 merge_tlist (pbefore_sp, t->cache_before_sp, 1);
2153 add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
2154 return;
2157 case ADDR_EXPR:
2158 x = TREE_OPERAND (x, 0);
2159 if (DECL_P (x))
2160 return;
2161 writer = 0;
2162 goto restart;
2164 case VIEW_CONVERT_EXPR:
2165 if (location_wrapper_p (x))
2167 x = TREE_OPERAND (x, 0);
2168 goto restart;
2170 goto do_default;
2172 case LSHIFT_EXPR:
2173 case RSHIFT_EXPR:
2174 case ARRAY_REF:
2175 if (cxx_dialect >= cxx17)
2176 goto sequenced_binary;
2177 goto do_default;
2179 case COMPONENT_REF:
2180 /* Treat as unary, the other operands aren't evaluated. */
2181 x = TREE_OPERAND (x, 0);
2182 writer = 0;
2183 goto restart;
2185 default:
2186 do_default:
2187 /* For other expressions, simply recurse on their operands.
2188 Manual tail recursion for unary expressions.
2189 Other non-expressions need not be processed. */
2190 if (cl == tcc_unary)
2192 x = TREE_OPERAND (x, 0);
2193 writer = 0;
2194 goto restart;
2196 else if (IS_EXPR_CODE_CLASS (cl))
2198 int lp;
2199 int max = TREE_OPERAND_LENGTH (x);
2200 for (lp = 0; lp < max; lp++)
2202 tmp_before = tmp_nosp = 0;
2203 verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
2204 merge_tlist (&tmp_nosp, tmp_before, 0);
2205 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2208 return;
2212 static constexpr size_t verify_sequence_points_limit = 1024;
2214 /* Called from verify_sequence_points via walk_tree. */
2216 static tree
2217 verify_tree_lim_r (tree *tp, int *walk_subtrees, void *data)
2219 if (++*((size_t *) data) > verify_sequence_points_limit)
2220 return integer_zero_node;
2222 if (TYPE_P (*tp))
2223 *walk_subtrees = 0;
2225 return NULL_TREE;
2228 /* Try to warn for undefined behavior in EXPR due to missing sequence
2229 points. */
2231 void
2232 verify_sequence_points (tree expr)
2234 tlist *before_sp = nullptr, *after_sp = nullptr;
2236 /* verify_tree is highly recursive, and merge_tlist is O(n^2),
2237 so we return early if the expression is too big. */
2238 size_t n = 0;
2239 if (walk_tree (&expr, verify_tree_lim_r, &n, nullptr))
2240 return;
2242 warned_ids = nullptr;
2243 save_expr_cache = nullptr;
2244 if (!tlist_firstobj)
2246 gcc_obstack_init (&tlist_obstack);
2247 tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
2250 verify_tree (expr, &before_sp, &after_sp, NULL_TREE);
2251 warn_for_collisions (after_sp);
2252 obstack_free (&tlist_obstack, tlist_firstobj);
2255 /* Validate the expression after `case' and apply default promotions. */
2257 static tree
2258 check_case_value (location_t loc, tree value)
2260 if (value == NULL_TREE)
2261 return value;
2263 if (INTEGRAL_TYPE_P (TREE_TYPE (value))
2264 && TREE_CODE (value) == INTEGER_CST)
2265 /* Promote char or short to int. */
2266 value = perform_integral_promotions (value);
2267 else if (value != error_mark_node)
2269 error_at (loc, "case label does not reduce to an integer constant");
2270 value = error_mark_node;
2273 constant_expression_warning (value);
2275 return value;
2278 /* Return an integer type with BITS bits of precision,
2279 that is unsigned if UNSIGNEDP is nonzero, otherwise signed. */
2281 tree
2282 c_common_type_for_size (unsigned int bits, int unsignedp)
2284 int i;
2286 if (bits == TYPE_PRECISION (integer_type_node))
2287 return unsignedp ? unsigned_type_node : integer_type_node;
2289 if (bits == TYPE_PRECISION (signed_char_type_node))
2290 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2292 if (bits == TYPE_PRECISION (short_integer_type_node))
2293 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2295 if (bits == TYPE_PRECISION (long_integer_type_node))
2296 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2298 if (bits == TYPE_PRECISION (long_long_integer_type_node))
2299 return (unsignedp ? long_long_unsigned_type_node
2300 : long_long_integer_type_node);
2302 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2303 if (int_n_enabled_p[i]
2304 && bits == int_n_data[i].bitsize)
2305 return (unsignedp ? int_n_trees[i].unsigned_type
2306 : int_n_trees[i].signed_type);
2308 if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2309 return (unsignedp ? widest_unsigned_literal_type_node
2310 : widest_integer_literal_type_node);
2312 if (bits <= TYPE_PRECISION (intQI_type_node))
2313 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2315 if (bits <= TYPE_PRECISION (intHI_type_node))
2316 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2318 if (bits <= TYPE_PRECISION (intSI_type_node))
2319 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2321 if (bits <= TYPE_PRECISION (intDI_type_node))
2322 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2324 if (bits <= TYPE_PRECISION (widest_integer_literal_type_node))
2325 return (unsignedp ? widest_unsigned_literal_type_node
2326 : widest_integer_literal_type_node);
2328 return NULL_TREE;
2331 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2332 that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2333 and saturating if SATP is nonzero, otherwise not saturating. */
2335 tree
2336 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2337 int unsignedp, int satp)
2339 enum mode_class mclass;
2340 if (ibit == 0)
2341 mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2342 else
2343 mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2345 opt_scalar_mode opt_mode;
2346 scalar_mode mode;
2347 FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2349 mode = opt_mode.require ();
2350 if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2351 break;
2354 if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2356 sorry ("GCC cannot support operators with integer types and "
2357 "fixed-point types that have too many integral and "
2358 "fractional bits together");
2359 return NULL_TREE;
2362 return c_common_type_for_mode (mode, satp);
2365 /* Used for communication between c_common_type_for_mode and
2366 c_register_builtin_type. */
2367 tree registered_builtin_types;
2369 /* Return a data type that has machine mode MODE.
2370 If the mode is an integer,
2371 then UNSIGNEDP selects between signed and unsigned types.
2372 If the mode is a fixed-point mode,
2373 then UNSIGNEDP selects between saturating and nonsaturating types. */
2375 tree
2376 c_common_type_for_mode (machine_mode mode, int unsignedp)
2378 tree t;
2379 int i;
2381 if (mode == TYPE_MODE (integer_type_node))
2382 return unsignedp ? unsigned_type_node : integer_type_node;
2384 if (mode == TYPE_MODE (signed_char_type_node))
2385 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2387 if (mode == TYPE_MODE (short_integer_type_node))
2388 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2390 if (mode == TYPE_MODE (long_integer_type_node))
2391 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2393 if (mode == TYPE_MODE (long_long_integer_type_node))
2394 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2396 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2397 if (int_n_enabled_p[i]
2398 && mode == int_n_data[i].m)
2399 return (unsignedp ? int_n_trees[i].unsigned_type
2400 : int_n_trees[i].signed_type);
2402 if (mode == QImode)
2403 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2405 if (mode == HImode)
2406 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2408 if (mode == SImode)
2409 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2411 if (mode == DImode)
2412 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2414 #if HOST_BITS_PER_WIDE_INT >= 64
2415 if (mode == TYPE_MODE (intTI_type_node))
2416 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2417 #endif
2419 if (mode == TYPE_MODE (float_type_node))
2420 return float_type_node;
2422 if (mode == TYPE_MODE (double_type_node))
2423 return double_type_node;
2425 if (mode == TYPE_MODE (long_double_type_node))
2426 return long_double_type_node;
2428 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2429 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2430 && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2431 return FLOATN_NX_TYPE_NODE (i);
2433 if (mode == TYPE_MODE (void_type_node))
2434 return void_type_node;
2436 if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2437 || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2439 unsigned int precision
2440 = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2441 return (unsignedp
2442 ? make_unsigned_type (precision)
2443 : make_signed_type (precision));
2446 if (COMPLEX_MODE_P (mode))
2448 machine_mode inner_mode;
2449 tree inner_type;
2451 if (mode == TYPE_MODE (complex_float_type_node))
2452 return complex_float_type_node;
2453 if (mode == TYPE_MODE (complex_double_type_node))
2454 return complex_double_type_node;
2455 if (mode == TYPE_MODE (complex_long_double_type_node))
2456 return complex_long_double_type_node;
2458 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2459 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2460 && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2461 return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2463 if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2464 return complex_integer_type_node;
2466 inner_mode = GET_MODE_INNER (mode);
2467 inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2468 if (inner_type != NULL_TREE)
2469 return build_complex_type (inner_type);
2471 else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
2472 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2474 unsigned int elem_bits = vector_element_size (GET_MODE_PRECISION (mode),
2475 GET_MODE_NUNITS (mode));
2476 tree bool_type = build_nonstandard_boolean_type (elem_bits);
2477 return build_vector_type_for_mode (bool_type, mode);
2479 else if (VECTOR_MODE_P (mode)
2480 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2482 machine_mode inner_mode = GET_MODE_INNER (mode);
2483 tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2484 if (inner_type != NULL_TREE)
2485 return build_vector_type_for_mode (inner_type, mode);
2488 if (dfloat32_type_node != NULL_TREE
2489 && mode == TYPE_MODE (dfloat32_type_node))
2490 return dfloat32_type_node;
2491 if (dfloat64_type_node != NULL_TREE
2492 && mode == TYPE_MODE (dfloat64_type_node))
2493 return dfloat64_type_node;
2494 if (dfloat128_type_node != NULL_TREE
2495 && mode == TYPE_MODE (dfloat128_type_node))
2496 return dfloat128_type_node;
2498 if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2500 if (mode == TYPE_MODE (short_fract_type_node))
2501 return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2502 if (mode == TYPE_MODE (fract_type_node))
2503 return unsignedp ? sat_fract_type_node : fract_type_node;
2504 if (mode == TYPE_MODE (long_fract_type_node))
2505 return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2506 if (mode == TYPE_MODE (long_long_fract_type_node))
2507 return unsignedp ? sat_long_long_fract_type_node
2508 : long_long_fract_type_node;
2510 if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2511 return unsignedp ? sat_unsigned_short_fract_type_node
2512 : unsigned_short_fract_type_node;
2513 if (mode == TYPE_MODE (unsigned_fract_type_node))
2514 return unsignedp ? sat_unsigned_fract_type_node
2515 : unsigned_fract_type_node;
2516 if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2517 return unsignedp ? sat_unsigned_long_fract_type_node
2518 : unsigned_long_fract_type_node;
2519 if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2520 return unsignedp ? sat_unsigned_long_long_fract_type_node
2521 : unsigned_long_long_fract_type_node;
2523 if (mode == TYPE_MODE (short_accum_type_node))
2524 return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2525 if (mode == TYPE_MODE (accum_type_node))
2526 return unsignedp ? sat_accum_type_node : accum_type_node;
2527 if (mode == TYPE_MODE (long_accum_type_node))
2528 return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2529 if (mode == TYPE_MODE (long_long_accum_type_node))
2530 return unsignedp ? sat_long_long_accum_type_node
2531 : long_long_accum_type_node;
2533 if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2534 return unsignedp ? sat_unsigned_short_accum_type_node
2535 : unsigned_short_accum_type_node;
2536 if (mode == TYPE_MODE (unsigned_accum_type_node))
2537 return unsignedp ? sat_unsigned_accum_type_node
2538 : unsigned_accum_type_node;
2539 if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2540 return unsignedp ? sat_unsigned_long_accum_type_node
2541 : unsigned_long_accum_type_node;
2542 if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2543 return unsignedp ? sat_unsigned_long_long_accum_type_node
2544 : unsigned_long_long_accum_type_node;
2546 if (mode == QQmode)
2547 return unsignedp ? sat_qq_type_node : qq_type_node;
2548 if (mode == HQmode)
2549 return unsignedp ? sat_hq_type_node : hq_type_node;
2550 if (mode == SQmode)
2551 return unsignedp ? sat_sq_type_node : sq_type_node;
2552 if (mode == DQmode)
2553 return unsignedp ? sat_dq_type_node : dq_type_node;
2554 if (mode == TQmode)
2555 return unsignedp ? sat_tq_type_node : tq_type_node;
2557 if (mode == UQQmode)
2558 return unsignedp ? sat_uqq_type_node : uqq_type_node;
2559 if (mode == UHQmode)
2560 return unsignedp ? sat_uhq_type_node : uhq_type_node;
2561 if (mode == USQmode)
2562 return unsignedp ? sat_usq_type_node : usq_type_node;
2563 if (mode == UDQmode)
2564 return unsignedp ? sat_udq_type_node : udq_type_node;
2565 if (mode == UTQmode)
2566 return unsignedp ? sat_utq_type_node : utq_type_node;
2568 if (mode == HAmode)
2569 return unsignedp ? sat_ha_type_node : ha_type_node;
2570 if (mode == SAmode)
2571 return unsignedp ? sat_sa_type_node : sa_type_node;
2572 if (mode == DAmode)
2573 return unsignedp ? sat_da_type_node : da_type_node;
2574 if (mode == TAmode)
2575 return unsignedp ? sat_ta_type_node : ta_type_node;
2577 if (mode == UHAmode)
2578 return unsignedp ? sat_uha_type_node : uha_type_node;
2579 if (mode == USAmode)
2580 return unsignedp ? sat_usa_type_node : usa_type_node;
2581 if (mode == UDAmode)
2582 return unsignedp ? sat_uda_type_node : uda_type_node;
2583 if (mode == UTAmode)
2584 return unsignedp ? sat_uta_type_node : uta_type_node;
2587 for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2589 tree type = TREE_VALUE (t);
2590 if (TYPE_MODE (type) == mode
2591 && VECTOR_TYPE_P (type) == VECTOR_MODE_P (mode)
2592 && !!unsignedp == !!TYPE_UNSIGNED (type))
2593 return type;
2595 return NULL_TREE;
2598 tree
2599 c_common_unsigned_type (tree type)
2601 return c_common_signed_or_unsigned_type (1, type);
2604 /* Return a signed type the same as TYPE in other respects. */
2606 tree
2607 c_common_signed_type (tree type)
2609 return c_common_signed_or_unsigned_type (0, type);
2612 /* Return a type the same as TYPE except unsigned or
2613 signed according to UNSIGNEDP. */
2615 tree
2616 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2618 tree type1;
2619 int i;
2621 /* This block of code emulates the behavior of the old
2622 c_common_unsigned_type. In particular, it returns
2623 long_unsigned_type_node if passed a long, even when a int would
2624 have the same size. This is necessary for warnings to work
2625 correctly in archs where sizeof(int) == sizeof(long) */
2627 type1 = TYPE_MAIN_VARIANT (type);
2628 if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2629 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2630 if (type1 == integer_type_node || type1 == unsigned_type_node)
2631 return unsignedp ? unsigned_type_node : integer_type_node;
2632 if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2633 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2634 if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2635 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2636 if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2637 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2639 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2640 if (int_n_enabled_p[i]
2641 && (type1 == int_n_trees[i].unsigned_type
2642 || type1 == int_n_trees[i].signed_type))
2643 return (unsignedp ? int_n_trees[i].unsigned_type
2644 : int_n_trees[i].signed_type);
2646 #if HOST_BITS_PER_WIDE_INT >= 64
2647 if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2648 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2649 #endif
2650 if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2651 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2652 if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2653 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2654 if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2655 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2656 if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2657 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2659 #define C_COMMON_FIXED_TYPES(NAME) \
2660 if (type1 == short_ ## NAME ## _type_node \
2661 || type1 == unsigned_short_ ## NAME ## _type_node) \
2662 return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2663 : short_ ## NAME ## _type_node; \
2664 if (type1 == NAME ## _type_node \
2665 || type1 == unsigned_ ## NAME ## _type_node) \
2666 return unsignedp ? unsigned_ ## NAME ## _type_node \
2667 : NAME ## _type_node; \
2668 if (type1 == long_ ## NAME ## _type_node \
2669 || type1 == unsigned_long_ ## NAME ## _type_node) \
2670 return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2671 : long_ ## NAME ## _type_node; \
2672 if (type1 == long_long_ ## NAME ## _type_node \
2673 || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2674 return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2675 : long_long_ ## NAME ## _type_node;
2677 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2678 if (type1 == NAME ## _type_node \
2679 || type1 == u ## NAME ## _type_node) \
2680 return unsignedp ? u ## NAME ## _type_node \
2681 : NAME ## _type_node;
2683 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2684 if (type1 == sat_ ## short_ ## NAME ## _type_node \
2685 || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2686 return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2687 : sat_ ## short_ ## NAME ## _type_node; \
2688 if (type1 == sat_ ## NAME ## _type_node \
2689 || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2690 return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2691 : sat_ ## NAME ## _type_node; \
2692 if (type1 == sat_ ## long_ ## NAME ## _type_node \
2693 || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2694 return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2695 : sat_ ## long_ ## NAME ## _type_node; \
2696 if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2697 || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2698 return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2699 : sat_ ## long_long_ ## NAME ## _type_node;
2701 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME) \
2702 if (type1 == sat_ ## NAME ## _type_node \
2703 || type1 == sat_ ## u ## NAME ## _type_node) \
2704 return unsignedp ? sat_ ## u ## NAME ## _type_node \
2705 : sat_ ## NAME ## _type_node;
2707 C_COMMON_FIXED_TYPES (fract);
2708 C_COMMON_FIXED_TYPES_SAT (fract);
2709 C_COMMON_FIXED_TYPES (accum);
2710 C_COMMON_FIXED_TYPES_SAT (accum);
2712 C_COMMON_FIXED_MODE_TYPES (qq);
2713 C_COMMON_FIXED_MODE_TYPES (hq);
2714 C_COMMON_FIXED_MODE_TYPES (sq);
2715 C_COMMON_FIXED_MODE_TYPES (dq);
2716 C_COMMON_FIXED_MODE_TYPES (tq);
2717 C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2718 C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2719 C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2720 C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2721 C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2722 C_COMMON_FIXED_MODE_TYPES (ha);
2723 C_COMMON_FIXED_MODE_TYPES (sa);
2724 C_COMMON_FIXED_MODE_TYPES (da);
2725 C_COMMON_FIXED_MODE_TYPES (ta);
2726 C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2727 C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2728 C_COMMON_FIXED_MODE_TYPES_SAT (da);
2729 C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2731 /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2732 the precision; they have precision set to match their range, but
2733 may use a wider mode to match an ABI. If we change modes, we may
2734 wind up with bad conversions. For INTEGER_TYPEs in C, must check
2735 the precision as well, so as to yield correct results for
2736 bit-field types. C++ does not have these separate bit-field
2737 types, and producing a signed or unsigned variant of an
2738 ENUMERAL_TYPE may cause other problems as well. */
2740 if (!INTEGRAL_TYPE_P (type)
2741 || TYPE_UNSIGNED (type) == unsignedp)
2742 return type;
2744 if (TREE_CODE (type) == BITINT_TYPE
2745 /* signed _BitInt(1) is invalid, avoid creating that. */
2746 && (unsignedp || TYPE_PRECISION (type) > 1))
2747 return build_bitint_type (TYPE_PRECISION (type), unsignedp);
2749 #define TYPE_OK(node) \
2750 (TYPE_MODE (type) == TYPE_MODE (node) \
2751 && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2752 if (TYPE_OK (signed_char_type_node))
2753 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2754 if (TYPE_OK (integer_type_node))
2755 return unsignedp ? unsigned_type_node : integer_type_node;
2756 if (TYPE_OK (short_integer_type_node))
2757 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2758 if (TYPE_OK (long_integer_type_node))
2759 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2760 if (TYPE_OK (long_long_integer_type_node))
2761 return (unsignedp ? long_long_unsigned_type_node
2762 : long_long_integer_type_node);
2764 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2765 if (int_n_enabled_p[i]
2766 && TYPE_MODE (type) == int_n_data[i].m
2767 && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2768 return (unsignedp ? int_n_trees[i].unsigned_type
2769 : int_n_trees[i].signed_type);
2771 #if HOST_BITS_PER_WIDE_INT >= 64
2772 if (TYPE_OK (intTI_type_node))
2773 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2774 #endif
2775 if (TYPE_OK (intDI_type_node))
2776 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2777 if (TYPE_OK (intSI_type_node))
2778 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2779 if (TYPE_OK (intHI_type_node))
2780 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2781 if (TYPE_OK (intQI_type_node))
2782 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2783 #undef TYPE_OK
2785 return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2788 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP. */
2790 tree
2791 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2793 int i;
2795 /* Extended integer types of the same width as a standard type have
2796 lesser rank, so those of the same width as int promote to int or
2797 unsigned int and are valid for printf formats expecting int or
2798 unsigned int. To avoid such special cases, avoid creating
2799 extended integer types for bit-fields if a standard integer type
2800 is available. */
2801 if (width == TYPE_PRECISION (integer_type_node))
2802 return unsignedp ? unsigned_type_node : integer_type_node;
2803 if (width == TYPE_PRECISION (signed_char_type_node))
2804 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2805 if (width == TYPE_PRECISION (short_integer_type_node))
2806 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2807 if (width == TYPE_PRECISION (long_integer_type_node))
2808 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2809 if (width == TYPE_PRECISION (long_long_integer_type_node))
2810 return (unsignedp ? long_long_unsigned_type_node
2811 : long_long_integer_type_node);
2812 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2813 if (int_n_enabled_p[i]
2814 && width == int_n_data[i].bitsize)
2815 return (unsignedp ? int_n_trees[i].unsigned_type
2816 : int_n_trees[i].signed_type);
2817 return build_nonstandard_integer_type (width, unsignedp);
2820 /* The C version of the register_builtin_type langhook. */
2822 void
2823 c_register_builtin_type (tree type, const char* name)
2825 tree decl;
2827 decl = build_decl (UNKNOWN_LOCATION,
2828 TYPE_DECL, get_identifier (name), type);
2829 DECL_ARTIFICIAL (decl) = 1;
2830 if (!TYPE_NAME (type))
2831 TYPE_NAME (type) = decl;
2832 lang_hooks.decls.pushdecl (decl);
2834 registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2837 /* Print an error message for invalid operands to arith operation
2838 CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2839 RICHLOC is a rich location for the message, containing either
2840 three separate locations for each of the operator and operands
2842 lhs op rhs
2843 ~~~ ^~ ~~~
2845 (C FE), or one location ranging over all over them
2847 lhs op rhs
2848 ~~~~^~~~~~
2850 (C++ FE). */
2852 void
2853 binary_op_error (rich_location *richloc, enum tree_code code,
2854 tree type0, tree type1)
2856 const char *opname;
2858 switch (code)
2860 case PLUS_EXPR:
2861 opname = "+"; break;
2862 case MINUS_EXPR:
2863 opname = "-"; break;
2864 case MULT_EXPR:
2865 opname = "*"; break;
2866 case MAX_EXPR:
2867 opname = "max"; break;
2868 case MIN_EXPR:
2869 opname = "min"; break;
2870 case EQ_EXPR:
2871 opname = "=="; break;
2872 case NE_EXPR:
2873 opname = "!="; break;
2874 case LE_EXPR:
2875 opname = "<="; break;
2876 case GE_EXPR:
2877 opname = ">="; break;
2878 case LT_EXPR:
2879 opname = "<"; break;
2880 case GT_EXPR:
2881 opname = ">"; break;
2882 case LSHIFT_EXPR:
2883 opname = "<<"; break;
2884 case RSHIFT_EXPR:
2885 opname = ">>"; break;
2886 case TRUNC_MOD_EXPR:
2887 case FLOOR_MOD_EXPR:
2888 opname = "%"; break;
2889 case TRUNC_DIV_EXPR:
2890 case FLOOR_DIV_EXPR:
2891 opname = "/"; break;
2892 case BIT_AND_EXPR:
2893 opname = "&"; break;
2894 case BIT_IOR_EXPR:
2895 opname = "|"; break;
2896 case TRUTH_ANDIF_EXPR:
2897 opname = "&&"; break;
2898 case TRUTH_ORIF_EXPR:
2899 opname = "||"; break;
2900 case BIT_XOR_EXPR:
2901 opname = "^"; break;
2902 default:
2903 gcc_unreachable ();
2905 error_at (richloc,
2906 "invalid operands to binary %s (have %qT and %qT)",
2907 opname, type0, type1);
2910 /* Given an expression as a tree, return its original type. Do this
2911 by stripping any conversion that preserves the sign and precision. */
2912 static tree
2913 expr_original_type (tree expr)
2915 STRIP_SIGN_NOPS (expr);
2916 return TREE_TYPE (expr);
2919 /* Subroutine of build_binary_op, used for comparison operations.
2920 See if the operands have both been converted from subword integer types
2921 and, if so, perhaps change them both back to their original type.
2922 This function is also responsible for converting the two operands
2923 to the proper common type for comparison.
2925 The arguments of this function are all pointers to local variables
2926 of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2927 RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2929 LOC is the location of the comparison.
2931 If this function returns non-NULL_TREE, it means that the comparison has
2932 a constant value. What this function returns is an expression for
2933 that value. */
2935 tree
2936 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2937 tree *restype_ptr, enum tree_code *rescode_ptr)
2939 tree type;
2940 tree op0 = *op0_ptr;
2941 tree op1 = *op1_ptr;
2942 int unsignedp0, unsignedp1;
2943 int real1, real2;
2944 tree primop0, primop1;
2945 enum tree_code code = *rescode_ptr;
2947 /* Throw away any conversions to wider types
2948 already present in the operands. */
2950 primop0 = c_common_get_narrower (op0, &unsignedp0);
2951 primop1 = c_common_get_narrower (op1, &unsignedp1);
2953 /* If primopN is first sign-extended from primopN's precision to opN's
2954 precision, then zero-extended from opN's precision to
2955 *restype_ptr precision, shortenings might be invalid. */
2956 if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2957 && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2958 && !unsignedp0
2959 && TYPE_UNSIGNED (TREE_TYPE (op0)))
2960 primop0 = op0;
2961 if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2962 && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2963 && !unsignedp1
2964 && TYPE_UNSIGNED (TREE_TYPE (op1)))
2965 primop1 = op1;
2967 /* Handle the case that OP0 does not *contain* a conversion
2968 but it *requires* conversion to FINAL_TYPE. */
2970 if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2971 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2972 if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2973 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2975 /* If one of the operands must be floated, we cannot optimize. */
2976 real1 = SCALAR_FLOAT_TYPE_P (TREE_TYPE (primop0));
2977 real2 = SCALAR_FLOAT_TYPE_P (TREE_TYPE (primop1));
2979 /* If first arg is constant, swap the args (changing operation
2980 so value is preserved), for canonicalization. Don't do this if
2981 the second arg is 0. */
2983 if (TREE_CONSTANT (primop0)
2984 && !integer_zerop (primop1) && !real_zerop (primop1)
2985 && !fixed_zerop (primop1))
2987 std::swap (primop0, primop1);
2988 std::swap (op0, op1);
2989 *op0_ptr = op0;
2990 *op1_ptr = op1;
2991 std::swap (unsignedp0, unsignedp1);
2992 std::swap (real1, real2);
2994 switch (code)
2996 case LT_EXPR:
2997 code = GT_EXPR;
2998 break;
2999 case GT_EXPR:
3000 code = LT_EXPR;
3001 break;
3002 case LE_EXPR:
3003 code = GE_EXPR;
3004 break;
3005 case GE_EXPR:
3006 code = LE_EXPR;
3007 break;
3008 default:
3009 break;
3011 *rescode_ptr = code;
3014 /* If comparing an integer against a constant more bits wide,
3015 maybe we can deduce a value of 1 or 0 independent of the data.
3016 Or else truncate the constant now
3017 rather than extend the variable at run time.
3019 This is only interesting if the constant is the wider arg.
3020 Also, it is not safe if the constant is unsigned and the
3021 variable arg is signed, since in this case the variable
3022 would be sign-extended and then regarded as unsigned.
3023 Our technique fails in this case because the lowest/highest
3024 possible unsigned results don't follow naturally from the
3025 lowest/highest possible values of the variable operand.
3026 For just EQ_EXPR and NE_EXPR there is another technique that
3027 could be used: see if the constant can be faithfully represented
3028 in the other operand's type, by truncating it and reextending it
3029 and see if that preserves the constant's value. */
3031 if (!real1 && !real2
3032 && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
3033 && TREE_CODE (primop1) == INTEGER_CST
3034 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
3036 int min_gt, max_gt, min_lt, max_lt;
3037 tree maxval, minval;
3038 /* 1 if comparison is nominally unsigned. */
3039 int unsignedp = TYPE_UNSIGNED (*restype_ptr);
3040 tree val;
3042 type = c_common_signed_or_unsigned_type (unsignedp0,
3043 TREE_TYPE (primop0));
3045 maxval = TYPE_MAX_VALUE (type);
3046 minval = TYPE_MIN_VALUE (type);
3048 if (unsignedp && !unsignedp0)
3049 *restype_ptr = c_common_signed_type (*restype_ptr);
3051 if (TREE_TYPE (primop1) != *restype_ptr)
3053 /* Convert primop1 to target type, but do not introduce
3054 additional overflow. We know primop1 is an int_cst. */
3055 primop1 = force_fit_type (*restype_ptr,
3056 wi::to_wide
3057 (primop1,
3058 TYPE_PRECISION (*restype_ptr)),
3059 0, TREE_OVERFLOW (primop1));
3061 if (type != *restype_ptr)
3063 minval = convert (*restype_ptr, minval);
3064 maxval = convert (*restype_ptr, maxval);
3067 min_gt = tree_int_cst_lt (primop1, minval);
3068 max_gt = tree_int_cst_lt (primop1, maxval);
3069 min_lt = tree_int_cst_lt (minval, primop1);
3070 max_lt = tree_int_cst_lt (maxval, primop1);
3072 val = 0;
3073 /* This used to be a switch, but Genix compiler can't handle that. */
3074 if (code == NE_EXPR)
3076 if (max_lt || min_gt)
3077 val = truthvalue_true_node;
3079 else if (code == EQ_EXPR)
3081 if (max_lt || min_gt)
3082 val = truthvalue_false_node;
3084 else if (code == LT_EXPR)
3086 if (max_lt)
3087 val = truthvalue_true_node;
3088 if (!min_lt)
3089 val = truthvalue_false_node;
3091 else if (code == GT_EXPR)
3093 if (min_gt)
3094 val = truthvalue_true_node;
3095 if (!max_gt)
3096 val = truthvalue_false_node;
3098 else if (code == LE_EXPR)
3100 if (!max_gt)
3101 val = truthvalue_true_node;
3102 if (min_gt)
3103 val = truthvalue_false_node;
3105 else if (code == GE_EXPR)
3107 if (!min_lt)
3108 val = truthvalue_true_node;
3109 if (max_lt)
3110 val = truthvalue_false_node;
3113 /* If primop0 was sign-extended and unsigned comparison specd,
3114 we did a signed comparison above using the signed type bounds.
3115 But the comparison we output must be unsigned.
3117 Also, for inequalities, VAL is no good; but if the signed
3118 comparison had *any* fixed result, it follows that the
3119 unsigned comparison just tests the sign in reverse
3120 (positive values are LE, negative ones GE).
3121 So we can generate an unsigned comparison
3122 against an extreme value of the signed type. */
3124 if (unsignedp && !unsignedp0)
3126 if (val != 0)
3127 switch (code)
3129 case LT_EXPR:
3130 case GE_EXPR:
3131 primop1 = TYPE_MIN_VALUE (type);
3132 val = 0;
3133 break;
3135 case LE_EXPR:
3136 case GT_EXPR:
3137 primop1 = TYPE_MAX_VALUE (type);
3138 val = 0;
3139 break;
3141 default:
3142 break;
3144 type = c_common_unsigned_type (type);
3147 if (TREE_CODE (primop0) != INTEGER_CST
3148 /* Don't warn if it's from a (non-system) macro. */
3149 && !(from_macro_expansion_at
3150 (expansion_point_location_if_in_system_header
3151 (EXPR_LOCATION (primop0)))))
3153 if (val == truthvalue_false_node)
3154 warning_at (loc, OPT_Wtype_limits,
3155 "comparison is always false due to limited range of data type");
3156 if (val == truthvalue_true_node)
3157 warning_at (loc, OPT_Wtype_limits,
3158 "comparison is always true due to limited range of data type");
3161 if (val != 0)
3163 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3164 if (TREE_SIDE_EFFECTS (primop0))
3165 return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
3166 return val;
3169 /* Value is not predetermined, but do the comparison
3170 in the type of the operand that is not constant.
3171 TYPE is already properly set. */
3174 /* If either arg is decimal float and the other is float, find the
3175 proper common type to use for comparison. */
3176 else if (real1 && real2
3177 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3178 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
3179 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3181 /* If either arg is decimal float and the other is float, fail. */
3182 else if (real1 && real2
3183 && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
3184 || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
3186 type = *restype_ptr;
3187 primop0 = op0;
3188 primop1 = op1;
3191 else if (real1 && real2
3192 && (TYPE_PRECISION (TREE_TYPE (primop0))
3193 == TYPE_PRECISION (TREE_TYPE (primop1))))
3194 type = TREE_TYPE (primop0);
3196 /* If args' natural types are both narrower than nominal type
3197 and both extend in the same manner, compare them
3198 in the type of the wider arg.
3199 Otherwise must actually extend both to the nominal
3200 common type lest different ways of extending
3201 alter the result.
3202 (eg, (short)-1 == (unsigned short)-1 should be 0.) */
3204 else if (unsignedp0 == unsignedp1 && real1 == real2
3205 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
3206 && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr)
3207 && (type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1)))
3208 != error_mark_node)
3210 type = c_common_signed_or_unsigned_type (unsignedp0
3211 || TYPE_UNSIGNED (*restype_ptr),
3212 type);
3213 /* Make sure shorter operand is extended the right way
3214 to match the longer operand. */
3215 primop0
3216 = convert (c_common_signed_or_unsigned_type (unsignedp0,
3217 TREE_TYPE (primop0)),
3218 primop0);
3219 primop1
3220 = convert (c_common_signed_or_unsigned_type (unsignedp1,
3221 TREE_TYPE (primop1)),
3222 primop1);
3224 else
3226 /* Here we must do the comparison on the nominal type
3227 using the args exactly as we received them. */
3228 type = *restype_ptr;
3229 primop0 = op0;
3230 primop1 = op1;
3232 /* We want to fold unsigned comparisons of >= and < against zero.
3233 For these, we may also issue a warning if we have a non-constant
3234 compared against zero, where the zero was spelled as "0" (rather
3235 than merely folding to it).
3236 If we have at least one constant, then op1 is constant
3237 and we may have a non-constant expression as op0. */
3238 if (!real1 && !real2 && integer_zerop (primop1)
3239 && TYPE_UNSIGNED (*restype_ptr))
3241 tree value = NULL_TREE;
3242 /* All unsigned values are >= 0, so we warn. However,
3243 if OP0 is a constant that is >= 0, the signedness of
3244 the comparison isn't an issue, so suppress the
3245 warning. */
3246 tree folded_op0 = fold_for_warn (op0);
3247 bool warn =
3248 warn_type_limits && !in_system_header_at (loc)
3249 && !(TREE_CODE (folded_op0) == INTEGER_CST
3250 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3251 folded_op0)))
3252 /* Do not warn for enumeration types. */
3253 && (TREE_CODE (expr_original_type (folded_op0)) != ENUMERAL_TYPE);
3255 switch (code)
3257 case GE_EXPR:
3258 if (warn)
3259 warning_at (loc, OPT_Wtype_limits,
3260 "comparison of unsigned expression in %<>= 0%> "
3261 "is always true");
3262 value = truthvalue_true_node;
3263 break;
3265 case LT_EXPR:
3266 if (warn)
3267 warning_at (loc, OPT_Wtype_limits,
3268 "comparison of unsigned expression in %<< 0%> "
3269 "is always false");
3270 value = truthvalue_false_node;
3271 break;
3273 default:
3274 break;
3277 if (value != NULL_TREE)
3279 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3280 if (TREE_SIDE_EFFECTS (primop0))
3281 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3282 primop0, value);
3283 return value;
3288 *op0_ptr = convert (type, primop0);
3289 *op1_ptr = convert (type, primop1);
3291 *restype_ptr = truthvalue_type_node;
3293 return NULL_TREE;
3296 /* Return a tree for the sum or difference (RESULTCODE says which)
3297 of pointer PTROP and integer INTOP. */
3299 tree
3300 pointer_int_sum (location_t loc, enum tree_code resultcode,
3301 tree ptrop, tree intop, bool complain)
3303 tree size_exp, ret;
3305 /* The result is a pointer of the same type that is being added. */
3306 tree result_type = TREE_TYPE (ptrop);
3308 if (VOID_TYPE_P (TREE_TYPE (result_type)))
3310 if (complain && warn_pointer_arith)
3311 pedwarn (loc, OPT_Wpointer_arith,
3312 "pointer of type %<void *%> used in arithmetic");
3313 else if (!complain)
3314 return error_mark_node;
3315 size_exp = integer_one_node;
3317 else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3319 if (complain && warn_pointer_arith)
3320 pedwarn (loc, OPT_Wpointer_arith,
3321 "pointer to a function used in arithmetic");
3322 else if (!complain)
3323 return error_mark_node;
3324 size_exp = integer_one_node;
3326 else if (!verify_type_context (loc, TCTX_POINTER_ARITH,
3327 TREE_TYPE (result_type)))
3328 size_exp = integer_one_node;
3329 else
3331 if (!complain && !COMPLETE_TYPE_P (TREE_TYPE (result_type)))
3332 return error_mark_node;
3333 size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3334 /* Wrap the pointer expression in a SAVE_EXPR to make sure it
3335 is evaluated first when the size expression may depend
3336 on it for VM types. */
3337 if (TREE_SIDE_EFFECTS (size_exp)
3338 && TREE_SIDE_EFFECTS (ptrop)
3339 && variably_modified_type_p (TREE_TYPE (ptrop), NULL))
3341 ptrop = save_expr (ptrop);
3342 size_exp = build2 (COMPOUND_EXPR, TREE_TYPE (intop), ptrop, size_exp);
3346 /* We are manipulating pointer values, so we don't need to warn
3347 about relying on undefined signed overflow. We disable the
3348 warning here because we use integer types so fold won't know that
3349 they are really pointers. */
3350 fold_defer_overflow_warnings ();
3352 /* If what we are about to multiply by the size of the elements
3353 contains a constant term, apply distributive law
3354 and multiply that constant term separately.
3355 This helps produce common subexpressions. */
3356 if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3357 && !TREE_CONSTANT (intop)
3358 && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3359 && TREE_CONSTANT (size_exp)
3360 /* If the constant comes from pointer subtraction,
3361 skip this optimization--it would cause an error. */
3362 && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3363 /* If the constant is unsigned, and smaller than the pointer size,
3364 then we must skip this optimization. This is because it could cause
3365 an overflow error if the constant is negative but INTOP is not. */
3366 && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (intop))
3367 || (TYPE_PRECISION (TREE_TYPE (intop))
3368 == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3370 enum tree_code subcode = resultcode;
3371 tree int_type = TREE_TYPE (intop);
3372 if (TREE_CODE (intop) == MINUS_EXPR)
3373 subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3374 /* Convert both subexpression types to the type of intop,
3375 because weird cases involving pointer arithmetic
3376 can result in a sum or difference with different type args. */
3377 ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3378 subcode, ptrop,
3379 convert (int_type, TREE_OPERAND (intop, 1)),
3380 true);
3381 intop = convert (int_type, TREE_OPERAND (intop, 0));
3384 /* Convert the integer argument to a type the same size as sizetype
3385 so the multiply won't overflow spuriously. */
3386 if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3387 || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3388 intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3389 TYPE_UNSIGNED (sizetype)), intop);
3391 /* Replace the integer argument with a suitable product by the object size.
3392 Do this multiplication as signed, then convert to the appropriate type
3393 for the pointer operation and disregard an overflow that occurred only
3394 because of the sign-extension change in the latter conversion. */
3396 tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3397 convert (TREE_TYPE (intop), size_exp));
3398 intop = convert (sizetype, t);
3399 if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3400 intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3403 /* Create the sum or difference. */
3404 if (resultcode == MINUS_EXPR)
3405 intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3407 ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3409 fold_undefer_and_ignore_overflow_warnings ();
3411 return ret;
3414 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3415 and if NON_CONST is known not to be permitted in an evaluated part
3416 of a constant expression. */
3418 tree
3419 c_wrap_maybe_const (tree expr, bool non_const)
3421 location_t loc = EXPR_LOCATION (expr);
3423 /* This should never be called for C++. */
3424 if (c_dialect_cxx ())
3425 gcc_unreachable ();
3427 /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING. */
3428 STRIP_TYPE_NOPS (expr);
3429 expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3430 C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3431 protected_set_expr_location (expr, loc);
3433 return expr;
3436 /* Return whether EXPR is a declaration whose address can never be NULL.
3437 The address of the first struct member could be NULL only if it were
3438 accessed through a NULL pointer, and such an access would be invalid.
3439 The address of a weak symbol may be null unless it has a definition. */
3441 bool
3442 decl_with_nonnull_addr_p (const_tree expr)
3444 if (!DECL_P (expr))
3445 return false;
3447 if (TREE_CODE (expr) == FIELD_DECL
3448 || TREE_CODE (expr) == PARM_DECL
3449 || TREE_CODE (expr) == LABEL_DECL)
3450 return true;
3452 if (!VAR_OR_FUNCTION_DECL_P (expr))
3453 return false;
3455 if (!DECL_WEAK (expr))
3456 /* Ordinary (non-weak) symbols have nonnull addresses. */
3457 return true;
3459 if (DECL_INITIAL (expr) && DECL_INITIAL (expr) != error_mark_node)
3460 /* Initialized weak symbols have nonnull addresses. */
3461 return true;
3463 if (DECL_EXTERNAL (expr) || !TREE_STATIC (expr))
3464 /* Uninitialized extern weak symbols and weak symbols with no
3465 allocated storage might have a null address. */
3466 return false;
3468 tree attribs = DECL_ATTRIBUTES (expr);
3469 if (lookup_attribute ("weakref", attribs))
3470 /* Weakref symbols might have a null address unless their referent
3471 is known not to. Don't bother following weakref targets here. */
3472 return false;
3474 return true;
3477 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3478 or for an `if' or `while' statement or ?..: exp. It should already
3479 have been validated to be of suitable type; otherwise, a bad
3480 diagnostic may result.
3482 The EXPR is located at LOCATION.
3484 This preparation consists of taking the ordinary
3485 representation of an expression expr and producing a valid tree
3486 boolean expression describing whether expr is nonzero. We could
3487 simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3488 but we optimize comparisons, &&, ||, and !.
3490 The resulting type should always be `truthvalue_type_node'. */
3492 tree
3493 c_common_truthvalue_conversion (location_t location, tree expr)
3495 STRIP_ANY_LOCATION_WRAPPER (expr);
3496 switch (TREE_CODE (expr))
3498 case EQ_EXPR: case NE_EXPR: case UNEQ_EXPR: case LTGT_EXPR:
3499 case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
3500 case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3501 case ORDERED_EXPR: case UNORDERED_EXPR:
3502 if (TREE_TYPE (expr) == truthvalue_type_node)
3503 return expr;
3504 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3505 TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3506 goto ret;
3508 case TRUTH_ANDIF_EXPR:
3509 case TRUTH_ORIF_EXPR:
3510 case TRUTH_AND_EXPR:
3511 case TRUTH_OR_EXPR:
3512 case TRUTH_XOR_EXPR:
3513 if (TREE_TYPE (expr) == truthvalue_type_node)
3514 return expr;
3515 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3516 c_common_truthvalue_conversion (location,
3517 TREE_OPERAND (expr, 0)),
3518 c_common_truthvalue_conversion (location,
3519 TREE_OPERAND (expr, 1)));
3520 goto ret;
3522 case TRUTH_NOT_EXPR:
3523 if (TREE_TYPE (expr) == truthvalue_type_node)
3524 return expr;
3525 expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3526 c_common_truthvalue_conversion (location,
3527 TREE_OPERAND (expr, 0)));
3528 goto ret;
3530 case ERROR_MARK:
3531 return expr;
3533 case INTEGER_CST:
3534 if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3535 && !integer_zerop (expr)
3536 && !integer_onep (expr))
3537 warning_at (location, OPT_Wint_in_bool_context,
3538 "enum constant in boolean context");
3539 return integer_zerop (expr) ? truthvalue_false_node
3540 : truthvalue_true_node;
3542 case REAL_CST:
3543 return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3544 ? truthvalue_true_node
3545 : truthvalue_false_node;
3547 case FIXED_CST:
3548 return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3549 &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3550 ? truthvalue_true_node
3551 : truthvalue_false_node;
3553 case FUNCTION_DECL:
3554 expr = build_unary_op (location, ADDR_EXPR, expr, false);
3555 /* Fall through. */
3557 case ADDR_EXPR:
3559 tree inner = TREE_OPERAND (expr, 0);
3560 if (decl_with_nonnull_addr_p (inner)
3561 /* Check both EXPR and INNER for suppression. */
3562 && !warning_suppressed_p (expr, OPT_Waddress)
3563 && !warning_suppressed_p (inner, OPT_Waddress))
3565 /* Common Ada programmer's mistake. */
3566 warning_at (location,
3567 OPT_Waddress,
3568 "the address of %qD will always evaluate as %<true%>",
3569 inner);
3570 suppress_warning (inner, OPT_Waddress);
3571 return truthvalue_true_node;
3573 break;
3576 case COMPLEX_EXPR:
3577 expr = build_binary_op (EXPR_LOCATION (expr),
3578 (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3579 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3580 c_common_truthvalue_conversion (location,
3581 TREE_OPERAND (expr, 0)),
3582 c_common_truthvalue_conversion (location,
3583 TREE_OPERAND (expr, 1)),
3584 false);
3585 goto ret;
3587 case NEGATE_EXPR:
3588 case ABS_EXPR:
3589 case ABSU_EXPR:
3590 case FLOAT_EXPR:
3591 case EXCESS_PRECISION_EXPR:
3592 /* These don't change whether an object is nonzero or zero. */
3593 return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3595 case LROTATE_EXPR:
3596 case RROTATE_EXPR:
3597 /* These don't change whether an object is zero or nonzero, but
3598 we can't ignore them if their second arg has side-effects. */
3599 if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3601 expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3602 TREE_OPERAND (expr, 1),
3603 c_common_truthvalue_conversion
3604 (location, TREE_OPERAND (expr, 0)));
3605 goto ret;
3607 else
3608 return c_common_truthvalue_conversion (location,
3609 TREE_OPERAND (expr, 0));
3611 case MULT_EXPR:
3612 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3613 "%<*%> in boolean context, suggest %<&&%> instead");
3614 break;
3616 case LSHIFT_EXPR:
3617 /* We will only warn on signed shifts here, because the majority of
3618 false positive warnings happen in code where unsigned arithmetic
3619 was used in anticipation of a possible overflow.
3620 Furthermore, if we see an unsigned type here we know that the
3621 result of the shift is not subject to integer promotion rules. */
3622 if ((TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3623 || TREE_CODE (TREE_TYPE (expr)) == BITINT_TYPE)
3624 && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3625 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3626 "%<<<%> in boolean context, did you mean %<<%>?");
3627 break;
3629 case COND_EXPR:
3630 if (warn_int_in_bool_context
3631 && !from_macro_definition_at (EXPR_LOCATION (expr)))
3633 tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3634 tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3635 if (TREE_CODE (val1) == INTEGER_CST
3636 && TREE_CODE (val2) == INTEGER_CST
3637 && !integer_zerop (val1)
3638 && !integer_zerop (val2)
3639 && (!integer_onep (val1)
3640 || !integer_onep (val2)))
3641 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3642 "%<?:%> using integer constants in boolean context, "
3643 "the expression will always evaluate to %<true%>");
3644 else if ((TREE_CODE (val1) == INTEGER_CST
3645 && !integer_zerop (val1)
3646 && !integer_onep (val1))
3647 || (TREE_CODE (val2) == INTEGER_CST
3648 && !integer_zerop (val2)
3649 && !integer_onep (val2)))
3650 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3651 "%<?:%> using integer constants in boolean context");
3653 /* Distribute the conversion into the arms of a COND_EXPR. */
3654 if (c_dialect_cxx ())
3655 /* Avoid premature folding. */
3656 break;
3657 else
3659 int w = warn_int_in_bool_context;
3660 warn_int_in_bool_context = 0;
3661 /* Folding will happen later for C. */
3662 expr = build3 (COND_EXPR, truthvalue_type_node,
3663 TREE_OPERAND (expr, 0),
3664 c_common_truthvalue_conversion (location,
3665 TREE_OPERAND (expr, 1)),
3666 c_common_truthvalue_conversion (location,
3667 TREE_OPERAND (expr, 2)));
3668 warn_int_in_bool_context = w;
3669 goto ret;
3672 CASE_CONVERT:
3674 tree totype = TREE_TYPE (expr);
3675 tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3677 if (POINTER_TYPE_P (totype)
3678 && !c_inhibit_evaluation_warnings
3679 && TREE_CODE (fromtype) == REFERENCE_TYPE)
3681 tree inner = expr;
3682 STRIP_NOPS (inner);
3684 if (DECL_P (inner))
3685 warning_at (location,
3686 OPT_Waddress,
3687 "the compiler can assume that the address of "
3688 "%qD will always evaluate to %<true%>",
3689 inner);
3692 /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3693 since that affects how `default_conversion' will behave. */
3694 if (TREE_CODE (totype) == REFERENCE_TYPE
3695 || TREE_CODE (fromtype) == REFERENCE_TYPE)
3696 break;
3697 /* Don't strip a conversion from C++0x scoped enum, since they
3698 don't implicitly convert to other types. */
3699 if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3700 && ENUM_IS_SCOPED (fromtype))
3701 break;
3702 /* If this isn't narrowing the argument, we can ignore it. */
3703 if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3705 tree op0 = TREE_OPERAND (expr, 0);
3706 if ((TREE_CODE (fromtype) == POINTER_TYPE
3707 && (TREE_CODE (totype) == INTEGER_TYPE
3708 || TREE_CODE (totype) == BITINT_TYPE))
3709 || warning_suppressed_p (expr, OPT_Waddress))
3710 /* Suppress -Waddress for casts to intptr_t, propagating
3711 any suppression from the enclosing expression to its
3712 operand. */
3713 suppress_warning (op0, OPT_Waddress);
3714 return c_common_truthvalue_conversion (location, op0);
3717 break;
3719 case MODIFY_EXPR:
3720 if (!warning_suppressed_p (expr, OPT_Wparentheses)
3721 && warn_parentheses
3722 && warning_at (location, OPT_Wparentheses,
3723 "suggest parentheses around assignment used as "
3724 "truth value"))
3725 suppress_warning (expr, OPT_Wparentheses);
3726 break;
3728 case CONST_DECL:
3730 tree folded_expr = fold_for_warn (expr);
3731 if (folded_expr != expr)
3732 return c_common_truthvalue_conversion (location, folded_expr);
3734 break;
3736 default:
3737 break;
3740 if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3742 tree t = save_expr (expr);
3743 expr = (build_binary_op
3744 (EXPR_LOCATION (expr),
3745 (TREE_SIDE_EFFECTS (expr)
3746 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3747 c_common_truthvalue_conversion
3748 (location,
3749 build_unary_op (location, REALPART_EXPR, t, false)),
3750 c_common_truthvalue_conversion
3751 (location,
3752 build_unary_op (location, IMAGPART_EXPR, t, false)),
3753 false));
3754 goto ret;
3757 if (FIXED_POINT_TYPE_P (TREE_TYPE (expr)))
3759 tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3760 FCONST0 (TYPE_MODE
3761 (TREE_TYPE (expr))));
3762 return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3764 else
3765 return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3767 ret:
3768 protected_set_expr_location (expr, location);
3769 return expr;
3772 static void def_builtin_1 (enum built_in_function fncode,
3773 const char *name,
3774 enum built_in_class fnclass,
3775 tree fntype, tree libtype,
3776 bool both_p, bool fallback_p, bool nonansi_p,
3777 tree fnattrs, bool implicit_p);
3780 /* Apply the TYPE_QUALS to the new DECL. */
3782 void
3783 c_apply_type_quals_to_decl (int type_quals, tree decl)
3785 tree type = TREE_TYPE (decl);
3787 if (type == error_mark_node)
3788 return;
3790 if ((type_quals & TYPE_QUAL_CONST)
3791 || (type && TREE_CODE (type) == REFERENCE_TYPE))
3792 /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3793 constructor can produce constant init, so rely on cp_finish_decl to
3794 clear TREE_READONLY if the variable has non-constant init. */
3795 TREE_READONLY (decl) = 1;
3796 if (type_quals & TYPE_QUAL_VOLATILE)
3798 TREE_SIDE_EFFECTS (decl) = 1;
3799 TREE_THIS_VOLATILE (decl) = 1;
3801 if (type_quals & TYPE_QUAL_RESTRICT)
3803 while (type && TREE_CODE (type) == ARRAY_TYPE)
3804 /* Allow 'restrict' on arrays of pointers.
3805 FIXME currently we just ignore it. */
3806 type = TREE_TYPE (type);
3807 if (!type
3808 || !POINTER_TYPE_P (type)
3809 || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3810 error ("invalid use of %<restrict%>");
3814 /* Return the typed-based alias set for T, which may be an expression
3815 or a type. Return -1 if we don't do anything special. */
3817 alias_set_type
3818 c_common_get_alias_set (tree t)
3820 /* For VLAs, use the alias set of the element type rather than the
3821 default of alias set 0 for types compared structurally. */
3822 if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3824 if (TREE_CODE (t) == ARRAY_TYPE)
3825 return get_alias_set (TREE_TYPE (t));
3826 return -1;
3829 /* That's all the expressions we handle specially. */
3830 if (!TYPE_P (t))
3831 return -1;
3833 /* Unlike char, char8_t doesn't alias in C++. (In C, char8_t is not
3834 a distinct type.) */
3835 if (flag_char8_t && t == char8_type_node && c_dialect_cxx ())
3836 return -1;
3838 /* The C standard guarantees that any object may be accessed via an
3839 lvalue that has narrow character type. */
3840 if (t == char_type_node
3841 || t == signed_char_type_node
3842 || t == unsigned_char_type_node)
3843 return 0;
3845 /* The C standard specifically allows aliasing between signed and
3846 unsigned variants of the same type. We treat the signed
3847 variant as canonical. */
3848 if ((TREE_CODE (t) == INTEGER_TYPE || TREE_CODE (t) == BITINT_TYPE)
3849 && TYPE_UNSIGNED (t))
3851 tree t1 = c_common_signed_type (t);
3853 /* t1 == t can happen for boolean nodes which are always unsigned. */
3854 if (t1 != t)
3855 return get_alias_set (t1);
3858 return -1;
3861 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3862 the IS_SIZEOF parameter indicates which operator is being applied.
3863 The COMPLAIN flag controls whether we should diagnose possibly
3864 ill-formed constructs or not. LOC is the location of the SIZEOF or
3865 TYPEOF operator. If MIN_ALIGNOF, the least alignment required for
3866 a type in any context should be returned, rather than the normal
3867 alignment for that type. */
3869 tree
3870 c_sizeof_or_alignof_type (location_t loc,
3871 tree type, bool is_sizeof, bool min_alignof,
3872 int complain)
3874 const char *op_name;
3875 tree value = NULL;
3876 enum tree_code type_code = TREE_CODE (type);
3878 op_name = is_sizeof ? "sizeof" : "__alignof__";
3880 if (type_code == FUNCTION_TYPE)
3882 if (is_sizeof)
3884 if (complain && warn_pointer_arith)
3885 pedwarn (loc, OPT_Wpointer_arith,
3886 "invalid application of %<sizeof%> to a function type");
3887 else if (!complain)
3888 return error_mark_node;
3889 value = size_one_node;
3891 else
3893 if (complain)
3895 if (c_dialect_cxx ())
3896 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3897 "%<alignof%> applied to a function type");
3898 else
3899 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3900 "%<_Alignof%> applied to a function type");
3902 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3905 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3907 if (type_code == VOID_TYPE
3908 && complain && warn_pointer_arith)
3909 pedwarn (loc, OPT_Wpointer_arith,
3910 "invalid application of %qs to a void type", op_name);
3911 else if (!complain)
3912 return error_mark_node;
3913 value = size_one_node;
3915 else if (!COMPLETE_TYPE_P (type)
3916 && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3918 if (complain)
3919 error_at (loc, "invalid application of %qs to incomplete type %qT",
3920 op_name, type);
3921 return error_mark_node;
3923 else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3924 && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3926 if (complain)
3927 error_at (loc, "invalid application of %qs to array type %qT of "
3928 "incomplete element type", op_name, type);
3929 return error_mark_node;
3931 else if (!verify_type_context (loc, is_sizeof ? TCTX_SIZEOF : TCTX_ALIGNOF,
3932 type, !complain))
3934 if (!complain)
3935 return error_mark_node;
3936 value = size_one_node;
3938 else
3940 if (is_sizeof)
3941 /* Convert in case a char is more than one unit. */
3942 value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3943 size_int (TYPE_PRECISION (char_type_node)
3944 / BITS_PER_UNIT));
3945 else if (min_alignof)
3946 value = size_int (min_align_of_type (type));
3947 else
3948 value = size_int (TYPE_ALIGN_UNIT (type));
3951 /* VALUE will have the middle-end integer type sizetype.
3952 However, we should really return a value of type `size_t',
3953 which is just a typedef for an ordinary integer type. */
3954 value = fold_convert_loc (loc, size_type_node, value);
3956 return value;
3959 /* Implement the __alignof keyword: Return the minimum required
3960 alignment of EXPR, measured in bytes. For VAR_DECLs,
3961 FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3962 from an "aligned" __attribute__ specification). LOC is the
3963 location of the ALIGNOF operator. */
3965 tree
3966 c_alignof_expr (location_t loc, tree expr)
3968 tree t;
3970 if (!verify_type_context (loc, TCTX_ALIGNOF, TREE_TYPE (expr)))
3971 t = size_one_node;
3973 else if (VAR_OR_FUNCTION_DECL_P (expr))
3974 t = size_int (DECL_ALIGN_UNIT (expr));
3976 else if (TREE_CODE (expr) == COMPONENT_REF
3977 && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3979 error_at (loc, "%<__alignof%> applied to a bit-field");
3980 t = size_one_node;
3982 else if (TREE_CODE (expr) == COMPONENT_REF
3983 && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3984 t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3986 else if (INDIRECT_REF_P (expr))
3988 tree t = TREE_OPERAND (expr, 0);
3989 tree best = t;
3990 int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3992 while (CONVERT_EXPR_P (t)
3993 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3995 int thisalign;
3997 t = TREE_OPERAND (t, 0);
3998 thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3999 if (thisalign > bestalign)
4000 best = t, bestalign = thisalign;
4002 return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
4004 else
4005 return c_alignof (loc, TREE_TYPE (expr));
4007 return fold_convert_loc (loc, size_type_node, t);
4010 /* Handle C and C++ default attributes. */
4012 enum built_in_attribute
4014 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
4015 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
4016 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
4017 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
4018 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
4019 #include "builtin-attrs.def"
4020 #undef DEF_ATTR_NULL_TREE
4021 #undef DEF_ATTR_INT
4022 #undef DEF_ATTR_STRING
4023 #undef DEF_ATTR_IDENT
4024 #undef DEF_ATTR_TREE_LIST
4025 ATTR_LAST
4028 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
4030 static void c_init_attributes (void);
4032 enum c_builtin_type
4034 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
4035 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
4036 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
4037 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
4038 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4039 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4040 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
4041 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4042 ARG6) NAME,
4043 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4044 ARG6, ARG7) NAME,
4045 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4046 ARG6, ARG7, ARG8) NAME,
4047 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4048 ARG6, ARG7, ARG8, ARG9) NAME,
4049 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4050 ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
4051 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4052 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
4053 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
4054 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
4055 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
4056 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4057 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4058 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4059 NAME,
4060 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4061 ARG6) NAME,
4062 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4063 ARG6, ARG7) NAME,
4064 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
4065 #include "builtin-types.def"
4066 #undef DEF_PRIMITIVE_TYPE
4067 #undef DEF_FUNCTION_TYPE_0
4068 #undef DEF_FUNCTION_TYPE_1
4069 #undef DEF_FUNCTION_TYPE_2
4070 #undef DEF_FUNCTION_TYPE_3
4071 #undef DEF_FUNCTION_TYPE_4
4072 #undef DEF_FUNCTION_TYPE_5
4073 #undef DEF_FUNCTION_TYPE_6
4074 #undef DEF_FUNCTION_TYPE_7
4075 #undef DEF_FUNCTION_TYPE_8
4076 #undef DEF_FUNCTION_TYPE_9
4077 #undef DEF_FUNCTION_TYPE_10
4078 #undef DEF_FUNCTION_TYPE_11
4079 #undef DEF_FUNCTION_TYPE_VAR_0
4080 #undef DEF_FUNCTION_TYPE_VAR_1
4081 #undef DEF_FUNCTION_TYPE_VAR_2
4082 #undef DEF_FUNCTION_TYPE_VAR_3
4083 #undef DEF_FUNCTION_TYPE_VAR_4
4084 #undef DEF_FUNCTION_TYPE_VAR_5
4085 #undef DEF_FUNCTION_TYPE_VAR_6
4086 #undef DEF_FUNCTION_TYPE_VAR_7
4087 #undef DEF_POINTER_TYPE
4088 BT_LAST
4091 typedef enum c_builtin_type builtin_type;
4093 /* A temporary array for c_common_nodes_and_builtins. Used in
4094 communication with def_fn_type. */
4095 static tree builtin_types[(int) BT_LAST + 1];
4097 /* A helper function for c_common_nodes_and_builtins. Build function type
4098 for DEF with return type RET and N arguments. If VAR is true, then the
4099 function should be variadic after those N arguments, or, if N is zero,
4100 unprototyped.
4102 Takes special care not to ICE if any of the types involved are
4103 error_mark_node, which indicates that said type is not in fact available
4104 (see builtin_type_for_size). In which case the function type as a whole
4105 should be error_mark_node. */
4107 static void
4108 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
4110 tree t;
4111 tree *args = XALLOCAVEC (tree, n);
4112 va_list list;
4113 int i;
4115 va_start (list, n);
4116 for (i = 0; i < n; ++i)
4118 builtin_type a = (builtin_type) va_arg (list, int);
4119 t = builtin_types[a];
4120 if (t == error_mark_node)
4121 goto egress;
4122 args[i] = t;
4125 t = builtin_types[ret];
4126 if (t == error_mark_node)
4127 goto egress;
4128 if (var)
4129 if (n == 0)
4130 t = build_function_type (t, NULL_TREE);
4131 else
4132 t = build_varargs_function_type_array (t, n, args);
4133 else
4134 t = build_function_type_array (t, n, args);
4136 egress:
4137 builtin_types[def] = t;
4138 va_end (list);
4141 /* Build builtin functions common to both C and C++ language
4142 frontends. */
4144 static void
4145 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
4147 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
4148 builtin_types[ENUM] = VALUE;
4149 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
4150 def_fn_type (ENUM, RETURN, 0, 0);
4151 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
4152 def_fn_type (ENUM, RETURN, 0, 1, ARG1);
4153 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
4154 def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
4155 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4156 def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
4157 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4158 def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
4159 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4160 def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4161 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4162 ARG6) \
4163 def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4164 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4165 ARG6, ARG7) \
4166 def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4167 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4168 ARG6, ARG7, ARG8) \
4169 def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4170 ARG7, ARG8);
4171 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4172 ARG6, ARG7, ARG8, ARG9) \
4173 def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4174 ARG7, ARG8, ARG9);
4175 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4176 ARG6, ARG7, ARG8, ARG9, ARG10) \
4177 def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4178 ARG7, ARG8, ARG9, ARG10);
4179 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4180 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
4181 def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
4182 ARG7, ARG8, ARG9, ARG10, ARG11);
4183 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
4184 def_fn_type (ENUM, RETURN, 1, 0);
4185 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
4186 def_fn_type (ENUM, RETURN, 1, 1, ARG1);
4187 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
4188 def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
4189 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4190 def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
4191 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4192 def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
4193 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4194 def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4195 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4196 ARG6) \
4197 def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4198 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4199 ARG6, ARG7) \
4200 def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4201 #define DEF_POINTER_TYPE(ENUM, TYPE) \
4202 builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
4204 #include "builtin-types.def"
4206 #undef DEF_PRIMITIVE_TYPE
4207 #undef DEF_FUNCTION_TYPE_0
4208 #undef DEF_FUNCTION_TYPE_1
4209 #undef DEF_FUNCTION_TYPE_2
4210 #undef DEF_FUNCTION_TYPE_3
4211 #undef DEF_FUNCTION_TYPE_4
4212 #undef DEF_FUNCTION_TYPE_5
4213 #undef DEF_FUNCTION_TYPE_6
4214 #undef DEF_FUNCTION_TYPE_7
4215 #undef DEF_FUNCTION_TYPE_8
4216 #undef DEF_FUNCTION_TYPE_9
4217 #undef DEF_FUNCTION_TYPE_10
4218 #undef DEF_FUNCTION_TYPE_11
4219 #undef DEF_FUNCTION_TYPE_VAR_0
4220 #undef DEF_FUNCTION_TYPE_VAR_1
4221 #undef DEF_FUNCTION_TYPE_VAR_2
4222 #undef DEF_FUNCTION_TYPE_VAR_3
4223 #undef DEF_FUNCTION_TYPE_VAR_4
4224 #undef DEF_FUNCTION_TYPE_VAR_5
4225 #undef DEF_FUNCTION_TYPE_VAR_6
4226 #undef DEF_FUNCTION_TYPE_VAR_7
4227 #undef DEF_POINTER_TYPE
4228 builtin_types[(int) BT_LAST] = NULL_TREE;
4230 c_init_attributes ();
4232 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
4233 NONANSI_P, ATTRS, IMPLICIT, COND) \
4234 if (NAME && COND) \
4235 def_builtin_1 (ENUM, NAME, CLASS, \
4236 builtin_types[(int) TYPE], \
4237 builtin_types[(int) LIBTYPE], \
4238 BOTH_P, FALLBACK_P, NONANSI_P, \
4239 built_in_attributes[(int) ATTRS], IMPLICIT);
4240 #include "builtins.def"
4242 targetm.init_builtins ();
4244 build_common_builtin_nodes ();
4247 /* Like get_identifier, but avoid warnings about null arguments when
4248 the argument may be NULL for targets where GCC lacks stdint.h type
4249 information. */
4251 static inline tree
4252 c_get_ident (const char *id)
4254 return get_identifier (id);
4257 /* Build tree nodes and builtin functions common to both C and C++ language
4258 frontends. */
4260 void
4261 c_common_nodes_and_builtins (void)
4263 int char8_type_size;
4264 int char16_type_size;
4265 int char32_type_size;
4266 int wchar_type_size;
4267 tree array_domain_type;
4268 tree va_list_ref_type_node;
4269 tree va_list_arg_type_node;
4270 int i;
4272 build_common_tree_nodes (flag_signed_char);
4274 /* Define `int' and `char' first so that dbx will output them first. */
4275 record_builtin_type (RID_INT, NULL, integer_type_node);
4276 record_builtin_type (RID_CHAR, "char", char_type_node);
4278 /* `signed' is the same as `int'. FIXME: the declarations of "signed",
4279 "unsigned long", "long long unsigned" and "unsigned short" were in C++
4280 but not C. Are the conditionals here needed? */
4281 if (c_dialect_cxx ())
4282 record_builtin_type (RID_SIGNED, NULL, integer_type_node);
4283 record_builtin_type (RID_LONG, "long int", long_integer_type_node);
4284 record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
4285 record_builtin_type (RID_MAX, "long unsigned int",
4286 long_unsigned_type_node);
4288 for (i = 0; i < NUM_INT_N_ENTS; i ++)
4290 char name[25];
4292 sprintf (name, "__int%d", int_n_data[i].bitsize);
4293 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4294 int_n_trees[i].signed_type);
4295 sprintf (name, "__int%d__", int_n_data[i].bitsize);
4296 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4297 int_n_trees[i].signed_type);
4298 ridpointers[RID_FIRST_INT_N + i]
4299 = DECL_NAME (TYPE_NAME (int_n_trees[i].signed_type));
4301 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
4302 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4303 sprintf (name, "__int%d__ unsigned", int_n_data[i].bitsize);
4304 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4307 if (c_dialect_cxx ())
4308 record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
4309 record_builtin_type (RID_MAX, "long long int",
4310 long_long_integer_type_node);
4311 record_builtin_type (RID_MAX, "long long unsigned int",
4312 long_long_unsigned_type_node);
4313 if (c_dialect_cxx ())
4314 record_builtin_type (RID_MAX, "long long unsigned",
4315 long_long_unsigned_type_node);
4316 record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4317 record_builtin_type (RID_MAX, "short unsigned int",
4318 short_unsigned_type_node);
4319 if (c_dialect_cxx ())
4320 record_builtin_type (RID_MAX, "unsigned short",
4321 short_unsigned_type_node);
4323 /* Define both `signed char' and `unsigned char'. */
4324 record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4325 record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4327 /* These are types that c_common_type_for_size and
4328 c_common_type_for_mode use. */
4329 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4330 TYPE_DECL, NULL_TREE,
4331 intQI_type_node));
4332 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4333 TYPE_DECL, NULL_TREE,
4334 intHI_type_node));
4335 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4336 TYPE_DECL, NULL_TREE,
4337 intSI_type_node));
4338 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4339 TYPE_DECL, NULL_TREE,
4340 intDI_type_node));
4341 #if HOST_BITS_PER_WIDE_INT >= 64
4342 /* Note that this is different than the __int128 type that's part of
4343 the generic __intN support. */
4344 if (targetm.scalar_mode_supported_p (TImode))
4345 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4346 TYPE_DECL,
4347 get_identifier ("__int128_t"),
4348 intTI_type_node));
4349 #endif
4350 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4351 TYPE_DECL, NULL_TREE,
4352 unsigned_intQI_type_node));
4353 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4354 TYPE_DECL, NULL_TREE,
4355 unsigned_intHI_type_node));
4356 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4357 TYPE_DECL, NULL_TREE,
4358 unsigned_intSI_type_node));
4359 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4360 TYPE_DECL, NULL_TREE,
4361 unsigned_intDI_type_node));
4362 #if HOST_BITS_PER_WIDE_INT >= 64
4363 if (targetm.scalar_mode_supported_p (TImode))
4364 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4365 TYPE_DECL,
4366 get_identifier ("__uint128_t"),
4367 unsigned_intTI_type_node));
4368 #endif
4370 /* Create the widest literal types. */
4371 if (targetm.scalar_mode_supported_p (TImode))
4373 widest_integer_literal_type_node = intTI_type_node;
4374 widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4376 else
4378 widest_integer_literal_type_node = intDI_type_node;
4379 widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4382 signed_size_type_node = c_common_signed_type (size_type_node);
4384 pid_type_node =
4385 TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4387 record_builtin_type (RID_FLOAT, NULL, float_type_node);
4388 record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4389 record_builtin_type (RID_MAX, "long double", long_double_type_node);
4391 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4393 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4394 record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4395 FLOATN_NX_TYPE_NODE (i));
4398 /* For C, let float128t_type_node (__float128 in some backends) be the
4399 same type as float128_type_node (_Float128), for C++ let those
4400 be distinct types that mangle and behave differently. */
4401 if (c_dialect_cxx ())
4402 float128t_type_node = NULL_TREE;
4404 /* Only supported decimal floating point extension if the target
4405 actually supports underlying modes. */
4406 if (targetm.scalar_mode_supported_p (SDmode)
4407 && targetm.scalar_mode_supported_p (DDmode)
4408 && targetm.scalar_mode_supported_p (TDmode))
4410 record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4411 record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4412 record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4415 if (targetm.fixed_point_supported_p ())
4417 record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4418 record_builtin_type (RID_FRACT, NULL, fract_type_node);
4419 record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4420 record_builtin_type (RID_MAX, "long long _Fract",
4421 long_long_fract_type_node);
4422 record_builtin_type (RID_MAX, "unsigned short _Fract",
4423 unsigned_short_fract_type_node);
4424 record_builtin_type (RID_MAX, "unsigned _Fract",
4425 unsigned_fract_type_node);
4426 record_builtin_type (RID_MAX, "unsigned long _Fract",
4427 unsigned_long_fract_type_node);
4428 record_builtin_type (RID_MAX, "unsigned long long _Fract",
4429 unsigned_long_long_fract_type_node);
4430 record_builtin_type (RID_MAX, "_Sat short _Fract",
4431 sat_short_fract_type_node);
4432 record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4433 record_builtin_type (RID_MAX, "_Sat long _Fract",
4434 sat_long_fract_type_node);
4435 record_builtin_type (RID_MAX, "_Sat long long _Fract",
4436 sat_long_long_fract_type_node);
4437 record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4438 sat_unsigned_short_fract_type_node);
4439 record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4440 sat_unsigned_fract_type_node);
4441 record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4442 sat_unsigned_long_fract_type_node);
4443 record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4444 sat_unsigned_long_long_fract_type_node);
4445 record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4446 record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4447 record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4448 record_builtin_type (RID_MAX, "long long _Accum",
4449 long_long_accum_type_node);
4450 record_builtin_type (RID_MAX, "unsigned short _Accum",
4451 unsigned_short_accum_type_node);
4452 record_builtin_type (RID_MAX, "unsigned _Accum",
4453 unsigned_accum_type_node);
4454 record_builtin_type (RID_MAX, "unsigned long _Accum",
4455 unsigned_long_accum_type_node);
4456 record_builtin_type (RID_MAX, "unsigned long long _Accum",
4457 unsigned_long_long_accum_type_node);
4458 record_builtin_type (RID_MAX, "_Sat short _Accum",
4459 sat_short_accum_type_node);
4460 record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4461 record_builtin_type (RID_MAX, "_Sat long _Accum",
4462 sat_long_accum_type_node);
4463 record_builtin_type (RID_MAX, "_Sat long long _Accum",
4464 sat_long_long_accum_type_node);
4465 record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4466 sat_unsigned_short_accum_type_node);
4467 record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4468 sat_unsigned_accum_type_node);
4469 record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4470 sat_unsigned_long_accum_type_node);
4471 record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4472 sat_unsigned_long_long_accum_type_node);
4476 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4477 TYPE_DECL,
4478 get_identifier ("complex int"),
4479 complex_integer_type_node));
4480 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4481 TYPE_DECL,
4482 get_identifier ("complex float"),
4483 complex_float_type_node));
4484 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4485 TYPE_DECL,
4486 get_identifier ("complex double"),
4487 complex_double_type_node));
4488 lang_hooks.decls.pushdecl
4489 (build_decl (UNKNOWN_LOCATION,
4490 TYPE_DECL, get_identifier ("complex long double"),
4491 complex_long_double_type_node));
4493 if (!c_dialect_cxx ())
4494 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4495 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4497 char buf[30];
4498 sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4499 floatn_nx_types[i].extended ? "x" : "");
4500 lang_hooks.decls.pushdecl
4501 (build_decl (UNKNOWN_LOCATION,
4502 TYPE_DECL,
4503 get_identifier (buf),
4504 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4507 /* Make fileptr_type_node a distinct void * type until
4508 FILE type is defined. Likewise for const struct tm*. */
4509 for (unsigned i = 0; i < ARRAY_SIZE (builtin_structptr_types); ++i)
4510 builtin_structptr_types[i].node
4511 = build_variant_type_copy (builtin_structptr_types[i].base);
4513 record_builtin_type (RID_VOID, NULL, void_type_node);
4515 /* Set the TYPE_NAME for any variants that were built before
4516 record_builtin_type gave names to the built-in types. */
4518 tree void_name = TYPE_NAME (void_type_node);
4519 TYPE_NAME (void_type_node) = NULL_TREE;
4520 TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4521 = void_name;
4522 TYPE_NAME (void_type_node) = void_name;
4525 /* Make a type to be the domain of a few array types
4526 whose domains don't really matter.
4527 200 is small enough that it always fits in size_t
4528 and large enough that it can hold most function names for the
4529 initializations of __FUNCTION__ and __PRETTY_FUNCTION__. */
4530 array_domain_type = build_index_type (size_int (200));
4532 /* Make a type for arrays of characters.
4533 With luck nothing will ever really depend on the length of this
4534 array type. */
4535 char_array_type_node
4536 = build_array_type (char_type_node, array_domain_type);
4538 string_type_node = build_pointer_type (char_type_node);
4539 const_string_type_node
4540 = build_pointer_type (build_qualified_type
4541 (char_type_node, TYPE_QUAL_CONST));
4543 /* This is special for C++ so functions can be overloaded. */
4544 wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4545 wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4546 wchar_type_size = TYPE_PRECISION (wchar_type_node);
4547 underlying_wchar_type_node = wchar_type_node;
4548 if (c_dialect_cxx ())
4550 if (TYPE_UNSIGNED (wchar_type_node))
4551 wchar_type_node = make_unsigned_type (wchar_type_size);
4552 else
4553 wchar_type_node = make_signed_type (wchar_type_size);
4554 record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4557 /* This is for wide string constants. */
4558 wchar_array_type_node
4559 = build_array_type (wchar_type_node, array_domain_type);
4561 /* Define 'char8_t'. */
4562 char8_type_node = get_identifier (CHAR8_TYPE);
4563 char8_type_node = TREE_TYPE (identifier_global_value (char8_type_node));
4564 char8_type_size = TYPE_PRECISION (char8_type_node);
4565 if (c_dialect_cxx ())
4567 char8_type_node = make_unsigned_type (char8_type_size);
4568 TYPE_STRING_FLAG (char8_type_node) = true;
4570 if (flag_char8_t)
4571 record_builtin_type (RID_CHAR8, "char8_t", char8_type_node);
4574 /* This is for UTF-8 string constants. */
4575 char8_array_type_node
4576 = build_array_type (char8_type_node, array_domain_type);
4578 /* Define 'char16_t'. */
4579 char16_type_node = get_identifier (CHAR16_TYPE);
4580 char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4581 char16_type_size = TYPE_PRECISION (char16_type_node);
4582 if (c_dialect_cxx ())
4584 char16_type_node = make_unsigned_type (char16_type_size);
4586 if (cxx_dialect >= cxx11)
4587 record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4590 /* This is for UTF-16 string constants. */
4591 char16_array_type_node
4592 = build_array_type (char16_type_node, array_domain_type);
4594 /* Define 'char32_t'. */
4595 char32_type_node = get_identifier (CHAR32_TYPE);
4596 char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4597 char32_type_size = TYPE_PRECISION (char32_type_node);
4598 if (c_dialect_cxx ())
4600 char32_type_node = make_unsigned_type (char32_type_size);
4602 if (cxx_dialect >= cxx11)
4603 record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4606 /* This is for UTF-32 string constants. */
4607 char32_array_type_node
4608 = build_array_type (char32_type_node, array_domain_type);
4610 if (strcmp (WINT_TYPE, "wchar_t") == 0)
4611 wint_type_node = wchar_type_node;
4612 else
4613 wint_type_node =
4614 TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4616 intmax_type_node =
4617 TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4618 uintmax_type_node =
4619 TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4621 if (SIG_ATOMIC_TYPE)
4622 sig_atomic_type_node =
4623 TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4624 if (INT8_TYPE)
4625 int8_type_node =
4626 TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4627 if (INT16_TYPE)
4628 int16_type_node =
4629 TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4630 if (INT32_TYPE)
4631 int32_type_node =
4632 TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4633 if (INT64_TYPE)
4634 int64_type_node =
4635 TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4636 if (UINT8_TYPE)
4637 uint8_type_node =
4638 TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4639 if (UINT16_TYPE)
4640 c_uint16_type_node = uint16_type_node =
4641 TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4642 if (UINT32_TYPE)
4643 c_uint32_type_node = uint32_type_node =
4644 TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4645 if (UINT64_TYPE)
4646 c_uint64_type_node = uint64_type_node =
4647 TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4648 if (INT_LEAST8_TYPE)
4649 int_least8_type_node =
4650 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4651 if (INT_LEAST16_TYPE)
4652 int_least16_type_node =
4653 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4654 if (INT_LEAST32_TYPE)
4655 int_least32_type_node =
4656 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4657 if (INT_LEAST64_TYPE)
4658 int_least64_type_node =
4659 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4660 if (UINT_LEAST8_TYPE)
4661 uint_least8_type_node =
4662 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4663 if (UINT_LEAST16_TYPE)
4664 uint_least16_type_node =
4665 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4666 if (UINT_LEAST32_TYPE)
4667 uint_least32_type_node =
4668 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4669 if (UINT_LEAST64_TYPE)
4670 uint_least64_type_node =
4671 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4672 if (INT_FAST8_TYPE)
4673 int_fast8_type_node =
4674 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4675 if (INT_FAST16_TYPE)
4676 int_fast16_type_node =
4677 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4678 if (INT_FAST32_TYPE)
4679 int_fast32_type_node =
4680 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4681 if (INT_FAST64_TYPE)
4682 int_fast64_type_node =
4683 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4684 if (UINT_FAST8_TYPE)
4685 uint_fast8_type_node =
4686 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4687 if (UINT_FAST16_TYPE)
4688 uint_fast16_type_node =
4689 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4690 if (UINT_FAST32_TYPE)
4691 uint_fast32_type_node =
4692 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4693 if (UINT_FAST64_TYPE)
4694 uint_fast64_type_node =
4695 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4696 if (INTPTR_TYPE)
4697 intptr_type_node =
4698 TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4699 if (UINTPTR_TYPE)
4700 uintptr_type_node =
4701 TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4703 default_function_type = build_function_type (integer_type_node, NULL_TREE);
4704 unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4706 lang_hooks.decls.pushdecl
4707 (build_decl (UNKNOWN_LOCATION,
4708 TYPE_DECL, get_identifier ("__builtin_va_list"),
4709 va_list_type_node));
4710 if (targetm.enum_va_list_p)
4712 int l;
4713 const char *pname;
4714 tree ptype;
4716 for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4718 lang_hooks.decls.pushdecl
4719 (build_decl (UNKNOWN_LOCATION,
4720 TYPE_DECL, get_identifier (pname),
4721 ptype));
4726 if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4728 va_list_arg_type_node = va_list_ref_type_node =
4729 build_pointer_type (TREE_TYPE (va_list_type_node));
4731 else
4733 va_list_arg_type_node = va_list_type_node;
4734 va_list_ref_type_node = build_reference_type (va_list_type_node);
4737 c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4739 main_identifier_node = get_identifier ("main");
4741 /* Create the built-in __null node. It is important that this is
4742 not shared. */
4743 null_node = make_int_cst (1, 1);
4744 TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4746 /* Create the built-in nullptr node. This part of its initialization is
4747 common to C and C++. The front ends can further adjust its definition
4748 in {c,cxx}_init_decl_processing. In particular, we aren't setting the
4749 alignment here for C++ backward ABI bug compatibility. */
4750 nullptr_type_node = make_node (NULLPTR_TYPE);
4751 TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4752 TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4753 TYPE_UNSIGNED (nullptr_type_node) = 1;
4754 TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4755 SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4756 nullptr_node = build_int_cst (nullptr_type_node, 0);
4758 /* Since builtin_types isn't gc'ed, don't export these nodes. */
4759 memset (builtin_types, 0, sizeof (builtin_types));
4762 /* The number of named compound-literals generated thus far. */
4763 static GTY(()) int compound_literal_number;
4765 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal. */
4767 void
4768 set_compound_literal_name (tree decl)
4770 char *name;
4771 ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4772 compound_literal_number);
4773 compound_literal_number++;
4774 DECL_NAME (decl) = get_identifier (name);
4777 /* build_va_arg helper function. Return a VA_ARG_EXPR with location LOC, type
4778 TYPE and operand OP. */
4780 static tree
4781 build_va_arg_1 (location_t loc, tree type, tree op)
4783 tree expr = build1 (VA_ARG_EXPR, type, op);
4784 SET_EXPR_LOCATION (expr, loc);
4785 return expr;
4788 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4789 va_arg (EXPR, TYPE) at source location LOC. */
4791 tree
4792 build_va_arg (location_t loc, tree expr, tree type)
4794 tree va_type = TREE_TYPE (expr);
4795 tree canon_va_type = (va_type == error_mark_node
4796 ? error_mark_node
4797 : targetm.canonical_va_list_type (va_type));
4799 if (va_type == error_mark_node
4800 || canon_va_type == NULL_TREE)
4802 if (canon_va_type == NULL_TREE)
4803 error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4805 /* Let's handle things neutrally, if expr:
4806 - has undeclared type, or
4807 - is not an va_list type. */
4808 return build_va_arg_1 (loc, type, error_mark_node);
4811 if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4813 /* Case 1: Not an array type. */
4815 /* Take the address, to get '&ap'. Note that &ap is not a va_list
4816 type. */
4817 c_common_mark_addressable_vec (expr);
4818 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4820 return build_va_arg_1 (loc, type, expr);
4823 /* Case 2: Array type.
4825 Background:
4827 For contrast, let's start with the simple case (case 1). If
4828 canon_va_type is not an array type, but say a char *, then when
4829 passing-by-value a va_list, the type of the va_list param decl is
4830 the same as for another va_list decl (all ap's are char *):
4832 f2_1 (char * ap)
4833 D.1815 = VA_ARG (&ap, 0B, 1);
4834 return D.1815;
4836 f2 (int i)
4837 char * ap.0;
4838 char * ap;
4839 __builtin_va_start (&ap, 0);
4840 ap.0 = ap;
4841 res = f2_1 (ap.0);
4842 __builtin_va_end (&ap);
4843 D.1812 = res;
4844 return D.1812;
4846 However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4847 va_list the type of the va_list param decl (case 2b, struct * ap) is not
4848 the same as for another va_list decl (case 2a, struct ap[1]).
4850 f2_1 (struct * ap)
4851 D.1844 = VA_ARG (ap, 0B, 0);
4852 return D.1844;
4854 f2 (int i)
4855 struct ap[1];
4856 __builtin_va_start (&ap, 0);
4857 res = f2_1 (&ap);
4858 __builtin_va_end (&ap);
4859 D.1841 = res;
4860 return D.1841;
4862 Case 2b is different because:
4863 - on the callee side, the parm decl has declared type va_list, but
4864 grokdeclarator changes the type of the parm decl to a pointer to the
4865 array elem type.
4866 - on the caller side, the pass-by-value uses &ap.
4868 We unify these two cases (case 2a: va_list is array type,
4869 case 2b: va_list is pointer to array elem type), by adding '&' for the
4870 array type case, such that we have a pointer to array elem in both
4871 cases. */
4873 if (TREE_CODE (va_type) == ARRAY_TYPE)
4875 /* Case 2a: va_list is array type. */
4877 /* Take the address, to get '&ap'. Make sure it's a pointer to array
4878 elem type. */
4879 c_common_mark_addressable_vec (expr);
4880 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4881 expr);
4883 /* Verify that &ap is still recognized as having va_list type. */
4884 tree canon_expr_type
4885 = targetm.canonical_va_list_type (TREE_TYPE (expr));
4886 gcc_assert (canon_expr_type != NULL_TREE);
4888 else
4890 /* Case 2b: va_list is pointer to array elem type. */
4891 gcc_assert (POINTER_TYPE_P (va_type));
4893 /* Comparison as in std_canonical_va_list_type. */
4894 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4895 == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4897 /* Don't take the address. We've already got '&ap'. */
4901 return build_va_arg_1 (loc, type, expr);
4905 /* Linked list of disabled built-in functions. */
4907 struct disabled_builtin
4909 const char *name;
4910 struct disabled_builtin *next;
4912 static disabled_builtin *disabled_builtins = NULL;
4914 static bool builtin_function_disabled_p (const char *);
4916 /* Disable a built-in function specified by -fno-builtin-NAME. If NAME
4917 begins with "__builtin_", give an error. */
4919 void
4920 disable_builtin_function (const char *name)
4922 if (startswith (name, "__builtin_"))
4923 error ("cannot disable built-in function %qs", name);
4924 else
4926 disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4927 new_disabled_builtin->name = name;
4928 new_disabled_builtin->next = disabled_builtins;
4929 disabled_builtins = new_disabled_builtin;
4934 /* Return true if the built-in function NAME has been disabled, false
4935 otherwise. */
4937 static bool
4938 builtin_function_disabled_p (const char *name)
4940 disabled_builtin *p;
4941 for (p = disabled_builtins; p != NULL; p = p->next)
4943 if (strcmp (name, p->name) == 0)
4944 return true;
4946 return false;
4950 /* Worker for DEF_BUILTIN.
4951 Possibly define a builtin function with one or two names.
4952 Does not declare a non-__builtin_ function if flag_no_builtin, or if
4953 nonansi_p and flag_no_nonansi_builtin. */
4955 static void
4956 def_builtin_1 (enum built_in_function fncode,
4957 const char *name,
4958 enum built_in_class fnclass,
4959 tree fntype, tree libtype,
4960 bool both_p, bool fallback_p, bool nonansi_p,
4961 tree fnattrs, bool implicit_p)
4963 tree decl;
4964 const char *libname;
4966 if (fntype == error_mark_node)
4967 return;
4969 gcc_assert ((!both_p && !fallback_p)
4970 || startswith (name, "__builtin_"));
4972 libname = name + strlen ("__builtin_");
4973 decl = add_builtin_function (name, fntype, fncode, fnclass,
4974 (fallback_p ? libname : NULL),
4975 fnattrs);
4977 set_builtin_decl (fncode, decl, implicit_p);
4979 if (both_p
4980 && !flag_no_builtin && !builtin_function_disabled_p (libname)
4981 && !(nonansi_p && flag_no_nonansi_builtin))
4982 add_builtin_function (libname, libtype, fncode, fnclass,
4983 NULL, fnattrs);
4986 /* Nonzero if the type T promotes to int. This is (nearly) the
4987 integral promotions defined in ISO C99 6.3.1.1/2. */
4989 bool
4990 c_promoting_integer_type_p (const_tree t)
4992 switch (TREE_CODE (t))
4994 case INTEGER_TYPE:
4995 return (TYPE_MAIN_VARIANT (t) == char_type_node
4996 || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4997 || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4998 || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4999 || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
5000 || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
5002 case ENUMERAL_TYPE:
5003 /* ??? Technically all enumerations not larger than an int
5004 promote to an int. But this is used along code paths
5005 that only want to notice a size change. */
5006 return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
5008 case BOOLEAN_TYPE:
5009 return true;
5011 default:
5012 return false;
5016 /* Return 1 if PARMS specifies a fixed number of parameters
5017 and none of their types is affected by default promotions. */
5019 bool
5020 self_promoting_args_p (const_tree parms)
5022 const_tree t;
5023 for (t = parms; t; t = TREE_CHAIN (t))
5025 tree type = TREE_VALUE (t);
5027 if (type == error_mark_node)
5028 continue;
5030 if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
5031 return false;
5033 if (type == NULL_TREE)
5034 return false;
5036 if (TYPE_MAIN_VARIANT (type) == float_type_node)
5037 return false;
5039 if (c_promoting_integer_type_p (type))
5040 return false;
5042 return true;
5045 /* Recursively remove any '*' or '&' operator from TYPE. */
5046 tree
5047 strip_pointer_operator (tree t)
5049 while (POINTER_TYPE_P (t))
5050 t = TREE_TYPE (t);
5051 return t;
5054 /* Recursively remove pointer or array type from TYPE. */
5055 tree
5056 strip_pointer_or_array_types (tree t)
5058 while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
5059 t = TREE_TYPE (t);
5060 return t;
5063 /* Used to compare case labels. K1 and K2 are actually tree nodes
5064 representing case labels, or NULL_TREE for a `default' label.
5065 Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
5066 K2, and 0 if K1 and K2 are equal. */
5069 case_compare (splay_tree_key k1, splay_tree_key k2)
5071 /* Consider a NULL key (such as arises with a `default' label) to be
5072 smaller than anything else. */
5073 if (!k1)
5074 return k2 ? -1 : 0;
5075 else if (!k2)
5076 return k1 ? 1 : 0;
5078 return tree_int_cst_compare ((tree) k1, (tree) k2);
5081 /* Process a case label, located at LOC, for the range LOW_VALUE
5082 ... HIGH_VALUE. If LOW_VALUE and HIGH_VALUE are both NULL_TREE
5083 then this case label is actually a `default' label. If only
5084 HIGH_VALUE is NULL_TREE, then case label was declared using the
5085 usual C/C++ syntax, rather than the GNU case range extension.
5086 CASES is a tree containing all the case ranges processed so far;
5087 COND is the condition for the switch-statement itself.
5088 Returns the CASE_LABEL_EXPR created, or ERROR_MARK_NODE if no
5089 CASE_LABEL_EXPR is created. ATTRS are the attributes to be applied
5090 to the label. */
5092 tree
5093 c_add_case_label (location_t loc, splay_tree cases, tree cond,
5094 tree low_value, tree high_value, tree attrs)
5096 tree type;
5097 tree label;
5098 tree case_label;
5099 splay_tree_node node;
5101 /* Create the LABEL_DECL itself. */
5102 label = create_artificial_label (loc);
5103 decl_attributes (&label, attrs, 0);
5105 /* If there was an error processing the switch condition, bail now
5106 before we get more confused. */
5107 if (!cond || cond == error_mark_node)
5108 goto error_out;
5110 if ((low_value && TREE_TYPE (low_value)
5111 && POINTER_TYPE_P (TREE_TYPE (low_value)))
5112 || (high_value && TREE_TYPE (high_value)
5113 && POINTER_TYPE_P (TREE_TYPE (high_value))))
5115 error_at (loc, "pointers are not permitted as case values");
5116 goto error_out;
5119 /* Case ranges are a GNU extension. */
5120 if (high_value)
5121 pedwarn (loc, OPT_Wpedantic,
5122 "range expressions in switch statements are non-standard");
5124 type = TREE_TYPE (cond);
5125 if (low_value)
5127 low_value = check_case_value (loc, low_value);
5128 low_value = convert_and_check (loc, type, low_value);
5129 low_value = fold (low_value);
5130 if (low_value == error_mark_node)
5131 goto error_out;
5133 if (high_value)
5135 high_value = check_case_value (loc, high_value);
5136 high_value = convert_and_check (loc, type, high_value);
5137 high_value = fold (high_value);
5138 if (high_value == error_mark_node)
5139 goto error_out;
5142 if (low_value && high_value)
5144 /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
5145 really a case range, even though it was written that way.
5146 Remove the HIGH_VALUE to simplify later processing. */
5147 if (tree_int_cst_equal (low_value, high_value))
5148 high_value = NULL_TREE;
5149 else if (!tree_int_cst_lt (low_value, high_value))
5150 warning_at (loc, 0, "empty range specified");
5153 /* Look up the LOW_VALUE in the table of case labels we already
5154 have. */
5155 node = splay_tree_lookup (cases, (splay_tree_key) low_value);
5156 /* If there was not an exact match, check for overlapping ranges.
5157 There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
5158 that's a `default' label and the only overlap is an exact match. */
5159 if (!node && (low_value || high_value))
5161 splay_tree_node low_bound;
5162 splay_tree_node high_bound;
5164 /* Even though there wasn't an exact match, there might be an
5165 overlap between this case range and another case range.
5166 Since we've (inductively) not allowed any overlapping case
5167 ranges, we simply need to find the greatest low case label
5168 that is smaller that LOW_VALUE, and the smallest low case
5169 label that is greater than LOW_VALUE. If there is an overlap
5170 it will occur in one of these two ranges. */
5171 low_bound = splay_tree_predecessor (cases,
5172 (splay_tree_key) low_value);
5173 high_bound = splay_tree_successor (cases,
5174 (splay_tree_key) low_value);
5176 /* Check to see if the LOW_BOUND overlaps. It is smaller than
5177 the LOW_VALUE, so there is no need to check unless the
5178 LOW_BOUND is in fact itself a case range. */
5179 if (low_bound
5180 && CASE_HIGH ((tree) low_bound->value)
5181 && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
5182 low_value) >= 0)
5183 node = low_bound;
5184 /* Check to see if the HIGH_BOUND overlaps. The low end of that
5185 range is bigger than the low end of the current range, so we
5186 are only interested if the current range is a real range, and
5187 not an ordinary case label. */
5188 else if (high_bound
5189 && high_value
5190 && (tree_int_cst_compare ((tree) high_bound->key,
5191 high_value)
5192 <= 0))
5193 node = high_bound;
5195 /* If there was an overlap, issue an error. */
5196 if (node)
5198 tree duplicate = CASE_LABEL ((tree) node->value);
5200 if (high_value)
5202 error_at (loc, "duplicate (or overlapping) case value");
5203 inform (DECL_SOURCE_LOCATION (duplicate),
5204 "this is the first entry overlapping that value");
5206 else if (low_value)
5208 error_at (loc, "duplicate case value") ;
5209 inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
5211 else
5213 error_at (loc, "multiple default labels in one switch");
5214 inform (DECL_SOURCE_LOCATION (duplicate),
5215 "this is the first default label");
5217 goto error_out;
5220 /* Add a CASE_LABEL to the statement-tree. */
5221 case_label = add_stmt (build_case_label (low_value, high_value, label));
5222 /* Register this case label in the splay tree. */
5223 splay_tree_insert (cases,
5224 (splay_tree_key) low_value,
5225 (splay_tree_value) case_label);
5227 return case_label;
5229 error_out:
5230 /* Add a label so that the back-end doesn't think that the beginning of
5231 the switch is unreachable. Note that we do not add a case label, as
5232 that just leads to duplicates and thence to failure later on. */
5233 if (!cases->root)
5235 tree t = create_artificial_label (loc);
5236 add_stmt (build_stmt (loc, LABEL_EXPR, t));
5238 return error_mark_node;
5241 /* Subroutine of c_switch_covers_all_cases_p, called via
5242 splay_tree_foreach. Return 1 if it doesn't cover all the cases.
5243 ARGS[0] is initially NULL and after the first iteration is the
5244 so far highest case label. ARGS[1] is the minimum of SWITCH_COND's
5245 type. */
5247 static int
5248 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
5250 tree label = (tree) node->value;
5251 tree *args = (tree *) data;
5253 /* If there is a default case, we shouldn't have called this. */
5254 gcc_assert (CASE_LOW (label));
5256 if (args[0] == NULL_TREE)
5258 if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
5259 return 1;
5261 else if (wi::add (wi::to_widest (args[0]), 1)
5262 != wi::to_widest (CASE_LOW (label)))
5263 return 1;
5264 if (CASE_HIGH (label))
5265 args[0] = CASE_HIGH (label);
5266 else
5267 args[0] = CASE_LOW (label);
5268 return 0;
5271 /* Return true if switch with CASES and switch condition with type
5272 covers all possible values in the case labels. */
5274 bool
5275 c_switch_covers_all_cases_p (splay_tree cases, tree type)
5277 /* If there is default:, this is always the case. */
5278 splay_tree_node default_node
5279 = splay_tree_lookup (cases, (splay_tree_key) NULL);
5280 if (default_node)
5281 return true;
5283 if (!INTEGRAL_TYPE_P (type))
5284 return false;
5286 tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
5287 if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
5288 return false;
5290 /* If there are no cases at all, or if the highest case label
5291 is smaller than TYPE_MAX_VALUE, return false. */
5292 if (args[0] == NULL_TREE
5293 || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
5294 return false;
5296 return true;
5299 /* Return true if stmt can fall through. Used by block_may_fallthru
5300 default case. */
5302 bool
5303 c_block_may_fallthru (const_tree stmt)
5305 switch (TREE_CODE (stmt))
5307 case SWITCH_STMT:
5308 return (!SWITCH_STMT_ALL_CASES_P (stmt)
5309 || !SWITCH_STMT_NO_BREAK_P (stmt)
5310 || block_may_fallthru (SWITCH_STMT_BODY (stmt)));
5312 default:
5313 return true;
5317 /* Finish an expression taking the address of LABEL (an
5318 IDENTIFIER_NODE). Returns an expression for the address.
5320 LOC is the location for the expression returned. */
5322 tree
5323 finish_label_address_expr (tree label, location_t loc)
5325 tree result;
5327 pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
5329 if (label == error_mark_node)
5330 return error_mark_node;
5332 label = lookup_label (label);
5333 if (label == NULL_TREE)
5334 result = null_pointer_node;
5335 else
5337 TREE_USED (label) = 1;
5338 result = build1 (ADDR_EXPR, ptr_type_node, label);
5339 /* The current function is not necessarily uninlinable.
5340 Computed gotos are incompatible with inlining, but the value
5341 here could be used only in a diagnostic, for example. */
5342 protected_set_expr_location (result, loc);
5345 return result;
5349 /* Given a boolean expression ARG, return a tree representing an increment
5350 or decrement (as indicated by CODE) of ARG. The front end must check for
5351 invalid cases (e.g., decrement in C++). */
5352 tree
5353 boolean_increment (enum tree_code code, tree arg)
5355 tree val;
5356 tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5358 arg = stabilize_reference (arg);
5359 switch (code)
5361 case PREINCREMENT_EXPR:
5362 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5363 break;
5364 case POSTINCREMENT_EXPR:
5365 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5366 arg = save_expr (arg);
5367 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5368 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5369 break;
5370 case PREDECREMENT_EXPR:
5371 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5372 invert_truthvalue_loc (input_location, arg));
5373 break;
5374 case POSTDECREMENT_EXPR:
5375 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5376 invert_truthvalue_loc (input_location, arg));
5377 arg = save_expr (arg);
5378 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5379 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5380 break;
5381 default:
5382 gcc_unreachable ();
5384 TREE_SIDE_EFFECTS (val) = 1;
5385 return val;
5388 /* Built-in macros for stddef.h and stdint.h, that require macros
5389 defined in this file. */
5390 void
5391 c_stddef_cpp_builtins(void)
5393 builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5394 builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5395 builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5396 /* C++ has wchar_t as a builtin type, C doesn't, so if WINT_TYPE
5397 maps to wchar_t, define it to the underlying WCHAR_TYPE in C, and
5398 to wchar_t in C++, so the desired type equivalence holds. */
5399 if (!c_dialect_cxx ()
5400 && strcmp (WINT_TYPE, "wchar_t") == 0)
5401 builtin_define_with_value ("__WINT_TYPE__", WCHAR_TYPE, 0);
5402 else
5403 builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5404 builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5405 builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5406 if (flag_char8_t)
5407 builtin_define_with_value ("__CHAR8_TYPE__", CHAR8_TYPE, 0);
5408 builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5409 builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5410 if (SIG_ATOMIC_TYPE)
5411 builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5412 if (INT8_TYPE)
5413 builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5414 if (INT16_TYPE)
5415 builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5416 if (INT32_TYPE)
5417 builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5418 if (INT64_TYPE)
5419 builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5420 if (UINT8_TYPE)
5421 builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5422 if (UINT16_TYPE)
5423 builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5424 if (UINT32_TYPE)
5425 builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5426 if (UINT64_TYPE)
5427 builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5428 if (INT_LEAST8_TYPE)
5429 builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5430 if (INT_LEAST16_TYPE)
5431 builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5432 if (INT_LEAST32_TYPE)
5433 builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5434 if (INT_LEAST64_TYPE)
5435 builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5436 if (UINT_LEAST8_TYPE)
5437 builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5438 if (UINT_LEAST16_TYPE)
5439 builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5440 if (UINT_LEAST32_TYPE)
5441 builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5442 if (UINT_LEAST64_TYPE)
5443 builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5444 if (INT_FAST8_TYPE)
5445 builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5446 if (INT_FAST16_TYPE)
5447 builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5448 if (INT_FAST32_TYPE)
5449 builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5450 if (INT_FAST64_TYPE)
5451 builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5452 if (UINT_FAST8_TYPE)
5453 builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5454 if (UINT_FAST16_TYPE)
5455 builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5456 if (UINT_FAST32_TYPE)
5457 builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5458 if (UINT_FAST64_TYPE)
5459 builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5460 if (INTPTR_TYPE)
5461 builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5462 if (UINTPTR_TYPE)
5463 builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5464 /* GIMPLE FE testcases need access to the GCC internal 'sizetype'.
5465 Expose it as __SIZETYPE__. */
5466 if (flag_gimple)
5467 builtin_define_with_value ("__SIZETYPE__", SIZETYPE, 0);
5470 static void
5471 c_init_attributes (void)
5473 /* Fill in the built_in_attributes array. */
5474 #define DEF_ATTR_NULL_TREE(ENUM) \
5475 built_in_attributes[(int) ENUM] = NULL_TREE;
5476 #define DEF_ATTR_INT(ENUM, VALUE) \
5477 built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5478 #define DEF_ATTR_STRING(ENUM, VALUE) \
5479 built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5480 #define DEF_ATTR_IDENT(ENUM, STRING) \
5481 built_in_attributes[(int) ENUM] = get_identifier (STRING);
5482 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5483 built_in_attributes[(int) ENUM] \
5484 = tree_cons (built_in_attributes[(int) PURPOSE], \
5485 built_in_attributes[(int) VALUE], \
5486 built_in_attributes[(int) CHAIN]);
5487 #include "builtin-attrs.def"
5488 #undef DEF_ATTR_NULL_TREE
5489 #undef DEF_ATTR_INT
5490 #undef DEF_ATTR_IDENT
5491 #undef DEF_ATTR_TREE_LIST
5494 /* Check whether the byte alignment ALIGN is a valid user-specified
5495 alignment less than the supported maximum. If so, return ALIGN's
5496 base-2 log; if not, output an error and return -1. If OBJFILE
5497 then reject alignments greater than MAX_OFILE_ALIGNMENT when
5498 converted to bits. Otherwise, consider valid only alignments
5499 that are less than HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT.
5500 Zero is not considered a valid argument (and results in -1 on
5501 return) but it only triggers a warning when WARN_ZERO is set. */
5504 check_user_alignment (const_tree align, bool objfile, bool warn_zero)
5506 if (error_operand_p (align))
5507 return -1;
5509 if (TREE_CODE (align) != INTEGER_CST
5510 || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5512 error ("requested alignment is not an integer constant");
5513 return -1;
5516 if (integer_zerop (align))
5518 if (warn_zero)
5519 warning (OPT_Wattributes,
5520 "requested alignment %qE is not a positive power of 2",
5521 align);
5522 return -1;
5525 /* Log2 of the byte alignment ALIGN. */
5526 int log2align;
5527 if (tree_int_cst_sgn (align) == -1
5528 || (log2align = tree_log2 (align)) == -1)
5530 error ("requested alignment %qE is not a positive power of 2",
5531 align);
5532 return -1;
5535 if (objfile)
5537 unsigned maxalign = MAX_OFILE_ALIGNMENT / BITS_PER_UNIT;
5538 if (!tree_fits_uhwi_p (align) || tree_to_uhwi (align) > maxalign)
5540 error ("requested alignment %qE exceeds object file maximum %u",
5541 align, maxalign);
5542 return -1;
5546 if (log2align >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5548 error ("requested alignment %qE exceeds maximum %u",
5549 align, 1U << (HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT - 1));
5550 return -1;
5553 return log2align;
5556 /* Determine the ELF symbol visibility for DECL, which is either a
5557 variable or a function. It is an error to use this function if a
5558 definition of DECL is not available in this translation unit.
5559 Returns true if the final visibility has been determined by this
5560 function; false if the caller is free to make additional
5561 modifications. */
5563 bool
5564 c_determine_visibility (tree decl)
5566 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5568 /* If the user explicitly specified the visibility with an
5569 attribute, honor that. DECL_VISIBILITY will have been set during
5570 the processing of the attribute. We check for an explicit
5571 attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5572 to distinguish the use of an attribute from the use of a "#pragma
5573 GCC visibility push(...)"; in the latter case we still want other
5574 considerations to be able to overrule the #pragma. */
5575 if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5576 || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5577 && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5578 || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5579 return true;
5581 /* Set default visibility to whatever the user supplied with
5582 visibility_specified depending on #pragma GCC visibility. */
5583 if (!DECL_VISIBILITY_SPECIFIED (decl))
5585 if (visibility_options.inpragma
5586 || DECL_VISIBILITY (decl) != default_visibility)
5588 DECL_VISIBILITY (decl) = default_visibility;
5589 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5590 /* If visibility changed and DECL already has DECL_RTL, ensure
5591 symbol flags are updated. */
5592 if (((VAR_P (decl) && TREE_STATIC (decl))
5593 || TREE_CODE (decl) == FUNCTION_DECL)
5594 && DECL_RTL_SET_P (decl))
5595 make_decl_rtl (decl);
5598 return false;
5601 /* Data to communicate through check_function_arguments_recurse between
5602 check_function_nonnull and check_nonnull_arg. */
5604 struct nonnull_arg_ctx
5606 /* Location of the call. */
5607 location_t loc;
5608 /* The function whose arguments are being checked and its type (used
5609 for calls through function pointers). */
5610 const_tree fndecl, fntype;
5611 /* True if a warning has been issued. */
5612 bool warned_p;
5615 /* Check the argument list of a function call to CTX.FNDECL of CTX.FNTYPE
5616 for null in argument slots that are marked as requiring a non-null
5617 pointer argument. The NARGS arguments are passed in the array ARGARRAY.
5618 Return true if we have warned. */
5620 static bool
5621 check_function_nonnull (nonnull_arg_ctx &ctx, int nargs, tree *argarray)
5623 int firstarg = 0;
5624 if (TREE_CODE (ctx.fntype) == METHOD_TYPE)
5626 bool closure = false;
5627 if (ctx.fndecl)
5629 /* For certain lambda expressions the C++ front end emits calls
5630 that pass a null this pointer as an argument named __closure
5631 to the member operator() of empty function. Detect those
5632 and avoid checking them, but proceed to check the remaining
5633 arguments. */
5634 tree arg0 = DECL_ARGUMENTS (ctx.fndecl);
5635 if (tree arg0name = DECL_NAME (arg0))
5636 closure = id_equal (arg0name, "__closure");
5639 /* In calls to C++ non-static member functions check the this
5640 pointer regardless of whether the function is declared with
5641 attribute nonnull. */
5642 firstarg = 1;
5643 if (!closure)
5644 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[0],
5645 firstarg, OPT_Wnonnull);
5648 tree attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (ctx.fntype));
5649 if (attrs == NULL_TREE)
5650 return ctx.warned_p;
5652 tree a = attrs;
5653 /* See if any of the nonnull attributes has no arguments. If so,
5654 then every pointer argument is checked (in which case the check
5655 for pointer type is done in check_nonnull_arg). */
5656 if (TREE_VALUE (a) != NULL_TREE)
5658 a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5659 while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5661 if (a != NULL_TREE)
5662 for (int i = firstarg; i < nargs; i++)
5663 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5664 i + 1, OPT_Wnonnull);
5665 else
5667 /* Walk the argument list. If we encounter an argument number we
5668 should check for non-null, do it. */
5669 for (int i = firstarg; i < nargs; i++)
5671 for (a = attrs; ; a = TREE_CHAIN (a))
5673 a = lookup_attribute ("nonnull", a);
5674 if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5675 break;
5678 if (a != NULL_TREE)
5679 check_function_arguments_recurse (check_nonnull_arg, &ctx,
5680 argarray[i], i + 1,
5681 OPT_Wnonnull);
5684 return ctx.warned_p;
5687 /* Check that the Nth argument of a function call (counting backwards
5688 from the end) is a (pointer)0. The NARGS arguments are passed in the
5689 array ARGARRAY. */
5691 static void
5692 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5694 tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5696 if (attr)
5698 int len = 0;
5699 int pos = 0;
5700 tree sentinel;
5701 function_args_iterator iter;
5702 tree t;
5704 /* Skip over the named arguments. */
5705 FOREACH_FUNCTION_ARGS (fntype, t, iter)
5707 if (len == nargs)
5708 break;
5709 len++;
5712 if (TREE_VALUE (attr))
5714 tree p = TREE_VALUE (TREE_VALUE (attr));
5715 pos = TREE_INT_CST_LOW (p);
5718 /* The sentinel must be one of the varargs, i.e.
5719 in position >= the number of fixed arguments. */
5720 if ((nargs - 1 - pos) < len)
5722 warning (OPT_Wformat_,
5723 "not enough variable arguments to fit a sentinel");
5724 return;
5727 /* Validate the sentinel. */
5728 sentinel = fold_for_warn (argarray[nargs - 1 - pos]);
5729 if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5730 || !integer_zerop (sentinel))
5731 /* Although __null (in C++) is only an integer we allow it
5732 nevertheless, as we are guaranteed that it's exactly
5733 as wide as a pointer, and we don't want to force
5734 users to cast the NULL they have written there.
5735 We warn with -Wstrict-null-sentinel, though. */
5736 && (warn_strict_null_sentinel || null_node != sentinel))
5737 warning (OPT_Wformat_, "missing sentinel in function call");
5741 /* Check that the same argument isn't passed to two or more
5742 restrict-qualified formal and issue a -Wrestrict warning
5743 if it is. Return true if a warning has been issued. */
5745 static bool
5746 check_function_restrict (const_tree fndecl, const_tree fntype,
5747 int nargs, tree *unfolded_argarray)
5749 int i;
5750 tree parms = TYPE_ARG_TYPES (fntype);
5752 /* Call fold_for_warn on all of the arguments. */
5753 auto_vec<tree> argarray (nargs);
5754 for (i = 0; i < nargs; i++)
5755 argarray.quick_push (fold_for_warn (unfolded_argarray[i]));
5757 if (fndecl
5758 && TREE_CODE (fndecl) == FUNCTION_DECL)
5760 /* Avoid diagnosing calls built-ins with a zero size/bound
5761 here. They are checked in more detail elsewhere. */
5762 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
5763 && nargs == 3
5764 && TREE_CODE (argarray[2]) == INTEGER_CST
5765 && integer_zerop (argarray[2]))
5766 return false;
5768 if (DECL_ARGUMENTS (fndecl))
5769 parms = DECL_ARGUMENTS (fndecl);
5772 for (i = 0; i < nargs; i++)
5773 TREE_VISITED (argarray[i]) = 0;
5775 bool warned = false;
5777 for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5779 tree type;
5780 if (TREE_CODE (parms) == PARM_DECL)
5782 type = TREE_TYPE (parms);
5783 parms = DECL_CHAIN (parms);
5785 else
5787 type = TREE_VALUE (parms);
5788 parms = TREE_CHAIN (parms);
5790 if (POINTER_TYPE_P (type)
5791 && TYPE_RESTRICT (type)
5792 && !TYPE_READONLY (TREE_TYPE (type)))
5793 warned |= warn_for_restrict (i, argarray.address (), nargs);
5796 for (i = 0; i < nargs; i++)
5797 TREE_VISITED (argarray[i]) = 0;
5799 return warned;
5802 /* Helper for check_function_nonnull; given a list of operands which
5803 must be non-null in ARGS, determine if operand PARAM_NUM should be
5804 checked. */
5806 static bool
5807 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5809 unsigned HOST_WIDE_INT arg_num = 0;
5811 for (; args; args = TREE_CHAIN (args))
5813 bool found = get_attribute_operand (TREE_VALUE (args), &arg_num);
5815 gcc_assert (found);
5817 if (arg_num == param_num)
5818 return true;
5820 return false;
5823 /* Check that the function argument PARAM (which is operand number
5824 PARAM_NUM) is non-null. This is called by check_function_nonnull
5825 via check_function_arguments_recurse. */
5827 static void
5828 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5830 struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5832 /* Just skip checking the argument if it's not a pointer. This can
5833 happen if the "nonnull" attribute was given without an operand
5834 list (which means to check every pointer argument). */
5836 tree paramtype = TREE_TYPE (param);
5837 if (TREE_CODE (paramtype) != POINTER_TYPE
5838 && TREE_CODE (paramtype) != NULLPTR_TYPE)
5839 return;
5841 /* Diagnose the simple cases of null arguments. */
5842 if (!integer_zerop (fold_for_warn (param)))
5843 return;
5845 auto_diagnostic_group adg;
5847 const location_t loc = EXPR_LOC_OR_LOC (param, pctx->loc);
5849 if (TREE_CODE (pctx->fntype) == METHOD_TYPE)
5850 --param_num;
5852 bool warned;
5853 if (param_num == 0)
5855 warned = warning_at (loc, OPT_Wnonnull,
5856 "%qs pointer is null", "this");
5857 if (warned && pctx->fndecl)
5858 inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5859 "in a call to non-static member function %qD",
5860 pctx->fndecl);
5862 else
5864 warned = warning_at (loc, OPT_Wnonnull,
5865 "argument %u null where non-null expected",
5866 (unsigned) param_num);
5867 if (warned && pctx->fndecl)
5868 inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5869 "in a call to function %qD declared %qs",
5870 pctx->fndecl, "nonnull");
5873 if (warned)
5874 pctx->warned_p = true;
5877 /* Helper for attribute handling; fetch the operand number from
5878 the attribute argument list. */
5880 bool
5881 get_attribute_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5883 /* Verify the arg number is a small constant. */
5884 if (tree_fits_uhwi_p (arg_num_expr))
5886 *valp = tree_to_uhwi (arg_num_expr);
5887 return true;
5889 else
5890 return false;
5893 /* Arguments being collected for optimization. */
5894 typedef const char *const_char_p; /* For DEF_VEC_P. */
5895 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5898 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5899 options in ARGS. ATTR_P is true if this is for attribute(optimize), and
5900 false for #pragma GCC optimize. */
5902 bool
5903 parse_optimize_options (tree args, bool attr_p)
5905 bool ret = true;
5906 unsigned opt_argc;
5907 unsigned i;
5908 const char **opt_argv;
5909 struct cl_decoded_option *decoded_options;
5910 unsigned int decoded_options_count;
5911 tree ap;
5913 /* Build up argv vector. Just in case the string is stored away, use garbage
5914 collected strings. */
5915 vec_safe_truncate (optimize_args, 0);
5916 vec_safe_push (optimize_args, (const char *) NULL);
5918 for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5920 tree value = TREE_VALUE (ap);
5922 if (TREE_CODE (value) == INTEGER_CST)
5924 char buffer[HOST_BITS_PER_LONG / 3 + 4];
5925 sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5926 vec_safe_push (optimize_args, ggc_strdup (buffer));
5929 else if (TREE_CODE (value) == STRING_CST)
5931 /* Split string into multiple substrings. */
5932 size_t len = TREE_STRING_LENGTH (value);
5933 char *p = ASTRDUP (TREE_STRING_POINTER (value));
5934 char *end = p + len;
5935 char *comma;
5936 char *next_p = p;
5938 while (next_p != NULL)
5940 size_t len2;
5941 char *q, *r;
5943 p = next_p;
5944 comma = strchr (p, ',');
5945 if (comma)
5947 len2 = comma - p;
5948 *comma = '\0';
5949 next_p = comma+1;
5951 else
5953 len2 = end - p;
5954 next_p = NULL;
5957 /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5958 options. */
5959 if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5961 ret = false;
5962 if (attr_p)
5963 warning (OPT_Wattributes,
5964 "bad option %qs to attribute %<optimize%>", p);
5965 else
5966 warning (OPT_Wpragmas,
5967 "bad option %qs to pragma %<optimize%>", p);
5968 continue;
5971 /* Can't use GC memory here, see PR88007. */
5972 r = q = XOBNEWVEC (&opts_obstack, char, len2 + 3);
5974 if (*p != '-')
5976 *r++ = '-';
5978 /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5979 itself is -Os, and any other switch begins with a -f. */
5980 if ((*p >= '0' && *p <= '9')
5981 || (p[0] == 's' && p[1] == '\0'))
5982 *r++ = 'O';
5983 else if (*p != 'O')
5984 *r++ = 'f';
5987 memcpy (r, p, len2);
5988 r[len2] = '\0';
5989 vec_safe_push (optimize_args, (const char *) q);
5995 opt_argc = optimize_args->length ();
5996 opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5998 for (i = 1; i < opt_argc; i++)
5999 opt_argv[i] = (*optimize_args)[i];
6001 /* Now parse the options. */
6002 decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
6003 &decoded_options,
6004 &decoded_options_count);
6005 /* Drop non-Optimization options. */
6006 unsigned j = 1;
6007 for (i = 1; i < decoded_options_count; ++i)
6009 if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
6011 ret = false;
6012 if (attr_p)
6013 warning (OPT_Wattributes,
6014 "bad option %qs to attribute %<optimize%>",
6015 decoded_options[i].orig_option_with_args_text);
6016 else
6017 warning (OPT_Wpragmas,
6018 "bad option %qs to pragma %<optimize%>",
6019 decoded_options[i].orig_option_with_args_text);
6020 continue;
6022 if (i != j)
6023 decoded_options[j] = decoded_options[i];
6024 j++;
6026 decoded_options_count = j;
6028 /* Merge the decoded options with save_decoded_options. */
6029 unsigned save_opt_count = save_opt_decoded_options->length ();
6030 unsigned merged_decoded_options_count
6031 = save_opt_count + decoded_options_count;
6032 cl_decoded_option *merged_decoded_options
6033 = XNEWVEC (cl_decoded_option, merged_decoded_options_count);
6035 /* Note the first decoded_options is used for the program name. */
6036 for (unsigned i = 0; i < save_opt_count; ++i)
6037 merged_decoded_options[i + 1] = (*save_opt_decoded_options)[i];
6038 for (unsigned i = 1; i < decoded_options_count; ++i)
6039 merged_decoded_options[save_opt_count + i] = decoded_options[i];
6041 /* And apply them. */
6042 decode_options (&global_options, &global_options_set,
6043 merged_decoded_options, merged_decoded_options_count,
6044 input_location, global_dc, NULL);
6045 free (decoded_options);
6047 targetm.override_options_after_change();
6049 optimize_args->truncate (0);
6050 return ret;
6053 /* Check whether ATTR is a valid attribute fallthrough. */
6055 bool
6056 attribute_fallthrough_p (tree attr)
6058 if (attr == error_mark_node)
6059 return false;
6060 tree t = lookup_attribute ("", "fallthrough", attr);
6061 if (t == NULL_TREE)
6062 return false;
6063 /* It is no longer true that "this attribute shall appear at most once in
6064 each attribute-list", but we still give a warning. */
6065 if (lookup_attribute ("", "fallthrough", TREE_CHAIN (t)))
6066 warning (OPT_Wattributes, "attribute %<fallthrough%> specified multiple "
6067 "times");
6068 /* No attribute-argument-clause shall be present. */
6069 else if (TREE_VALUE (t) != NULL_TREE)
6070 warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
6071 "a parameter");
6072 /* Warn if other attributes are found. */
6073 for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
6075 tree name = get_attribute_name (t);
6076 if (!is_attribute_p ("fallthrough", name)
6077 || !is_attribute_namespace_p ("", t))
6079 if (!c_dialect_cxx () && get_attribute_namespace (t) == NULL_TREE)
6080 /* The specifications of standard attributes in C mean
6081 this is a constraint violation. */
6082 pedwarn (input_location, OPT_Wattributes, "%qE attribute ignored",
6083 get_attribute_name (t));
6084 else
6085 warning (OPT_Wattributes, "%qE attribute ignored", name);
6088 return true;
6092 /* Check for valid arguments being passed to a function with FNTYPE.
6093 There are NARGS arguments in the array ARGARRAY. LOC should be used
6094 for diagnostics. Return true if either -Wnonnull or -Wrestrict has
6095 been issued.
6097 The arguments in ARGARRAY may not have been folded yet (e.g. for C++,
6098 to preserve location wrappers); checks that require folded arguments
6099 should call fold_for_warn on them. */
6101 bool
6102 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
6103 int nargs, tree *argarray, vec<location_t> *arglocs)
6105 bool warned_p = false;
6107 /* Check for null being passed in a pointer argument that must be
6108 non-null. In C++, this includes the this pointer. We also need
6109 to do this if format checking is enabled. */
6110 if (warn_nonnull)
6112 nonnull_arg_ctx ctx = { loc, fndecl, fntype, false };
6113 warned_p = check_function_nonnull (ctx, nargs, argarray);
6116 /* Check for errors in format strings. */
6118 if (warn_format || warn_suggest_attribute_format)
6119 check_function_format (fndecl ? fndecl : fntype, TYPE_ATTRIBUTES (fntype), nargs,
6120 argarray, arglocs);
6122 if (warn_format)
6123 check_function_sentinel (fntype, nargs, argarray);
6125 if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
6127 switch (DECL_FUNCTION_CODE (fndecl))
6129 case BUILT_IN_SPRINTF:
6130 case BUILT_IN_SPRINTF_CHK:
6131 case BUILT_IN_SNPRINTF:
6132 case BUILT_IN_SNPRINTF_CHK:
6133 /* Let the sprintf pass handle these. */
6134 return warned_p;
6136 default:
6137 break;
6141 /* check_function_restrict sets the DECL_READ_P for arguments
6142 so it must be called unconditionally. */
6143 warned_p |= check_function_restrict (fndecl, fntype, nargs, argarray);
6145 return warned_p;
6148 /* Generic argument checking recursion routine. PARAM is the argument to
6149 be checked. PARAM_NUM is the number of the argument. CALLBACK is invoked
6150 once the argument is resolved. CTX is context for the callback.
6151 OPT is the warning for which this is done. */
6152 void
6153 check_function_arguments_recurse (void (*callback)
6154 (void *, tree, unsigned HOST_WIDE_INT),
6155 void *ctx, tree param,
6156 unsigned HOST_WIDE_INT param_num,
6157 opt_code opt)
6159 if (opt != OPT_Wformat_ && warning_suppressed_p (param))
6160 return;
6162 if (CONVERT_EXPR_P (param)
6163 && (TYPE_PRECISION (TREE_TYPE (param))
6164 == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
6166 /* Strip coercion. */
6167 check_function_arguments_recurse (callback, ctx,
6168 TREE_OPERAND (param, 0), param_num,
6169 opt);
6170 return;
6173 if (TREE_CODE (param) == CALL_EXPR && CALL_EXPR_FN (param))
6175 tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
6176 tree attrs;
6177 bool found_format_arg = false;
6179 /* See if this is a call to a known internationalization function
6180 that modifies a format arg. Such a function may have multiple
6181 format_arg attributes (for example, ngettext). */
6183 for (attrs = TYPE_ATTRIBUTES (type);
6184 attrs;
6185 attrs = TREE_CHAIN (attrs))
6186 if (is_attribute_p ("format_arg", get_attribute_name (attrs)))
6188 tree inner_arg;
6189 tree format_num_expr;
6190 int format_num;
6191 int i;
6192 call_expr_arg_iterator iter;
6194 /* Extract the argument number, which was previously checked
6195 to be valid. */
6196 format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
6198 format_num = tree_to_uhwi (format_num_expr);
6200 for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
6201 inner_arg != NULL_TREE;
6202 inner_arg = next_call_expr_arg (&iter), i++)
6203 if (i == format_num)
6205 check_function_arguments_recurse (callback, ctx,
6206 inner_arg, param_num,
6207 opt);
6208 found_format_arg = true;
6209 break;
6213 /* If we found a format_arg attribute and did a recursive check,
6214 we are done with checking this argument. Otherwise, we continue
6215 and this will be considered a non-literal. */
6216 if (found_format_arg)
6217 return;
6220 if (TREE_CODE (param) == COND_EXPR)
6222 /* Simplify to avoid warning for an impossible case. */
6223 param = fold_for_warn (param);
6224 if (TREE_CODE (param) == COND_EXPR)
6226 /* Check both halves of the conditional expression. */
6227 check_function_arguments_recurse (callback, ctx,
6228 TREE_OPERAND (param, 1),
6229 param_num, opt);
6230 check_function_arguments_recurse (callback, ctx,
6231 TREE_OPERAND (param, 2),
6232 param_num, opt);
6233 return;
6237 (*callback) (ctx, param, param_num);
6240 /* Checks for a builtin function FNDECL that the number of arguments
6241 NARGS against the required number REQUIRED and issues an error if
6242 there is a mismatch. Returns true if the number of arguments is
6243 correct, otherwise false. LOC is the location of FNDECL. */
6245 static bool
6246 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
6247 int required)
6249 if (nargs < required)
6251 error_at (loc, "too few arguments to function %qE", fndecl);
6252 return false;
6254 else if (nargs > required)
6256 error_at (loc, "too many arguments to function %qE", fndecl);
6257 return false;
6259 return true;
6262 /* Helper macro for check_builtin_function_arguments. */
6263 #define ARG_LOCATION(N) \
6264 (arg_loc.is_empty () \
6265 ? EXPR_LOC_OR_LOC (args[(N)], input_location) \
6266 : expansion_point_location (arg_loc[(N)]))
6268 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
6269 Returns false if there was an error, otherwise true. LOC is the
6270 location of the function; ARG_LOC is a vector of locations of the
6271 arguments. If FNDECL is the result of resolving an overloaded
6272 target built-in, ORIG_FNDECL is the original function decl,
6273 otherwise it is null. */
6275 bool
6276 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
6277 tree fndecl, tree orig_fndecl,
6278 int nargs, tree *args)
6280 if (!fndecl_built_in_p (fndecl))
6281 return true;
6283 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
6284 return (!targetm.check_builtin_call
6285 || targetm.check_builtin_call (loc, arg_loc, fndecl,
6286 orig_fndecl, nargs, args));
6288 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_FRONTEND)
6289 return true;
6291 gcc_assert (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL);
6292 switch (DECL_FUNCTION_CODE (fndecl))
6294 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
6295 if (!tree_fits_uhwi_p (args[2]))
6297 error_at (ARG_LOCATION (2),
6298 "third argument to function %qE must be a constant integer",
6299 fndecl);
6300 return false;
6302 /* fall through */
6304 case BUILT_IN_ALLOCA_WITH_ALIGN:
6306 /* Get the requested alignment (in bits) if it's a constant
6307 integer expression. */
6308 unsigned HOST_WIDE_INT align
6309 = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
6311 /* Determine if the requested alignment is a power of 2. */
6312 if ((align & (align - 1)))
6313 align = 0;
6315 /* The maximum alignment in bits corresponding to the same
6316 maximum in bytes enforced in check_user_alignment(). */
6317 unsigned maxalign = (UINT_MAX >> 1) + 1;
6319 /* Reject invalid alignments. */
6320 if (align < BITS_PER_UNIT || maxalign < align)
6322 error_at (ARG_LOCATION (1),
6323 "second argument to function %qE must be a constant "
6324 "integer power of 2 between %qi and %qu bits",
6325 fndecl, BITS_PER_UNIT, maxalign);
6326 return false;
6328 return true;
6331 case BUILT_IN_CONSTANT_P:
6332 return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
6334 case BUILT_IN_ISFINITE:
6335 case BUILT_IN_ISINF:
6336 case BUILT_IN_ISINF_SIGN:
6337 case BUILT_IN_ISNAN:
6338 case BUILT_IN_ISNORMAL:
6339 case BUILT_IN_ISSIGNALING:
6340 case BUILT_IN_SIGNBIT:
6341 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6343 if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
6345 error_at (ARG_LOCATION (0), "non-floating-point argument in "
6346 "call to function %qE", fndecl);
6347 return false;
6349 return true;
6351 return false;
6353 case BUILT_IN_ISGREATER:
6354 case BUILT_IN_ISGREATEREQUAL:
6355 case BUILT_IN_ISLESS:
6356 case BUILT_IN_ISLESSEQUAL:
6357 case BUILT_IN_ISLESSGREATER:
6358 case BUILT_IN_ISUNORDERED:
6359 case BUILT_IN_ISEQSIG:
6360 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
6362 enum tree_code code0, code1;
6363 code0 = TREE_CODE (TREE_TYPE (args[0]));
6364 code1 = TREE_CODE (TREE_TYPE (args[1]));
6365 if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
6366 || (code0 == REAL_TYPE
6367 && (code1 == INTEGER_TYPE || code1 == BITINT_TYPE))
6368 || ((code0 == INTEGER_TYPE || code0 == BITINT_TYPE)
6369 && code1 == REAL_TYPE)))
6371 error_at (loc, "non-floating-point arguments in call to "
6372 "function %qE", fndecl);
6373 return false;
6375 return true;
6377 return false;
6379 case BUILT_IN_FPCLASSIFY:
6380 if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
6382 for (unsigned int i = 0; i < 5; i++)
6383 if (TREE_CODE (args[i]) != INTEGER_CST)
6385 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
6386 "call to function %qE", i + 1, fndecl);
6387 return false;
6390 if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
6392 error_at (ARG_LOCATION (5), "non-floating-point argument in "
6393 "call to function %qE", fndecl);
6394 return false;
6396 return true;
6398 return false;
6400 case BUILT_IN_ASSUME_ALIGNED:
6401 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
6403 if (nargs >= 3
6404 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE
6405 && TREE_CODE (TREE_TYPE (args[2])) != BITINT_TYPE)
6407 error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
6408 "function %qE", fndecl);
6409 return false;
6411 return true;
6413 return false;
6415 case BUILT_IN_ADD_OVERFLOW:
6416 case BUILT_IN_SUB_OVERFLOW:
6417 case BUILT_IN_MUL_OVERFLOW:
6418 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6420 unsigned i;
6421 for (i = 0; i < 2; i++)
6422 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6424 error_at (ARG_LOCATION (i), "argument %u in call to function "
6425 "%qE does not have integral type", i + 1, fndecl);
6426 return false;
6428 if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
6429 || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
6431 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6432 "does not have pointer to integral type", fndecl);
6433 return false;
6435 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
6437 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6438 "has pointer to enumerated type", fndecl);
6439 return false;
6441 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
6443 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6444 "has pointer to boolean type", fndecl);
6445 return false;
6447 else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[2]))))
6449 error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6450 "has pointer to %qs type (%qT)", 3, fndecl, "const",
6451 TREE_TYPE (args[2]));
6452 return false;
6454 else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[2]))))
6456 error_at (ARG_LOCATION (2), "argument %u in call to function %qE "
6457 "has pointer to %qs type (%qT)", 3, fndecl,
6458 "_Atomic", TREE_TYPE (args[2]));
6459 return false;
6461 return true;
6463 return false;
6465 case BUILT_IN_ADD_OVERFLOW_P:
6466 case BUILT_IN_SUB_OVERFLOW_P:
6467 case BUILT_IN_MUL_OVERFLOW_P:
6468 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6470 unsigned i;
6471 for (i = 0; i < 3; i++)
6472 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6474 error_at (ARG_LOCATION (i), "argument %u in call to function "
6475 "%qE does not have integral type", i + 1, fndecl);
6476 return false;
6478 if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
6480 error_at (ARG_LOCATION (2), "argument %u in call to function "
6481 "%qE has enumerated type", 3, fndecl);
6482 return false;
6484 else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
6486 error_at (ARG_LOCATION (2), "argument %u in call to function "
6487 "%qE has boolean type", 3, fndecl);
6488 return false;
6490 return true;
6492 return false;
6494 case BUILT_IN_CLEAR_PADDING:
6495 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6497 if (!POINTER_TYPE_P (TREE_TYPE (args[0])))
6499 error_at (ARG_LOCATION (0), "argument %u in call to function "
6500 "%qE does not have pointer type", 1, fndecl);
6501 return false;
6503 else if (!COMPLETE_TYPE_P (TREE_TYPE (TREE_TYPE (args[0]))))
6505 error_at (ARG_LOCATION (0), "argument %u in call to function "
6506 "%qE points to incomplete type", 1, fndecl);
6507 return false;
6509 else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[0]))))
6511 error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6512 "has pointer to %qs type (%qT)", 1, fndecl, "const",
6513 TREE_TYPE (args[0]));
6514 return false;
6516 else if (TYPE_ATOMIC (TREE_TYPE (TREE_TYPE (args[0]))))
6518 error_at (ARG_LOCATION (0), "argument %u in call to function %qE "
6519 "has pointer to %qs type (%qT)", 1, fndecl,
6520 "_Atomic", TREE_TYPE (args[0]));
6521 return false;
6523 return true;
6525 return false;
6527 case BUILT_IN_CLZG:
6528 case BUILT_IN_CTZG:
6529 case BUILT_IN_CLRSBG:
6530 case BUILT_IN_FFSG:
6531 case BUILT_IN_PARITYG:
6532 case BUILT_IN_POPCOUNTG:
6533 if (nargs == 2
6534 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CLZG
6535 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CTZG))
6537 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[1])))
6539 error_at (ARG_LOCATION (1), "argument %u in call to function "
6540 "%qE does not have integral type", 2, fndecl);
6541 return false;
6543 if ((TYPE_PRECISION (TREE_TYPE (args[1]))
6544 > TYPE_PRECISION (integer_type_node))
6545 || (TYPE_PRECISION (TREE_TYPE (args[1]))
6546 == TYPE_PRECISION (integer_type_node)
6547 && TYPE_UNSIGNED (TREE_TYPE (args[1]))))
6549 error_at (ARG_LOCATION (1), "argument %u in call to function "
6550 "%qE does not have %<int%> type", 2, fndecl);
6551 return false;
6554 else if (!builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6555 return false;
6557 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[0])))
6559 error_at (ARG_LOCATION (0), "argument %u in call to function "
6560 "%qE does not have integral type", 1, fndecl);
6561 return false;
6563 if (TREE_CODE (TREE_TYPE (args[0])) == ENUMERAL_TYPE)
6565 error_at (ARG_LOCATION (0), "argument %u in call to function "
6566 "%qE has enumerated type", 1, fndecl);
6567 return false;
6569 if (TREE_CODE (TREE_TYPE (args[0])) == BOOLEAN_TYPE)
6571 error_at (ARG_LOCATION (0), "argument %u in call to function "
6572 "%qE has boolean type", 1, fndecl);
6573 return false;
6575 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_FFSG
6576 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CLRSBG)
6578 if (TYPE_UNSIGNED (TREE_TYPE (args[0])))
6580 error_at (ARG_LOCATION (0), "argument 1 in call to function "
6581 "%qE has unsigned type", fndecl);
6582 return false;
6585 else if (!TYPE_UNSIGNED (TREE_TYPE (args[0])))
6587 error_at (ARG_LOCATION (0), "argument 1 in call to function "
6588 "%qE has signed type", fndecl);
6589 return false;
6591 return true;
6593 default:
6594 return true;
6598 /* Subroutine of c_parse_error.
6599 Return the result of concatenating LHS and RHS. RHS is really
6600 a string literal, its first character is indicated by RHS_START and
6601 RHS_SIZE is its length (including the terminating NUL character).
6603 The caller is responsible for deleting the returned pointer. */
6605 static char *
6606 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
6608 const size_t lhs_size = strlen (lhs);
6609 char *result = XNEWVEC (char, lhs_size + rhs_size);
6610 memcpy (result, lhs, lhs_size);
6611 memcpy (result + lhs_size, rhs_start, rhs_size);
6612 return result;
6615 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
6616 before TOKEN, which had the associated VALUE. */
6618 void
6619 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
6620 tree value, unsigned char token_flags,
6621 rich_location *richloc)
6623 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
6625 char *message = NULL;
6627 if (token_type == CPP_EOF)
6628 message = catenate_messages (gmsgid, " at end of input");
6629 else if (token_type == CPP_CHAR
6630 || token_type == CPP_WCHAR
6631 || token_type == CPP_CHAR16
6632 || token_type == CPP_CHAR32
6633 || token_type == CPP_UTF8CHAR)
6635 unsigned int val = TREE_INT_CST_LOW (value);
6636 const char *prefix;
6638 switch (token_type)
6640 default:
6641 prefix = "";
6642 break;
6643 case CPP_WCHAR:
6644 prefix = "L";
6645 break;
6646 case CPP_CHAR16:
6647 prefix = "u";
6648 break;
6649 case CPP_CHAR32:
6650 prefix = "U";
6651 break;
6652 case CPP_UTF8CHAR:
6653 prefix = "u8";
6654 break;
6657 if (val <= UCHAR_MAX && ISGRAPH (val))
6658 message = catenate_messages (gmsgid, " before %s'%c'");
6659 else
6660 message = catenate_messages (gmsgid, " before %s'\\x%x'");
6662 error_at (richloc, message, prefix, val);
6663 free (message);
6664 message = NULL;
6666 else if (token_type == CPP_CHAR_USERDEF
6667 || token_type == CPP_WCHAR_USERDEF
6668 || token_type == CPP_CHAR16_USERDEF
6669 || token_type == CPP_CHAR32_USERDEF
6670 || token_type == CPP_UTF8CHAR_USERDEF)
6671 message = catenate_messages (gmsgid,
6672 " before user-defined character literal");
6673 else if (token_type == CPP_STRING_USERDEF
6674 || token_type == CPP_WSTRING_USERDEF
6675 || token_type == CPP_STRING16_USERDEF
6676 || token_type == CPP_STRING32_USERDEF
6677 || token_type == CPP_UTF8STRING_USERDEF)
6678 message = catenate_messages (gmsgid, " before user-defined string literal");
6679 else if (token_type == CPP_STRING
6680 || token_type == CPP_WSTRING
6681 || token_type == CPP_STRING16
6682 || token_type == CPP_STRING32
6683 || token_type == CPP_UTF8STRING)
6684 message = catenate_messages (gmsgid, " before string constant");
6685 else if (token_type == CPP_NUMBER)
6686 message = catenate_messages (gmsgid, " before numeric constant");
6687 else if (token_type == CPP_NAME)
6689 message = catenate_messages (gmsgid, " before %qE");
6690 error_at (richloc, message, value);
6691 free (message);
6692 message = NULL;
6694 else if (token_type == CPP_PRAGMA)
6695 message = catenate_messages (gmsgid, " before %<#pragma%>");
6696 else if (token_type == CPP_PRAGMA_EOL)
6697 message = catenate_messages (gmsgid, " before end of line");
6698 else if (token_type == CPP_DECLTYPE)
6699 message = catenate_messages (gmsgid, " before %<decltype%>");
6700 else if (token_type < N_TTYPES)
6702 message = catenate_messages (gmsgid, " before %qs token");
6703 error_at (richloc, message, cpp_type2name (token_type, token_flags));
6704 free (message);
6705 message = NULL;
6707 else
6708 error_at (richloc, gmsgid);
6710 if (message)
6712 error_at (richloc, message);
6713 free (message);
6715 #undef catenate_messages
6718 /* Return the gcc option code associated with the reason for a cpp
6719 message, or 0 if none. */
6721 static int
6722 c_option_controlling_cpp_diagnostic (enum cpp_warning_reason reason)
6724 const struct cpp_reason_option_codes_t *entry;
6726 for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6728 if (entry->reason == reason)
6729 return entry->option_code;
6731 return 0;
6734 /* Return TRUE if the given option index corresponds to a diagnostic
6735 issued by libcpp. Linear search seems fine for now. */
6736 bool
6737 c_option_is_from_cpp_diagnostics (int option_index)
6739 for (auto entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE;
6740 ++entry)
6742 if (entry->option_code == option_index)
6743 return true;
6745 return false;
6748 /* Callback from cpp_diagnostic for PFILE to print diagnostics from the
6749 preprocessor. The diagnostic is of type LEVEL, with REASON set
6750 to the reason code if LEVEL is represents a warning, at location
6751 RICHLOC unless this is after lexing and the compiler's location
6752 should be used instead; MSG is the translated message and AP
6753 the arguments. Returns true if a diagnostic was emitted, false
6754 otherwise. */
6756 bool
6757 c_cpp_diagnostic (cpp_reader *pfile ATTRIBUTE_UNUSED,
6758 enum cpp_diagnostic_level level,
6759 enum cpp_warning_reason reason,
6760 rich_location *richloc,
6761 const char *msg, va_list *ap)
6763 diagnostic_info diagnostic;
6764 diagnostic_t dlevel;
6765 bool save_warn_system_headers = global_dc->m_warn_system_headers;
6766 bool ret;
6768 switch (level)
6770 case CPP_DL_WARNING_SYSHDR:
6771 if (flag_no_output)
6772 return false;
6773 global_dc->m_warn_system_headers = 1;
6774 /* Fall through. */
6775 case CPP_DL_WARNING:
6776 if (flag_no_output)
6777 return false;
6778 dlevel = DK_WARNING;
6779 break;
6780 case CPP_DL_PEDWARN:
6781 if (flag_no_output && !flag_pedantic_errors)
6782 return false;
6783 dlevel = DK_PEDWARN;
6784 break;
6785 case CPP_DL_ERROR:
6786 dlevel = DK_ERROR;
6787 break;
6788 case CPP_DL_ICE:
6789 dlevel = DK_ICE;
6790 break;
6791 case CPP_DL_NOTE:
6792 dlevel = DK_NOTE;
6793 break;
6794 case CPP_DL_FATAL:
6795 dlevel = DK_FATAL;
6796 break;
6797 default:
6798 gcc_unreachable ();
6800 if (override_libcpp_locations)
6801 richloc->set_range (0, input_location, SHOW_RANGE_WITH_CARET);
6802 diagnostic_set_info_translated (&diagnostic, msg, ap,
6803 richloc, dlevel);
6804 diagnostic_override_option_index
6805 (&diagnostic,
6806 c_option_controlling_cpp_diagnostic (reason));
6807 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6808 if (level == CPP_DL_WARNING_SYSHDR)
6809 global_dc->m_warn_system_headers = save_warn_system_headers;
6810 return ret;
6813 /* Convert a character from the host to the target execution character
6814 set. cpplib handles this, mostly. */
6816 HOST_WIDE_INT
6817 c_common_to_target_charset (HOST_WIDE_INT c)
6819 /* Character constants in GCC proper are sign-extended under -fsigned-char,
6820 zero-extended under -fno-signed-char. cpplib insists that characters
6821 and character constants are always unsigned. Hence we must convert
6822 back and forth. */
6823 cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6825 uc = cpp_host_to_exec_charset (parse_in, uc);
6827 if (flag_signed_char)
6828 return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6829 >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6830 else
6831 return uc;
6834 /* Fold an offsetof-like expression. EXPR is a nested sequence of component
6835 references with an INDIRECT_REF of a constant at the bottom; much like the
6836 traditional rendering of offsetof as a macro. TYPE is the desired type of
6837 the whole expression. Return the folded result. */
6839 tree
6840 fold_offsetof (tree expr, tree type, enum tree_code ctx)
6842 tree base, off, t;
6843 tree_code code = TREE_CODE (expr);
6844 switch (code)
6846 case ERROR_MARK:
6847 return expr;
6849 case VAR_DECL:
6850 error ("cannot apply %<offsetof%> to static data member %qD", expr);
6851 return error_mark_node;
6853 case CALL_EXPR:
6854 case TARGET_EXPR:
6855 error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6856 return error_mark_node;
6858 case NOP_EXPR:
6859 case INDIRECT_REF:
6860 if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6862 error ("cannot apply %<offsetof%> to a non constant address");
6863 return error_mark_node;
6865 return convert (type, TREE_OPERAND (expr, 0));
6867 case COMPONENT_REF:
6868 base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6869 if (base == error_mark_node)
6870 return base;
6872 t = TREE_OPERAND (expr, 1);
6873 if (DECL_C_BIT_FIELD (t))
6875 error ("attempt to take address of bit-field structure "
6876 "member %qD", t);
6877 return error_mark_node;
6879 off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6880 size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6881 / BITS_PER_UNIT));
6882 break;
6884 case ARRAY_REF:
6885 base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6886 if (base == error_mark_node)
6887 return base;
6889 t = TREE_OPERAND (expr, 1);
6890 STRIP_ANY_LOCATION_WRAPPER (t);
6892 /* Check if the offset goes beyond the upper bound of the array. */
6893 if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6895 tree upbound = array_ref_up_bound (expr);
6896 if (upbound != NULL_TREE
6897 && TREE_CODE (upbound) == INTEGER_CST
6898 && !tree_int_cst_equal (upbound,
6899 TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6901 if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6902 upbound = size_binop (PLUS_EXPR, upbound,
6903 build_int_cst (TREE_TYPE (upbound), 1));
6904 if (tree_int_cst_lt (upbound, t))
6906 tree v;
6908 for (v = TREE_OPERAND (expr, 0);
6909 TREE_CODE (v) == COMPONENT_REF;
6910 v = TREE_OPERAND (v, 0))
6911 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6912 == RECORD_TYPE)
6914 tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6915 for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6916 if (TREE_CODE (fld_chain) == FIELD_DECL)
6917 break;
6919 if (fld_chain)
6920 break;
6922 /* Don't warn if the array might be considered a poor
6923 man's flexible array member with a very permissive
6924 definition thereof. */
6925 if (TREE_CODE (v) == ARRAY_REF
6926 || TREE_CODE (v) == COMPONENT_REF)
6927 warning (OPT_Warray_bounds_,
6928 "index %E denotes an offset "
6929 "greater than size of %qT",
6930 t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6935 t = convert (sizetype, t);
6936 off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6937 break;
6939 case COMPOUND_EXPR:
6940 /* Handle static members of volatile structs. */
6941 t = TREE_OPERAND (expr, 1);
6942 gcc_checking_assert (VAR_P (get_base_address (t)));
6943 return fold_offsetof (t, type);
6945 default:
6946 gcc_unreachable ();
6949 if (!POINTER_TYPE_P (type))
6950 return size_binop (PLUS_EXPR, base, convert (type, off));
6951 return fold_build_pointer_plus (base, off);
6954 /* *PTYPE is an incomplete array. Complete it with a domain based on
6955 INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6956 is true. Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6957 2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty. */
6960 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6962 tree maxindex, type, main_type, elt, unqual_elt;
6963 int failure = 0, quals;
6964 bool overflow_p = false;
6966 maxindex = size_zero_node;
6967 if (initial_value)
6969 STRIP_ANY_LOCATION_WRAPPER (initial_value);
6971 if (TREE_CODE (initial_value) == STRING_CST)
6973 int eltsize
6974 = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6975 maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6977 else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6979 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6981 if (vec_safe_is_empty (v))
6983 if (pedantic)
6984 failure = 3;
6985 maxindex = ssize_int (-1);
6987 else
6989 tree curindex;
6990 unsigned HOST_WIDE_INT cnt;
6991 constructor_elt *ce;
6992 bool fold_p = false;
6994 if ((*v)[0].index)
6995 maxindex = (*v)[0].index, fold_p = true;
6997 curindex = maxindex;
6999 for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
7001 bool curfold_p = false;
7002 if (ce->index)
7003 curindex = ce->index, curfold_p = true;
7004 else
7006 if (fold_p)
7008 /* Since we treat size types now as ordinary
7009 unsigned types, we need an explicit overflow
7010 check. */
7011 tree orig = curindex;
7012 curindex = fold_convert (sizetype, curindex);
7013 overflow_p |= tree_int_cst_lt (curindex, orig);
7015 curindex = size_binop (PLUS_EXPR, curindex,
7016 size_one_node);
7018 if (tree_int_cst_lt (maxindex, curindex))
7019 maxindex = curindex, fold_p = curfold_p;
7021 if (fold_p)
7023 tree orig = maxindex;
7024 maxindex = fold_convert (sizetype, maxindex);
7025 overflow_p |= tree_int_cst_lt (maxindex, orig);
7029 else
7031 /* Make an error message unless that happened already. */
7032 if (initial_value != error_mark_node)
7033 failure = 1;
7036 else
7038 failure = 2;
7039 if (!do_default)
7040 return failure;
7043 type = *ptype;
7044 elt = TREE_TYPE (type);
7045 quals = TYPE_QUALS (strip_array_types (elt));
7046 if (quals == 0)
7047 unqual_elt = elt;
7048 else
7049 unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
7051 /* Using build_distinct_type_copy and modifying things afterward instead
7052 of using build_array_type to create a new type preserves all of the
7053 TYPE_LANG_FLAG_? bits that the front end may have set. */
7054 main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
7055 TREE_TYPE (main_type) = unqual_elt;
7056 TYPE_DOMAIN (main_type)
7057 = build_range_type (TREE_TYPE (maxindex),
7058 build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
7059 TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
7060 layout_type (main_type);
7062 /* Make sure we have the canonical MAIN_TYPE. */
7063 hashval_t hashcode = type_hash_canon_hash (main_type);
7064 main_type = type_hash_canon (hashcode, main_type);
7066 /* Fix the canonical type. */
7067 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
7068 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
7069 SET_TYPE_STRUCTURAL_EQUALITY (main_type);
7070 else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
7071 || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
7072 != TYPE_DOMAIN (main_type)))
7073 TYPE_CANONICAL (main_type)
7074 = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
7075 TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
7076 TYPE_TYPELESS_STORAGE (main_type));
7077 else
7078 TYPE_CANONICAL (main_type) = main_type;
7080 if (quals == 0)
7081 type = main_type;
7082 else
7083 type = c_build_qualified_type (main_type, quals);
7085 if (COMPLETE_TYPE_P (type)
7086 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
7087 && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
7089 error ("size of array is too large");
7090 /* If we proceed with the array type as it is, we'll eventually
7091 crash in tree_to_[su]hwi(). */
7092 type = error_mark_node;
7095 *ptype = type;
7096 return failure;
7099 /* INIT is an constructor of a structure with a flexible array member.
7100 Complete the flexible array member with a domain based on it's value. */
7101 void
7102 complete_flexible_array_elts (tree init)
7104 tree elt, type;
7106 if (init == NULL_TREE || TREE_CODE (init) != CONSTRUCTOR)
7107 return;
7109 if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
7110 return;
7112 elt = CONSTRUCTOR_ELTS (init)->last ().value;
7113 type = TREE_TYPE (elt);
7114 if (TREE_CODE (type) == ARRAY_TYPE
7115 && TYPE_SIZE (type) == NULL_TREE)
7116 complete_array_type (&TREE_TYPE (elt), elt, false);
7117 else
7118 complete_flexible_array_elts (elt);
7121 /* Like c_mark_addressable but don't check register qualifier. */
7122 void
7123 c_common_mark_addressable_vec (tree t)
7125 while (handled_component_p (t) || TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7127 if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
7128 t = C_MAYBE_CONST_EXPR_EXPR (t);
7129 else
7130 t = TREE_OPERAND (t, 0);
7132 if (!VAR_P (t)
7133 && TREE_CODE (t) != PARM_DECL
7134 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR
7135 && TREE_CODE (t) != TARGET_EXPR)
7136 return;
7137 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
7138 TREE_ADDRESSABLE (t) = 1;
7139 if (TREE_CODE (t) == COMPOUND_LITERAL_EXPR)
7140 TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (t)) = 1;
7141 else if (TREE_CODE (t) == TARGET_EXPR)
7142 TREE_ADDRESSABLE (TARGET_EXPR_SLOT (t)) = 1;
7147 /* Used to help initialize the builtin-types.def table. When a type of
7148 the correct size doesn't exist, use error_mark_node instead of NULL.
7149 The later results in segfaults even when a decl using the type doesn't
7150 get invoked. */
7152 tree
7153 builtin_type_for_size (int size, bool unsignedp)
7155 tree type = c_common_type_for_size (size, unsignedp);
7156 return type ? type : error_mark_node;
7159 /* Work out the size of the first argument of a call to
7160 __builtin_speculation_safe_value. Only pointers and integral types
7161 are permitted. Return -1 if the argument type is not supported or
7162 the size is too large; 0 if the argument type is a pointer or the
7163 size if it is integral. */
7164 static enum built_in_function
7165 speculation_safe_value_resolve_call (tree function, vec<tree, va_gc> *params)
7167 /* Type of the argument. */
7168 tree type;
7169 int size;
7171 if (vec_safe_is_empty (params))
7173 error ("too few arguments to function %qE", function);
7174 return BUILT_IN_NONE;
7177 type = TREE_TYPE ((*params)[0]);
7178 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7180 /* Force array-to-pointer decay for C++. */
7181 (*params)[0] = default_conversion ((*params)[0]);
7182 type = TREE_TYPE ((*params)[0]);
7185 if (POINTER_TYPE_P (type))
7186 return BUILT_IN_SPECULATION_SAFE_VALUE_PTR;
7188 if (!INTEGRAL_TYPE_P (type))
7189 goto incompatible;
7191 if (!COMPLETE_TYPE_P (type))
7192 goto incompatible;
7194 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7195 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7196 return ((enum built_in_function)
7197 ((int) BUILT_IN_SPECULATION_SAFE_VALUE_1 + exact_log2 (size)));
7199 incompatible:
7200 /* Issue the diagnostic only if the argument is valid, otherwise
7201 it would be redundant at best and could be misleading. */
7202 if (type != error_mark_node)
7203 error ("operand type %qT is incompatible with argument %d of %qE",
7204 type, 1, function);
7206 return BUILT_IN_NONE;
7209 /* Validate and coerce PARAMS, the arguments to ORIG_FUNCTION to fit
7210 the prototype for FUNCTION. The first argument is mandatory, a second
7211 argument, if present, must be type compatible with the first. */
7212 static bool
7213 speculation_safe_value_resolve_params (location_t loc, tree orig_function,
7214 vec<tree, va_gc> *params)
7216 tree val;
7218 if (params->length () == 0)
7220 error_at (loc, "too few arguments to function %qE", orig_function);
7221 return false;
7224 else if (params->length () > 2)
7226 error_at (loc, "too many arguments to function %qE", orig_function);
7227 return false;
7230 val = (*params)[0];
7231 if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE)
7232 val = default_conversion (val);
7233 if (!(TREE_CODE (TREE_TYPE (val)) == POINTER_TYPE
7234 || TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE))
7236 error_at (loc,
7237 "expecting argument of type pointer or of type integer "
7238 "for argument 1");
7239 return false;
7241 (*params)[0] = val;
7243 if (params->length () == 2)
7245 tree val2 = (*params)[1];
7246 if (TREE_CODE (TREE_TYPE (val2)) == ARRAY_TYPE)
7247 val2 = default_conversion (val2);
7248 if (error_operand_p (val2))
7249 return false;
7250 if (!(TREE_TYPE (val) == TREE_TYPE (val2)
7251 || useless_type_conversion_p (TREE_TYPE (val), TREE_TYPE (val2))))
7253 error_at (loc, "both arguments must be compatible");
7254 return false;
7256 (*params)[1] = val2;
7259 return true;
7262 /* Cast the result of the builtin back to the type of the first argument,
7263 preserving any qualifiers that it might have. */
7264 static tree
7265 speculation_safe_value_resolve_return (tree first_param, tree result)
7267 tree ptype = TREE_TYPE (first_param);
7268 tree rtype = TREE_TYPE (result);
7269 ptype = TYPE_MAIN_VARIANT (ptype);
7271 if (tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7272 return convert (ptype, result);
7274 return result;
7277 /* A helper function for resolve_overloaded_builtin in resolving the
7278 overloaded __sync_ builtins. Returns a positive power of 2 if the
7279 first operand of PARAMS is a pointer to a supported data type.
7280 Returns 0 if an error is encountered. Return -1 for _BitInt
7281 __atomic*fetch* with unsupported type which should be handled by
7282 a cas loop.
7283 FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
7284 built-ins. ORIG_FORMAT is for __sync_* rather than __atomic_*
7285 built-ins. */
7287 static int
7288 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch,
7289 bool orig_format)
7291 /* Type of the argument. */
7292 tree argtype;
7293 /* Type the argument points to. */
7294 tree type;
7295 int size;
7297 if (vec_safe_is_empty (params))
7299 error ("too few arguments to function %qE", function);
7300 return 0;
7303 argtype = type = TREE_TYPE ((*params)[0]);
7304 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7306 /* Force array-to-pointer decay for C++. */
7307 (*params)[0] = default_conversion ((*params)[0]);
7308 type = TREE_TYPE ((*params)[0]);
7310 if (TREE_CODE (type) != POINTER_TYPE)
7311 goto incompatible;
7313 type = TREE_TYPE (type);
7314 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
7315 goto incompatible;
7317 if (!COMPLETE_TYPE_P (type))
7318 goto incompatible;
7320 if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
7321 goto incompatible;
7323 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7324 if (size == 16
7325 && fetch
7326 && !orig_format
7327 && TREE_CODE (type) == BITINT_TYPE
7328 && !targetm.scalar_mode_supported_p (TImode))
7329 return -1;
7331 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
7332 return size;
7334 if (fetch && !orig_format && TREE_CODE (type) == BITINT_TYPE)
7335 return -1;
7337 incompatible:
7338 /* Issue the diagnostic only if the argument is valid, otherwise
7339 it would be redundant at best and could be misleading. */
7340 if (argtype != error_mark_node)
7341 error ("operand type %qT is incompatible with argument %d of %qE",
7342 argtype, 1, function);
7343 return 0;
7346 /* A helper function for resolve_overloaded_builtin. Adds casts to
7347 PARAMS to make arguments match up with those of FUNCTION. Drops
7348 the variadic arguments at the end. Returns false if some error
7349 was encountered; true on success. */
7351 static bool
7352 sync_resolve_params (location_t loc, tree orig_function, tree function,
7353 vec<tree, va_gc> *params, bool orig_format)
7355 function_args_iterator iter;
7356 tree ptype;
7357 unsigned int parmnum;
7359 function_args_iter_init (&iter, TREE_TYPE (function));
7360 /* We've declared the implementation functions to use "volatile void *"
7361 as the pointer parameter, so we shouldn't get any complaints from the
7362 call to check_function_arguments what ever type the user used. */
7363 function_args_iter_next (&iter);
7364 ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
7365 ptype = TYPE_MAIN_VARIANT (ptype);
7367 /* For the rest of the values, we need to cast these to FTYPE, so that we
7368 don't get warnings for passing pointer types, etc. */
7369 parmnum = 0;
7370 while (1)
7372 tree val, arg_type;
7374 arg_type = function_args_iter_cond (&iter);
7375 /* XXX void_type_node belies the abstraction. */
7376 if (arg_type == void_type_node)
7377 break;
7379 ++parmnum;
7380 if (params->length () <= parmnum)
7382 error_at (loc, "too few arguments to function %qE", orig_function);
7383 return false;
7386 /* Only convert parameters if arg_type is unsigned integer type with
7387 new format sync routines, i.e. don't attempt to convert pointer
7388 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
7389 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
7390 kinds). */
7391 if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
7393 /* Ideally for the first conversion we'd use convert_for_assignment
7394 so that we get warnings for anything that doesn't match the pointer
7395 type. This isn't portable across the C and C++ front ends atm. */
7396 val = (*params)[parmnum];
7397 val = convert (ptype, val);
7398 val = convert (arg_type, val);
7399 (*params)[parmnum] = val;
7402 function_args_iter_next (&iter);
7405 /* __atomic routines are not variadic. */
7406 if (!orig_format && params->length () != parmnum + 1)
7408 error_at (loc, "too many arguments to function %qE", orig_function);
7409 return false;
7412 /* The definition of these primitives is variadic, with the remaining
7413 being "an optional list of variables protected by the memory barrier".
7414 No clue what that's supposed to mean, precisely, but we consider all
7415 call-clobbered variables to be protected so we're safe. */
7416 params->truncate (parmnum + 1);
7418 return true;
7421 /* A helper function for resolve_overloaded_builtin. Adds a cast to
7422 RESULT to make it match the type of the first pointer argument in
7423 PARAMS. */
7425 static tree
7426 sync_resolve_return (tree first_param, tree result, bool orig_format)
7428 tree ptype = TREE_TYPE (TREE_TYPE (first_param));
7429 tree rtype = TREE_TYPE (result);
7430 ptype = TYPE_MAIN_VARIANT (ptype);
7432 /* New format doesn't require casting unless the types are the same size. */
7433 if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
7434 return convert (ptype, result);
7435 else
7436 return result;
7439 /* This function verifies the PARAMS to generic atomic FUNCTION.
7440 It returns the size if all the parameters are the same size, otherwise
7441 0 is returned if the parameters are invalid. */
7443 static int
7444 get_atomic_generic_size (location_t loc, tree function,
7445 vec<tree, va_gc> *params)
7447 unsigned int n_param;
7448 unsigned int n_model;
7449 unsigned int outputs = 0; // bitset of output parameters
7450 unsigned int x;
7451 int size_0;
7452 tree type_0;
7454 /* Determine the parameter makeup. */
7455 switch (DECL_FUNCTION_CODE (function))
7457 case BUILT_IN_ATOMIC_EXCHANGE:
7458 n_param = 4;
7459 n_model = 1;
7460 outputs = 5;
7461 break;
7462 case BUILT_IN_ATOMIC_LOAD:
7463 n_param = 3;
7464 n_model = 1;
7465 outputs = 2;
7466 break;
7467 case BUILT_IN_ATOMIC_STORE:
7468 n_param = 3;
7469 n_model = 1;
7470 outputs = 1;
7471 break;
7472 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7473 n_param = 6;
7474 n_model = 2;
7475 outputs = 3;
7476 break;
7477 default:
7478 gcc_unreachable ();
7481 if (vec_safe_length (params) != n_param)
7483 error_at (loc, "incorrect number of arguments to function %qE", function);
7484 return 0;
7487 /* Get type of first parameter, and determine its size. */
7488 type_0 = TREE_TYPE ((*params)[0]);
7489 if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
7491 /* Force array-to-pointer decay for C++. */
7492 (*params)[0] = default_conversion ((*params)[0]);
7493 type_0 = TREE_TYPE ((*params)[0]);
7495 if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
7497 error_at (loc, "argument 1 of %qE must be a non-void pointer type",
7498 function);
7499 return 0;
7502 if (!COMPLETE_TYPE_P (TREE_TYPE (type_0)))
7504 error_at (loc, "argument 1 of %qE must be a pointer to a complete type",
7505 function);
7506 return 0;
7509 /* Types must be compile time constant sizes. */
7510 if (!tree_fits_uhwi_p ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))))
7512 error_at (loc,
7513 "argument 1 of %qE must be a pointer to a constant size type",
7514 function);
7515 return 0;
7518 size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
7520 /* Zero size objects are not allowed. */
7521 if (size_0 == 0)
7523 error_at (loc,
7524 "argument 1 of %qE must be a pointer to a nonzero size object",
7525 function);
7526 return 0;
7529 /* Check each other parameter is a pointer and the same size. */
7530 for (x = 0; x < n_param - n_model; x++)
7532 int size;
7533 tree type = TREE_TYPE ((*params)[x]);
7534 /* __atomic_compare_exchange has a bool in the 4th position, skip it. */
7535 if (n_param == 6 && x == 3)
7536 continue;
7537 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7539 /* Force array-to-pointer decay for C++. */
7540 (*params)[x] = default_conversion ((*params)[x]);
7541 type = TREE_TYPE ((*params)[x]);
7543 if (!POINTER_TYPE_P (type))
7545 error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
7546 function);
7547 return 0;
7549 else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
7550 && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
7551 != INTEGER_CST)
7553 error_at (loc, "argument %d of %qE must be a pointer to a constant "
7554 "size type", x + 1, function);
7555 return 0;
7557 else if (FUNCTION_POINTER_TYPE_P (type))
7559 error_at (loc, "argument %d of %qE must not be a pointer to a "
7560 "function", x + 1, function);
7561 return 0;
7563 tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
7564 size = type_size ? tree_to_uhwi (type_size) : 0;
7565 if (size != size_0)
7567 error_at (loc, "size mismatch in argument %d of %qE", x + 1,
7568 function);
7569 return 0;
7573 auto_diagnostic_group d;
7574 int quals = TYPE_QUALS (TREE_TYPE (type));
7575 /* Must not write to an argument of a const-qualified type. */
7576 if (outputs & (1 << x) && quals & TYPE_QUAL_CONST)
7578 if (c_dialect_cxx ())
7580 error_at (loc, "argument %d of %qE must not be a pointer to "
7581 "a %<const%> type", x + 1, function);
7582 return 0;
7584 else
7585 pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7586 "of %qE discards %<const%> qualifier", x + 1,
7587 function);
7589 /* Only the first argument is allowed to be volatile. */
7590 if (x > 0 && quals & TYPE_QUAL_VOLATILE)
7592 if (c_dialect_cxx ())
7594 error_at (loc, "argument %d of %qE must not be a pointer to "
7595 "a %<volatile%> type", x + 1, function);
7596 return 0;
7598 else
7599 pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7600 "of %qE discards %<volatile%> qualifier", x + 1,
7601 function);
7606 /* Check memory model parameters for validity. */
7607 for (x = n_param - n_model ; x < n_param; x++)
7609 tree p = (*params)[x];
7610 if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
7612 error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
7613 function);
7614 return 0;
7616 p = fold_for_warn (p);
7617 if (TREE_CODE (p) == INTEGER_CST)
7619 /* memmodel_base masks the low 16 bits, thus ignore any bits above
7620 it by using TREE_INT_CST_LOW instead of tree_to_*hwi. Those high
7621 bits will be checked later during expansion in target specific
7622 way. */
7623 if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
7624 warning_at (loc, OPT_Winvalid_memory_model,
7625 "invalid memory model argument %d of %qE", x + 1,
7626 function);
7630 return size_0;
7634 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
7635 at the beginning of the parameter list PARAMS representing the size of the
7636 objects. This is to match the library ABI requirement. LOC is the location
7637 of the function call.
7638 The new function is returned if it needed rebuilding, otherwise NULL_TREE is
7639 returned to allow the external call to be constructed. */
7641 static tree
7642 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
7643 vec<tree, va_gc> *params)
7645 tree size_node;
7647 /* Insert a SIZE_T parameter as the first param. If there isn't
7648 enough space, allocate a new vector and recursively re-build with that. */
7649 if (!params->space (1))
7651 unsigned int z, len;
7652 vec<tree, va_gc> *v;
7653 tree f;
7655 len = params->length ();
7656 vec_alloc (v, len + 1);
7657 v->quick_push (build_int_cst (size_type_node, n));
7658 for (z = 0; z < len; z++)
7659 v->quick_push ((*params)[z]);
7660 f = build_function_call_vec (loc, vNULL, function, v, NULL);
7661 vec_free (v);
7662 return f;
7665 /* Add the size parameter and leave as a function call for processing. */
7666 size_node = build_int_cst (size_type_node, n);
7667 params->quick_insert (0, size_node);
7668 return NULL_TREE;
7672 /* Return whether atomic operations for naturally aligned N-byte
7673 arguments are supported, whether inline or through libatomic. */
7674 static bool
7675 atomic_size_supported_p (int n)
7677 switch (n)
7679 case 1:
7680 case 2:
7681 case 4:
7682 case 8:
7683 return true;
7685 case 16:
7686 return targetm.scalar_mode_supported_p (TImode);
7688 default:
7689 return false;
7693 /* This will process an __atomic_exchange function call, determine whether it
7694 needs to be mapped to the _N variation, or turned into a library call.
7695 LOC is the location of the builtin call.
7696 FUNCTION is the DECL that has been invoked;
7697 PARAMS is the argument list for the call. The return value is non-null
7698 TRUE is returned if it is translated into the proper format for a call to the
7699 external library, and NEW_RETURN is set the tree for that function.
7700 FALSE is returned if processing for the _N variation is required, and
7701 NEW_RETURN is set to the return value the result is copied into. */
7702 static bool
7703 resolve_overloaded_atomic_exchange (location_t loc, tree function,
7704 vec<tree, va_gc> *params, tree *new_return)
7706 tree p0, p1, p2, p3;
7707 tree I_type, I_type_ptr;
7708 int n = get_atomic_generic_size (loc, function, params);
7710 /* Size of 0 is an error condition. */
7711 if (n == 0)
7713 *new_return = error_mark_node;
7714 return true;
7717 /* If not a lock-free size, change to the library generic format. */
7718 if (!atomic_size_supported_p (n))
7720 *new_return = add_atomic_size_parameter (n, loc, function, params);
7721 return true;
7724 /* Otherwise there is a lockfree match, transform the call from:
7725 void fn(T* mem, T* desired, T* return, model)
7726 into
7727 *return = (T) (fn (In* mem, (In) *desired, model)) */
7729 p0 = (*params)[0];
7730 p1 = (*params)[1];
7731 p2 = (*params)[2];
7732 p3 = (*params)[3];
7734 /* Create pointer to appropriate size. */
7735 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7736 I_type_ptr = build_pointer_type (I_type);
7738 /* Convert object pointer to required type. */
7739 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7740 (*params)[0] = p0;
7741 /* Convert new value to required type, and dereference it. */
7742 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7743 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7744 (*params)[1] = p1;
7746 /* Move memory model to the 3rd position, and end param list. */
7747 (*params)[2] = p3;
7748 params->truncate (3);
7750 /* Convert return pointer and dereference it for later assignment. */
7751 *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7753 return false;
7757 /* This will process an __atomic_compare_exchange function call, determine
7758 whether it needs to be mapped to the _N variation, or turned into a lib call.
7759 LOC is the location of the builtin call.
7760 FUNCTION is the DECL that has been invoked;
7761 PARAMS is the argument list for the call. The return value is non-null
7762 TRUE is returned if it is translated into the proper format for a call to the
7763 external library, and NEW_RETURN is set the tree for that function.
7764 FALSE is returned if processing for the _N variation is required. */
7766 static bool
7767 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
7768 vec<tree, va_gc> *params,
7769 tree *new_return)
7771 tree p0, p1, p2;
7772 tree I_type, I_type_ptr;
7773 int n = get_atomic_generic_size (loc, function, params);
7775 /* Size of 0 is an error condition. */
7776 if (n == 0)
7778 *new_return = error_mark_node;
7779 return true;
7782 /* If not a lock-free size, change to the library generic format. */
7783 if (!atomic_size_supported_p (n))
7785 /* The library generic format does not have the weak parameter, so
7786 remove it from the param list. Since a parameter has been removed,
7787 we can be sure that there is room for the SIZE_T parameter, meaning
7788 there will not be a recursive rebuilding of the parameter list, so
7789 there is no danger this will be done twice. */
7790 if (n > 0)
7792 (*params)[3] = (*params)[4];
7793 (*params)[4] = (*params)[5];
7794 params->truncate (5);
7796 *new_return = add_atomic_size_parameter (n, loc, function, params);
7797 return true;
7800 /* Otherwise, there is a match, so the call needs to be transformed from:
7801 bool fn(T* mem, T* desired, T* return, weak, success, failure)
7802 into
7803 bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail) */
7805 p0 = (*params)[0];
7806 p1 = (*params)[1];
7807 p2 = (*params)[2];
7809 /* Create pointer to appropriate size. */
7810 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7811 I_type_ptr = build_pointer_type (I_type);
7813 /* Convert object pointer to required type. */
7814 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7815 (*params)[0] = p0;
7817 /* Convert expected pointer to required type. */
7818 p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
7819 (*params)[1] = p1;
7821 /* Convert desired value to required type, and dereference it. */
7822 p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7823 p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
7824 (*params)[2] = p2;
7826 /* The rest of the parameters are fine. NULL means no special return value
7827 processing.*/
7828 *new_return = NULL;
7829 return false;
7833 /* This will process an __atomic_load function call, determine whether it
7834 needs to be mapped to the _N variation, or turned into a library call.
7835 LOC is the location of the builtin call.
7836 FUNCTION is the DECL that has been invoked;
7837 PARAMS is the argument list for the call. The return value is non-null
7838 TRUE is returned if it is translated into the proper format for a call to the
7839 external library, and NEW_RETURN is set the tree for that function.
7840 FALSE is returned if processing for the _N variation is required, and
7841 NEW_RETURN is set to the return value the result is copied into. */
7843 static bool
7844 resolve_overloaded_atomic_load (location_t loc, tree function,
7845 vec<tree, va_gc> *params, tree *new_return)
7847 tree p0, p1, p2;
7848 tree I_type, I_type_ptr;
7849 int n = get_atomic_generic_size (loc, function, params);
7851 /* Size of 0 is an error condition. */
7852 if (n == 0)
7854 *new_return = error_mark_node;
7855 return true;
7858 /* If not a lock-free size, change to the library generic format. */
7859 if (!atomic_size_supported_p (n))
7861 *new_return = add_atomic_size_parameter (n, loc, function, params);
7862 return true;
7865 /* Otherwise, there is a match, so the call needs to be transformed from:
7866 void fn(T* mem, T* return, model)
7867 into
7868 *return = (T) (fn ((In *) mem, model)) */
7870 p0 = (*params)[0];
7871 p1 = (*params)[1];
7872 p2 = (*params)[2];
7874 /* Create pointer to appropriate size. */
7875 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7876 I_type_ptr = build_pointer_type (I_type);
7878 /* Convert object pointer to required type. */
7879 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7880 (*params)[0] = p0;
7882 /* Move memory model to the 2nd position, and end param list. */
7883 (*params)[1] = p2;
7884 params->truncate (2);
7886 /* Convert return pointer and dereference it for later assignment. */
7887 *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7889 return false;
7893 /* This will process an __atomic_store function call, determine whether it
7894 needs to be mapped to the _N variation, or turned into a library call.
7895 LOC is the location of the builtin call.
7896 FUNCTION is the DECL that has been invoked;
7897 PARAMS is the argument list for the call. The return value is non-null
7898 TRUE is returned if it is translated into the proper format for a call to the
7899 external library, and NEW_RETURN is set the tree for that function.
7900 FALSE is returned if processing for the _N variation is required, and
7901 NEW_RETURN is set to the return value the result is copied into. */
7903 static bool
7904 resolve_overloaded_atomic_store (location_t loc, tree function,
7905 vec<tree, va_gc> *params, tree *new_return)
7907 tree p0, p1;
7908 tree I_type, I_type_ptr;
7909 int n = get_atomic_generic_size (loc, function, params);
7911 /* Size of 0 is an error condition. */
7912 if (n == 0)
7914 *new_return = error_mark_node;
7915 return true;
7918 /* If not a lock-free size, change to the library generic format. */
7919 if (!atomic_size_supported_p (n))
7921 *new_return = add_atomic_size_parameter (n, loc, function, params);
7922 return true;
7925 /* Otherwise, there is a match, so the call needs to be transformed from:
7926 void fn(T* mem, T* value, model)
7927 into
7928 fn ((In *) mem, (In) *value, model) */
7930 p0 = (*params)[0];
7931 p1 = (*params)[1];
7933 /* Create pointer to appropriate size. */
7934 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7935 I_type_ptr = build_pointer_type (I_type);
7937 /* Convert object pointer to required type. */
7938 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7939 (*params)[0] = p0;
7941 /* Convert new value to required type, and dereference it. */
7942 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7943 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7944 (*params)[1] = p1;
7946 /* The memory model is in the right spot already. Return is void. */
7947 *new_return = NULL_TREE;
7949 return false;
7953 /* Emit __atomic*fetch* on _BitInt which doesn't have a size of
7954 1, 2, 4, 8 or 16 bytes using __atomic_compare_exchange loop.
7955 ORIG_CODE is the DECL_FUNCTION_CODE of ORIG_FUNCTION and
7956 ORIG_PARAMS arguments of the call. */
7958 static tree
7959 atomic_bitint_fetch_using_cas_loop (location_t loc,
7960 enum built_in_function orig_code,
7961 tree orig_function,
7962 vec<tree, va_gc> *orig_params)
7964 enum tree_code code = ERROR_MARK;
7965 bool return_old_p = false;
7966 switch (orig_code)
7968 case BUILT_IN_ATOMIC_ADD_FETCH_N:
7969 code = PLUS_EXPR;
7970 break;
7971 case BUILT_IN_ATOMIC_SUB_FETCH_N:
7972 code = MINUS_EXPR;
7973 break;
7974 case BUILT_IN_ATOMIC_AND_FETCH_N:
7975 code = BIT_AND_EXPR;
7976 break;
7977 case BUILT_IN_ATOMIC_NAND_FETCH_N:
7978 break;
7979 case BUILT_IN_ATOMIC_XOR_FETCH_N:
7980 code = BIT_XOR_EXPR;
7981 break;
7982 case BUILT_IN_ATOMIC_OR_FETCH_N:
7983 code = BIT_IOR_EXPR;
7984 break;
7985 case BUILT_IN_ATOMIC_FETCH_ADD_N:
7986 code = PLUS_EXPR;
7987 return_old_p = true;
7988 break;
7989 case BUILT_IN_ATOMIC_FETCH_SUB_N:
7990 code = MINUS_EXPR;
7991 return_old_p = true;
7992 break;
7993 case BUILT_IN_ATOMIC_FETCH_AND_N:
7994 code = BIT_AND_EXPR;
7995 return_old_p = true;
7996 break;
7997 case BUILT_IN_ATOMIC_FETCH_NAND_N:
7998 return_old_p = true;
7999 break;
8000 case BUILT_IN_ATOMIC_FETCH_XOR_N:
8001 code = BIT_XOR_EXPR;
8002 return_old_p = true;
8003 break;
8004 case BUILT_IN_ATOMIC_FETCH_OR_N:
8005 code = BIT_IOR_EXPR;
8006 return_old_p = true;
8007 break;
8008 default:
8009 gcc_unreachable ();
8012 if (orig_params->length () != 3)
8014 if (orig_params->length () < 3)
8015 error_at (loc, "too few arguments to function %qE", orig_function);
8016 else
8017 error_at (loc, "too many arguments to function %qE", orig_function);
8018 return error_mark_node;
8021 tree stmts = push_stmt_list ();
8023 tree nonatomic_lhs_type = TREE_TYPE (TREE_TYPE ((*orig_params)[0]));
8024 nonatomic_lhs_type = TYPE_MAIN_VARIANT (nonatomic_lhs_type);
8025 gcc_assert (TREE_CODE (nonatomic_lhs_type) == BITINT_TYPE);
8027 tree lhs_addr = (*orig_params)[0];
8028 tree val = convert (nonatomic_lhs_type, (*orig_params)[1]);
8029 tree model = convert (integer_type_node, (*orig_params)[2]);
8030 if (TREE_SIDE_EFFECTS (lhs_addr))
8032 tree var = create_tmp_var_raw (TREE_TYPE (lhs_addr));
8033 lhs_addr = build4 (TARGET_EXPR, TREE_TYPE (lhs_addr), var, lhs_addr,
8034 NULL_TREE, NULL_TREE);
8035 add_stmt (lhs_addr);
8037 if (TREE_SIDE_EFFECTS (val))
8039 tree var = create_tmp_var_raw (nonatomic_lhs_type);
8040 val = build4 (TARGET_EXPR, nonatomic_lhs_type, var, val, NULL_TREE,
8041 NULL_TREE);
8042 add_stmt (val);
8044 if (TREE_SIDE_EFFECTS (model))
8046 tree var = create_tmp_var_raw (integer_type_node);
8047 model = build4 (TARGET_EXPR, integer_type_node, var, model, NULL_TREE,
8048 NULL_TREE);
8049 add_stmt (model);
8052 tree old = create_tmp_var_raw (nonatomic_lhs_type);
8053 tree old_addr = build_unary_op (loc, ADDR_EXPR, old, false);
8054 TREE_ADDRESSABLE (old) = 1;
8055 suppress_warning (old);
8057 tree newval = create_tmp_var_raw (nonatomic_lhs_type);
8058 tree newval_addr = build_unary_op (loc, ADDR_EXPR, newval, false);
8059 TREE_ADDRESSABLE (newval) = 1;
8060 suppress_warning (newval);
8062 tree loop_decl = create_artificial_label (loc);
8063 tree loop_label = build1 (LABEL_EXPR, void_type_node, loop_decl);
8065 tree done_decl = create_artificial_label (loc);
8066 tree done_label = build1 (LABEL_EXPR, void_type_node, done_decl);
8068 vec<tree, va_gc> *params;
8069 vec_alloc (params, 6);
8071 /* __atomic_load (addr, &old, SEQ_CST). */
8072 tree fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_LOAD);
8073 params->quick_push (lhs_addr);
8074 params->quick_push (old_addr);
8075 params->quick_push (build_int_cst (integer_type_node, MEMMODEL_RELAXED));
8076 tree func_call = resolve_overloaded_builtin (loc, fndecl, params);
8077 if (func_call == NULL_TREE)
8078 func_call = build_function_call_vec (loc, vNULL, fndecl, params, NULL);
8079 old = build4 (TARGET_EXPR, nonatomic_lhs_type, old, func_call, NULL_TREE,
8080 NULL_TREE);
8081 add_stmt (old);
8082 params->truncate (0);
8084 /* loop: */
8085 add_stmt (loop_label);
8087 /* newval = old + val; */
8088 tree rhs;
8089 switch (code)
8091 case PLUS_EXPR:
8092 case MINUS_EXPR:
8093 if (!TYPE_OVERFLOW_WRAPS (nonatomic_lhs_type))
8095 tree utype
8096 = build_bitint_type (TYPE_PRECISION (nonatomic_lhs_type), 1);
8097 rhs = convert (nonatomic_lhs_type,
8098 build2_loc (loc, code, utype,
8099 convert (utype, old),
8100 convert (utype, val)));
8102 else
8103 rhs = build2_loc (loc, code, nonatomic_lhs_type, old, val);
8104 break;
8105 case BIT_AND_EXPR:
8106 case BIT_IOR_EXPR:
8107 case BIT_XOR_EXPR:
8108 rhs = build2_loc (loc, code, nonatomic_lhs_type, old, val);
8109 break;
8110 case ERROR_MARK:
8111 rhs = build2_loc (loc, BIT_AND_EXPR, nonatomic_lhs_type,
8112 build1_loc (loc, BIT_NOT_EXPR,
8113 nonatomic_lhs_type, old), val);
8114 break;
8115 default:
8116 gcc_unreachable ();
8118 rhs = build4 (TARGET_EXPR, nonatomic_lhs_type, newval, rhs, NULL_TREE,
8119 NULL_TREE);
8120 SET_EXPR_LOCATION (rhs, loc);
8121 add_stmt (rhs);
8123 /* if (__atomic_compare_exchange (addr, &old, &new, false, model, model))
8124 goto done; */
8125 fndecl = builtin_decl_explicit (BUILT_IN_ATOMIC_COMPARE_EXCHANGE);
8126 params->quick_push (lhs_addr);
8127 params->quick_push (old_addr);
8128 params->quick_push (newval_addr);
8129 params->quick_push (integer_zero_node);
8130 params->quick_push (model);
8131 if (tree_fits_uhwi_p (model)
8132 && (tree_to_uhwi (model) == MEMMODEL_RELEASE
8133 || tree_to_uhwi (model) == MEMMODEL_ACQ_REL))
8134 params->quick_push (build_int_cst (integer_type_node, MEMMODEL_RELAXED));
8135 else
8136 params->quick_push (model);
8137 func_call = resolve_overloaded_builtin (loc, fndecl, params);
8138 if (func_call == NULL_TREE)
8139 func_call = build_function_call_vec (loc, vNULL, fndecl, params, NULL);
8141 tree goto_stmt = build1 (GOTO_EXPR, void_type_node, done_decl);
8142 SET_EXPR_LOCATION (goto_stmt, loc);
8144 tree stmt
8145 = build3 (COND_EXPR, void_type_node, func_call, goto_stmt, NULL_TREE);
8146 SET_EXPR_LOCATION (stmt, loc);
8147 add_stmt (stmt);
8149 /* goto loop; */
8150 goto_stmt = build1 (GOTO_EXPR, void_type_node, loop_decl);
8151 SET_EXPR_LOCATION (goto_stmt, loc);
8152 add_stmt (goto_stmt);
8154 /* done: */
8155 add_stmt (done_label);
8157 tree ret = create_tmp_var_raw (nonatomic_lhs_type);
8158 stmt = build2_loc (loc, MODIFY_EXPR, void_type_node, ret,
8159 return_old_p ? old : newval);
8160 add_stmt (stmt);
8162 /* Finish the compound statement. */
8163 stmts = pop_stmt_list (stmts);
8165 return build4 (TARGET_EXPR, nonatomic_lhs_type, ret, stmts, NULL_TREE,
8166 NULL_TREE);
8170 /* Some builtin functions are placeholders for other expressions. This
8171 function should be called immediately after parsing the call expression
8172 before surrounding code has committed to the type of the expression.
8174 LOC is the location of the builtin call.
8176 FUNCTION is the DECL that has been invoked; it is known to be a builtin.
8177 PARAMS is the argument list for the call. The return value is non-null
8178 when expansion is complete, and null if normal processing should
8179 continue. */
8181 tree
8182 resolve_overloaded_builtin (location_t loc, tree function,
8183 vec<tree, va_gc> *params)
8185 /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
8186 Those are not valid to call with a pointer to _Bool (or C++ bool)
8187 and so must be rejected. */
8188 bool fetch_op = true;
8189 bool orig_format = true;
8190 tree new_return = NULL_TREE;
8192 switch (DECL_BUILT_IN_CLASS (function))
8194 case BUILT_IN_NORMAL:
8195 break;
8196 case BUILT_IN_MD:
8197 if (targetm.resolve_overloaded_builtin)
8198 return targetm.resolve_overloaded_builtin (loc, function, params);
8199 else
8200 return NULL_TREE;
8201 default:
8202 return NULL_TREE;
8205 /* Handle BUILT_IN_NORMAL here. */
8206 enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
8207 switch (orig_code)
8209 case BUILT_IN_SPECULATION_SAFE_VALUE_N:
8211 tree new_function, first_param, result;
8212 enum built_in_function fncode
8213 = speculation_safe_value_resolve_call (function, params);
8215 if (fncode == BUILT_IN_NONE)
8216 return error_mark_node;
8218 first_param = (*params)[0];
8219 if (!speculation_safe_value_resolve_params (loc, function, params))
8220 return error_mark_node;
8222 if (targetm.have_speculation_safe_value (true))
8224 new_function = builtin_decl_explicit (fncode);
8225 result = build_function_call_vec (loc, vNULL, new_function, params,
8226 NULL);
8228 if (result == error_mark_node)
8229 return result;
8231 return speculation_safe_value_resolve_return (first_param, result);
8233 else
8235 /* This target doesn't have, or doesn't need, active mitigation
8236 against incorrect speculative execution. Simply return the
8237 first parameter to the builtin. */
8238 if (!targetm.have_speculation_safe_value (false))
8239 /* The user has invoked __builtin_speculation_safe_value
8240 even though __HAVE_SPECULATION_SAFE_VALUE is not
8241 defined: emit a warning. */
8242 warning_at (input_location, 0,
8243 "this target does not define a speculation barrier; "
8244 "your program will still execute correctly, "
8245 "but incorrect speculation may not be "
8246 "restricted");
8248 /* If the optional second argument is present, handle any side
8249 effects now. */
8250 if (params->length () == 2
8251 && TREE_SIDE_EFFECTS ((*params)[1]))
8252 return build2 (COMPOUND_EXPR, TREE_TYPE (first_param),
8253 (*params)[1], first_param);
8255 return first_param;
8259 case BUILT_IN_ATOMIC_EXCHANGE:
8260 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
8261 case BUILT_IN_ATOMIC_LOAD:
8262 case BUILT_IN_ATOMIC_STORE:
8264 /* Handle these 4 together so that they can fall through to the next
8265 case if the call is transformed to an _N variant. */
8266 switch (orig_code)
8268 case BUILT_IN_ATOMIC_EXCHANGE:
8270 if (resolve_overloaded_atomic_exchange (loc, function, params,
8271 &new_return))
8272 return new_return;
8273 /* Change to the _N variant. */
8274 orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
8275 break;
8278 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
8280 if (resolve_overloaded_atomic_compare_exchange (loc, function,
8281 params,
8282 &new_return))
8283 return new_return;
8284 /* Change to the _N variant. */
8285 orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
8286 break;
8288 case BUILT_IN_ATOMIC_LOAD:
8290 if (resolve_overloaded_atomic_load (loc, function, params,
8291 &new_return))
8292 return new_return;
8293 /* Change to the _N variant. */
8294 orig_code = BUILT_IN_ATOMIC_LOAD_N;
8295 break;
8297 case BUILT_IN_ATOMIC_STORE:
8299 if (resolve_overloaded_atomic_store (loc, function, params,
8300 &new_return))
8301 return new_return;
8302 /* Change to the _N variant. */
8303 orig_code = BUILT_IN_ATOMIC_STORE_N;
8304 break;
8306 default:
8307 gcc_unreachable ();
8310 /* FALLTHRU */
8311 case BUILT_IN_ATOMIC_EXCHANGE_N:
8312 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
8313 case BUILT_IN_ATOMIC_LOAD_N:
8314 case BUILT_IN_ATOMIC_STORE_N:
8315 fetch_op = false;
8316 /* FALLTHRU */
8317 case BUILT_IN_ATOMIC_ADD_FETCH_N:
8318 case BUILT_IN_ATOMIC_SUB_FETCH_N:
8319 case BUILT_IN_ATOMIC_AND_FETCH_N:
8320 case BUILT_IN_ATOMIC_NAND_FETCH_N:
8321 case BUILT_IN_ATOMIC_XOR_FETCH_N:
8322 case BUILT_IN_ATOMIC_OR_FETCH_N:
8323 case BUILT_IN_ATOMIC_FETCH_ADD_N:
8324 case BUILT_IN_ATOMIC_FETCH_SUB_N:
8325 case BUILT_IN_ATOMIC_FETCH_AND_N:
8326 case BUILT_IN_ATOMIC_FETCH_NAND_N:
8327 case BUILT_IN_ATOMIC_FETCH_XOR_N:
8328 case BUILT_IN_ATOMIC_FETCH_OR_N:
8329 orig_format = false;
8330 /* FALLTHRU */
8331 case BUILT_IN_SYNC_FETCH_AND_ADD_N:
8332 case BUILT_IN_SYNC_FETCH_AND_SUB_N:
8333 case BUILT_IN_SYNC_FETCH_AND_OR_N:
8334 case BUILT_IN_SYNC_FETCH_AND_AND_N:
8335 case BUILT_IN_SYNC_FETCH_AND_XOR_N:
8336 case BUILT_IN_SYNC_FETCH_AND_NAND_N:
8337 case BUILT_IN_SYNC_ADD_AND_FETCH_N:
8338 case BUILT_IN_SYNC_SUB_AND_FETCH_N:
8339 case BUILT_IN_SYNC_OR_AND_FETCH_N:
8340 case BUILT_IN_SYNC_AND_AND_FETCH_N:
8341 case BUILT_IN_SYNC_XOR_AND_FETCH_N:
8342 case BUILT_IN_SYNC_NAND_AND_FETCH_N:
8343 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
8344 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
8345 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
8346 case BUILT_IN_SYNC_LOCK_RELEASE_N:
8348 /* The following are not _FETCH_OPs and must be accepted with
8349 pointers to _Bool (or C++ bool). */
8350 if (fetch_op)
8351 fetch_op = (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8352 && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
8353 && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
8354 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
8356 int n = sync_resolve_size (function, params, fetch_op, orig_format);
8357 tree new_function, first_param, result;
8358 enum built_in_function fncode;
8360 if (n == 0)
8361 return error_mark_node;
8363 if (n == -1)
8364 return atomic_bitint_fetch_using_cas_loop (loc, orig_code,
8365 function, params);
8367 fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
8368 new_function = builtin_decl_explicit (fncode);
8369 if (!sync_resolve_params (loc, function, new_function, params,
8370 orig_format))
8371 return error_mark_node;
8373 first_param = (*params)[0];
8374 result = build_function_call_vec (loc, vNULL, new_function, params,
8375 NULL);
8376 if (result == error_mark_node)
8377 return result;
8378 if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
8379 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
8380 && orig_code != BUILT_IN_ATOMIC_STORE_N
8381 && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
8382 result = sync_resolve_return (first_param, result, orig_format);
8384 if (fetch_op)
8385 /* Prevent -Wunused-value warning. */
8386 TREE_USED (result) = true;
8388 /* If new_return is set, assign function to that expr and cast the
8389 result to void since the generic interface returned void. */
8390 if (new_return)
8392 /* Cast function result from I{1,2,4,8,16} to the required type. */
8393 result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
8394 result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
8395 result);
8396 TREE_SIDE_EFFECTS (result) = 1;
8397 protected_set_expr_location (result, loc);
8398 result = convert (void_type_node, result);
8400 return result;
8403 default:
8404 return NULL_TREE;
8408 /* vector_types_compatible_elements_p is used in type checks of vectors
8409 values used as operands of binary operators. Where it returns true, and
8410 the other checks of the caller succeed (being vector types in he first
8411 place, and matching number of elements), we can just treat the types
8412 as essentially the same.
8413 Contrast with vector_targets_convertible_p, which is used for vector
8414 pointer types, and vector_types_convertible_p, which will allow
8415 language-specific matches under the control of flag_lax_vector_conversions,
8416 and might still require a conversion. */
8417 /* True if vector types T1 and T2 can be inputs to the same binary
8418 operator without conversion.
8419 We don't check the overall vector size here because some of our callers
8420 want to give different error messages when the vectors are compatible
8421 except for the element count. */
8423 bool
8424 vector_types_compatible_elements_p (tree t1, tree t2)
8426 bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
8427 t1 = TREE_TYPE (t1);
8428 t2 = TREE_TYPE (t2);
8430 enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
8432 gcc_assert ((INTEGRAL_TYPE_P (t1)
8433 || c1 == REAL_TYPE
8434 || c1 == FIXED_POINT_TYPE)
8435 && (INTEGRAL_TYPE_P (t2)
8436 || c2 == REAL_TYPE
8437 || c2 == FIXED_POINT_TYPE));
8439 t1 = c_common_signed_type (t1);
8440 t2 = c_common_signed_type (t2);
8441 /* Equality works here because c_common_signed_type uses
8442 TYPE_MAIN_VARIANT. */
8443 if (t1 == t2)
8444 return true;
8445 if (opaque && c1 == c2
8446 && (INTEGRAL_TYPE_P (t1) || c1 == REAL_TYPE)
8447 && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
8448 return true;
8449 return false;
8452 /* Check for missing format attributes on function pointers. LTYPE is
8453 the new type or left-hand side type. RTYPE is the old type or
8454 right-hand side type. Returns TRUE if LTYPE is missing the desired
8455 attribute. */
8457 bool
8458 check_missing_format_attribute (tree ltype, tree rtype)
8460 tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
8461 tree ra;
8463 for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
8464 if (is_attribute_p ("format", get_attribute_name (ra)))
8465 break;
8466 if (ra)
8468 tree la;
8469 for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
8470 if (is_attribute_p ("format", get_attribute_name (la)))
8471 break;
8472 return !la;
8474 else
8475 return false;
8478 /* Setup a TYPE_DECL node as a typedef representation.
8480 X is a TYPE_DECL for a typedef statement. Create a brand new
8481 ..._TYPE node (which will be just a variant of the existing
8482 ..._TYPE node with identical properties) and then install X
8483 as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
8485 The whole point here is to end up with a situation where each
8486 and every ..._TYPE node the compiler creates will be uniquely
8487 associated with AT MOST one node representing a typedef name.
8488 This way, even though the compiler substitutes corresponding
8489 ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
8490 early on, later parts of the compiler can always do the reverse
8491 translation and get back the corresponding typedef name. For
8492 example, given:
8494 typedef struct S MY_TYPE;
8495 MY_TYPE object;
8497 Later parts of the compiler might only know that `object' was of
8498 type `struct S' if it were not for code just below. With this
8499 code however, later parts of the compiler see something like:
8501 struct S' == struct S
8502 typedef struct S' MY_TYPE;
8503 struct S' object;
8505 And they can then deduce (from the node for type struct S') that
8506 the original object declaration was:
8508 MY_TYPE object;
8510 Being able to do this is important for proper support of protoize,
8511 and also for generating precise symbolic debugging information
8512 which takes full account of the programmer's (typedef) vocabulary.
8514 Obviously, we don't want to generate a duplicate ..._TYPE node if
8515 the TYPE_DECL node that we are now processing really represents a
8516 standard built-in type. */
8518 void
8519 set_underlying_type (tree x)
8521 if (x == error_mark_node || TREE_TYPE (x) == error_mark_node)
8522 return;
8523 if (DECL_IS_UNDECLARED_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
8525 if (TYPE_NAME (TREE_TYPE (x)) == 0)
8526 TYPE_NAME (TREE_TYPE (x)) = x;
8528 else if (DECL_ORIGINAL_TYPE (x))
8529 gcc_checking_assert (TYPE_NAME (TREE_TYPE (x)) == x);
8530 else
8532 tree tt = TREE_TYPE (x);
8533 DECL_ORIGINAL_TYPE (x) = tt;
8534 tt = build_variant_type_copy (tt);
8535 TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
8536 TYPE_NAME (tt) = x;
8538 /* Mark the type as used only when its type decl is decorated
8539 with attribute unused. */
8540 if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
8541 TREE_USED (tt) = 1;
8543 TREE_TYPE (x) = tt;
8547 /* Return true if it is worth exposing the DECL_ORIGINAL_TYPE of TYPE to
8548 the user in diagnostics, false if it would be better to use TYPE itself.
8549 TYPE is known to satisfy typedef_variant_p. */
8551 bool
8552 user_facing_original_type_p (const_tree type)
8554 gcc_assert (typedef_variant_p (type));
8555 tree decl = TYPE_NAME (type);
8557 /* Look through any typedef in "user" code. */
8558 if (!DECL_IN_SYSTEM_HEADER (decl) && !DECL_IS_UNDECLARED_BUILTIN (decl))
8559 return true;
8561 /* If the original type is also named and is in the user namespace,
8562 assume it too is a user-facing type. */
8563 tree orig_type = DECL_ORIGINAL_TYPE (decl);
8564 if (tree orig_id = TYPE_IDENTIFIER (orig_type))
8565 if (!name_reserved_for_implementation_p (IDENTIFIER_POINTER (orig_id)))
8566 return true;
8568 switch (TREE_CODE (orig_type))
8570 /* Don't look through to an anonymous vector type, since the syntax
8571 we use for them in diagnostics isn't real C or C++ syntax.
8572 And if ORIG_TYPE is named but in the implementation namespace,
8573 TYPE is likely to be more meaningful to the user. */
8574 case VECTOR_TYPE:
8575 return false;
8577 /* Don't expose anonymous tag types that are presumably meant to be
8578 known by their typedef name. Also don't expose tags that are in
8579 the implementation namespace, such as:
8581 typedef struct __foo foo; */
8582 case RECORD_TYPE:
8583 case UNION_TYPE:
8584 case ENUMERAL_TYPE:
8585 return false;
8587 /* Look through to anything else. */
8588 default:
8589 return true;
8593 /* Record the types used by the current global variable declaration
8594 being parsed, so that we can decide later to emit their debug info.
8595 Those types are in types_used_by_cur_var_decl, and we are going to
8596 store them in the types_used_by_vars_hash hash table.
8597 DECL is the declaration of the global variable that has been parsed. */
8599 void
8600 record_types_used_by_current_var_decl (tree decl)
8602 gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
8604 while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
8606 tree type = types_used_by_cur_var_decl->pop ();
8607 types_used_by_var_decl_insert (type, decl);
8611 /* The C and C++ parsers both use vectors to hold function arguments.
8612 For efficiency, we keep a cache of unused vectors. This is the
8613 cache. */
8615 typedef vec<tree, va_gc> *tree_gc_vec;
8616 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
8618 /* Return a new vector from the cache. If the cache is empty,
8619 allocate a new vector. These vectors are GC'ed, so it is OK if the
8620 pointer is not released.. */
8622 vec<tree, va_gc> *
8623 make_tree_vector (void)
8625 if (tree_vector_cache && !tree_vector_cache->is_empty ())
8626 return tree_vector_cache->pop ();
8627 else
8629 /* Passing 0 to vec::alloc returns NULL, and our callers require
8630 that we always return a non-NULL value. The vector code uses
8631 4 when growing a NULL vector, so we do too. */
8632 vec<tree, va_gc> *v;
8633 vec_alloc (v, 4);
8634 return v;
8638 /* Release a vector of trees back to the cache. */
8640 void
8641 release_tree_vector (vec<tree, va_gc> *vec)
8643 if (vec != NULL)
8645 if (vec->allocated () >= 16)
8646 /* Don't cache vecs that have expanded more than once. On a p64
8647 target, vecs double in alloc size with each power of 2 elements, e.g
8648 at 16 elements the alloc increases from 128 to 256 bytes. */
8649 vec_free (vec);
8650 else
8652 vec->truncate (0);
8653 vec_safe_push (tree_vector_cache, vec);
8658 /* Get a new tree vector holding a single tree. */
8660 vec<tree, va_gc> *
8661 make_tree_vector_single (tree t)
8663 vec<tree, va_gc> *ret = make_tree_vector ();
8664 ret->quick_push (t);
8665 return ret;
8668 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain. */
8670 vec<tree, va_gc> *
8671 make_tree_vector_from_list (tree list)
8673 vec<tree, va_gc> *ret = make_tree_vector ();
8674 for (; list; list = TREE_CHAIN (list))
8675 vec_safe_push (ret, TREE_VALUE (list));
8676 return ret;
8679 /* Get a new tree vector of the values of a CONSTRUCTOR. */
8681 vec<tree, va_gc> *
8682 make_tree_vector_from_ctor (tree ctor)
8684 vec<tree,va_gc> *ret = make_tree_vector ();
8685 vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
8686 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
8687 ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
8688 return ret;
8691 /* Get a new tree vector which is a copy of an existing one. */
8693 vec<tree, va_gc> *
8694 make_tree_vector_copy (const vec<tree, va_gc> *orig)
8696 vec<tree, va_gc> *ret;
8697 unsigned int ix;
8698 tree t;
8700 ret = make_tree_vector ();
8701 vec_safe_reserve (ret, vec_safe_length (orig));
8702 FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
8703 ret->quick_push (t);
8704 return ret;
8707 /* Return true if KEYWORD starts a type specifier. */
8709 bool
8710 keyword_begins_type_specifier (enum rid keyword)
8712 switch (keyword)
8714 case RID_AUTO_TYPE:
8715 case RID_INT:
8716 case RID_CHAR:
8717 case RID_FLOAT:
8718 case RID_DOUBLE:
8719 case RID_VOID:
8720 case RID_UNSIGNED:
8721 case RID_LONG:
8722 case RID_SHORT:
8723 case RID_SIGNED:
8724 CASE_RID_FLOATN_NX:
8725 case RID_DFLOAT32:
8726 case RID_DFLOAT64:
8727 case RID_DFLOAT128:
8728 case RID_FRACT:
8729 case RID_ACCUM:
8730 case RID_BOOL:
8731 case RID_BITINT:
8732 case RID_WCHAR:
8733 case RID_CHAR8:
8734 case RID_CHAR16:
8735 case RID_CHAR32:
8736 case RID_SAT:
8737 case RID_COMPLEX:
8738 case RID_TYPEOF:
8739 case RID_STRUCT:
8740 case RID_CLASS:
8741 case RID_UNION:
8742 case RID_ENUM:
8743 return true;
8744 default:
8745 if (keyword >= RID_FIRST_INT_N
8746 && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
8747 && int_n_enabled_p[keyword-RID_FIRST_INT_N])
8748 return true;
8749 return false;
8753 /* Return true if KEYWORD names a type qualifier. */
8755 bool
8756 keyword_is_type_qualifier (enum rid keyword)
8758 switch (keyword)
8760 case RID_CONST:
8761 case RID_VOLATILE:
8762 case RID_RESTRICT:
8763 case RID_ATOMIC:
8764 return true;
8765 default:
8766 return false;
8770 /* Return true if KEYWORD names a storage class specifier.
8772 RID_TYPEDEF is not included in this list despite `typedef' being
8773 listed in C99 6.7.1.1. 6.7.1.3 indicates that `typedef' is listed as
8774 such for syntactic convenience only. */
8776 bool
8777 keyword_is_storage_class_specifier (enum rid keyword)
8779 switch (keyword)
8781 case RID_STATIC:
8782 case RID_EXTERN:
8783 case RID_REGISTER:
8784 case RID_AUTO:
8785 case RID_MUTABLE:
8786 case RID_THREAD:
8787 return true;
8788 default:
8789 return false;
8793 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec]. */
8795 static bool
8796 keyword_is_function_specifier (enum rid keyword)
8798 switch (keyword)
8800 case RID_INLINE:
8801 case RID_NORETURN:
8802 case RID_VIRTUAL:
8803 case RID_EXPLICIT:
8804 return true;
8805 default:
8806 return false;
8810 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
8811 declaration-specifier (C99 6.7). */
8813 bool
8814 keyword_is_decl_specifier (enum rid keyword)
8816 if (keyword_is_storage_class_specifier (keyword)
8817 || keyword_is_type_qualifier (keyword)
8818 || keyword_is_function_specifier (keyword))
8819 return true;
8821 switch (keyword)
8823 case RID_TYPEDEF:
8824 case RID_FRIEND:
8825 case RID_CONSTEXPR:
8826 case RID_CONSTINIT:
8827 return true;
8828 default:
8829 return false;
8833 /* Initialize language-specific-bits of tree_contains_struct. */
8835 void
8836 c_common_init_ts (void)
8838 MARK_TS_EXP (SIZEOF_EXPR);
8839 MARK_TS_EXP (PAREN_SIZEOF_EXPR);
8840 MARK_TS_EXP (C_MAYBE_CONST_EXPR);
8841 MARK_TS_EXP (EXCESS_PRECISION_EXPR);
8842 MARK_TS_EXP (BREAK_STMT);
8843 MARK_TS_EXP (CONTINUE_STMT);
8844 MARK_TS_EXP (DO_STMT);
8845 MARK_TS_EXP (FOR_STMT);
8846 MARK_TS_EXP (SWITCH_STMT);
8847 MARK_TS_EXP (WHILE_STMT);
8849 MARK_TS_DECL_COMMON (CONCEPT_DECL);
8852 /* Build a user-defined numeric literal out of an integer constant type VALUE
8853 with identifier SUFFIX. */
8855 tree
8856 build_userdef_literal (tree suffix_id, tree value,
8857 enum overflow_type overflow, tree num_string)
8859 tree literal = make_node (USERDEF_LITERAL);
8860 USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
8861 USERDEF_LITERAL_VALUE (literal) = value;
8862 USERDEF_LITERAL_OVERFLOW (literal) = overflow;
8863 USERDEF_LITERAL_NUM_STRING (literal) = num_string;
8864 return literal;
8867 /* For vector[index], convert the vector to an array of the underlying type.
8868 Return true if the resulting ARRAY_REF should not be an lvalue. */
8870 bool
8871 convert_vector_to_array_for_subscript (location_t loc,
8872 tree *vecp, tree index)
8874 bool ret = false;
8875 if (gnu_vector_type_p (TREE_TYPE (*vecp)))
8877 tree type = TREE_TYPE (*vecp);
8879 ret = !lvalue_p (*vecp);
8881 index = fold_for_warn (index);
8882 if (TREE_CODE (index) == INTEGER_CST)
8883 if (!tree_fits_uhwi_p (index)
8884 || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
8885 warning_at (loc, OPT_Warray_bounds_, "index value is out of bound");
8887 /* We are building an ARRAY_REF so mark the vector as addressable
8888 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
8889 for function parameters. */
8890 c_common_mark_addressable_vec (*vecp);
8892 *vecp = build1 (VIEW_CONVERT_EXPR,
8893 build_array_type_nelts (TREE_TYPE (type),
8894 TYPE_VECTOR_SUBPARTS (type)),
8895 *vecp);
8897 return ret;
8900 /* Determine which of the operands, if any, is a scalar that needs to be
8901 converted to a vector, for the range of operations. */
8902 enum stv_conv
8903 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
8904 bool complain)
8906 tree type0 = TREE_TYPE (op0);
8907 tree type1 = TREE_TYPE (op1);
8908 bool integer_only_op = false;
8909 enum stv_conv ret = stv_firstarg;
8911 gcc_assert (gnu_vector_type_p (type0) || gnu_vector_type_p (type1));
8912 switch (code)
8914 /* Most GENERIC binary expressions require homogeneous arguments.
8915 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
8916 argument that is a vector and a second one that is a scalar, so
8917 we never return stv_secondarg for them. */
8918 case RSHIFT_EXPR:
8919 case LSHIFT_EXPR:
8920 if (TREE_CODE (type0) == INTEGER_TYPE
8921 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8923 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8924 NULL_TREE, false))
8926 if (complain)
8927 error_at (loc, "conversion of scalar %qT to vector %qT "
8928 "involves truncation", type0, type1);
8929 return stv_error;
8931 else
8932 return stv_firstarg;
8934 break;
8936 case BIT_IOR_EXPR:
8937 case BIT_XOR_EXPR:
8938 case BIT_AND_EXPR:
8939 integer_only_op = true;
8940 /* fall through */
8942 case VEC_COND_EXPR:
8944 case PLUS_EXPR:
8945 case MINUS_EXPR:
8946 case MULT_EXPR:
8947 case TRUNC_DIV_EXPR:
8948 case CEIL_DIV_EXPR:
8949 case FLOOR_DIV_EXPR:
8950 case ROUND_DIV_EXPR:
8951 case EXACT_DIV_EXPR:
8952 case TRUNC_MOD_EXPR:
8953 case FLOOR_MOD_EXPR:
8954 case RDIV_EXPR:
8955 case EQ_EXPR:
8956 case NE_EXPR:
8957 case LE_EXPR:
8958 case GE_EXPR:
8959 case LT_EXPR:
8960 case GT_EXPR:
8961 /* What about UNLT_EXPR? */
8962 if (gnu_vector_type_p (type0))
8964 ret = stv_secondarg;
8965 std::swap (type0, type1);
8966 std::swap (op0, op1);
8969 if (TREE_CODE (type0) == INTEGER_TYPE
8970 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8972 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8973 NULL_TREE, false))
8975 if (complain)
8976 error_at (loc, "conversion of scalar %qT to vector %qT "
8977 "involves truncation", type0, type1);
8978 return stv_error;
8980 return ret;
8982 else if (!integer_only_op
8983 /* Allow integer --> real conversion if safe. */
8984 && (SCALAR_FLOAT_TYPE_P (type0)
8985 || TREE_CODE (type0) == INTEGER_TYPE)
8986 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
8988 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8989 NULL_TREE, false))
8991 if (complain)
8992 error_at (loc, "conversion of scalar %qT to vector %qT "
8993 "involves truncation", type0, type1);
8994 return stv_error;
8996 return ret;
8998 default:
8999 break;
9002 return stv_nothing;
9005 /* Return the alignment of std::max_align_t.
9007 [support.types.layout] The type max_align_t is a POD type whose alignment
9008 requirement is at least as great as that of every scalar type, and whose
9009 alignment requirement is supported in every context. */
9011 unsigned
9012 max_align_t_align ()
9014 unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
9015 TYPE_ALIGN (long_double_type_node));
9016 if (float128_type_node != NULL_TREE)
9017 max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
9018 return max_align;
9021 /* Return true iff ALIGN is an integral constant that is a fundamental
9022 alignment, as defined by [basic.align] in the c++-11
9023 specifications.
9025 That is:
9027 [A fundamental alignment is represented by an alignment less than or
9028 equal to the greatest alignment supported by the implementation
9029 in all contexts, which is equal to alignof(max_align_t)]. */
9031 bool
9032 cxx_fundamental_alignment_p (unsigned align)
9034 return (align <= max_align_t_align ());
9037 /* Return true if T is a pointer to a zero-sized aggregate. */
9039 bool
9040 pointer_to_zero_sized_aggr_p (tree t)
9042 if (!POINTER_TYPE_P (t))
9043 return false;
9044 t = TREE_TYPE (t);
9045 return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
9048 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
9049 with no library fallback or for an ADDR_EXPR whose operand is such type
9050 issues an error pointing to the location LOC.
9051 Returns true when the expression has been diagnosed and false
9052 otherwise. */
9054 bool
9055 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
9057 if (TREE_CODE (expr) == ADDR_EXPR)
9058 expr = TREE_OPERAND (expr, 0);
9060 STRIP_ANY_LOCATION_WRAPPER (expr);
9062 if (TREE_TYPE (expr)
9063 && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
9064 && TREE_CODE (expr) == FUNCTION_DECL
9065 /* The intersection of DECL_BUILT_IN and DECL_IS_UNDECLARED_BUILTIN avoids
9066 false positives for user-declared built-ins such as abs or
9067 strlen, and for C++ operators new and delete.
9068 The c_decl_implicit() test avoids false positives for implicitly
9069 declared built-ins with library fallbacks (such as abs). */
9070 && fndecl_built_in_p (expr)
9071 && DECL_IS_UNDECLARED_BUILTIN (expr)
9072 && !c_decl_implicit (expr)
9073 && !DECL_ASSEMBLER_NAME_SET_P (expr))
9075 if (loc == UNKNOWN_LOCATION)
9076 loc = EXPR_LOC_OR_LOC (expr, input_location);
9078 /* Reject arguments that are built-in functions with
9079 no library fallback. */
9080 error_at (loc, "built-in function %qE must be directly called", expr);
9082 return true;
9085 return false;
9088 /* Issue an ERROR for an invalid SIZE of array NAME which is null
9089 for unnamed arrays. */
9091 void
9092 invalid_array_size_error (location_t loc, cst_size_error error,
9093 const_tree size, const_tree name)
9095 tree maxsize = max_object_size ();
9096 switch (error)
9098 case cst_size_not_constant:
9099 if (name)
9100 error_at (loc, "size of array %qE is not a constant expression",
9101 name);
9102 else
9103 error_at (loc, "size of array is not a constant expression");
9104 break;
9105 case cst_size_negative:
9106 if (name)
9107 error_at (loc, "size %qE of array %qE is negative",
9108 size, name);
9109 else
9110 error_at (loc, "size %qE of array is negative",
9111 size);
9112 break;
9113 case cst_size_too_big:
9114 if (name)
9115 error_at (loc, "size %qE of array %qE exceeds maximum "
9116 "object size %qE", size, name, maxsize);
9117 else
9118 error_at (loc, "size %qE of array exceeds maximum "
9119 "object size %qE", size, maxsize);
9120 break;
9121 case cst_size_overflow:
9122 if (name)
9123 error_at (loc, "size of array %qE exceeds maximum "
9124 "object size %qE", name, maxsize);
9125 else
9126 error_at (loc, "size of array exceeds maximum "
9127 "object size %qE", maxsize);
9128 break;
9129 default:
9130 gcc_unreachable ();
9134 /* Check if array size calculations overflow or if the array covers more
9135 than half of the address space. Return true if the size of the array
9136 is valid, false otherwise. T is either the type of the array or its
9137 size, and NAME is the name of the array, or null for unnamed arrays. */
9139 bool
9140 valid_array_size_p (location_t loc, const_tree t, tree name, bool complain)
9142 if (t == error_mark_node)
9143 return true;
9145 const_tree size;
9146 if (TYPE_P (t))
9148 if (!COMPLETE_TYPE_P (t))
9149 return true;
9150 size = TYPE_SIZE_UNIT (t);
9152 else
9153 size = t;
9155 if (TREE_CODE (size) != INTEGER_CST)
9156 return true;
9158 cst_size_error error;
9159 if (valid_constant_size_p (size, &error))
9160 return true;
9162 if (!complain)
9163 return false;
9165 if (TREE_CODE (TREE_TYPE (size)) == ENUMERAL_TYPE)
9166 /* Show the value of the enumerator rather than its name. */
9167 size = convert (ssizetype, const_cast<tree> (size));
9169 invalid_array_size_error (loc, error, size, name);
9170 return false;
9173 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
9174 timestamp to replace embedded current dates to get reproducible
9175 results. Returns -1 if SOURCE_DATE_EPOCH is not defined. */
9177 time_t
9178 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
9180 char *source_date_epoch;
9181 int64_t epoch;
9182 char *endptr;
9184 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
9185 if (!source_date_epoch)
9186 return (time_t) -1;
9188 errno = 0;
9189 #if defined(INT64_T_IS_LONG)
9190 epoch = strtol (source_date_epoch, &endptr, 10);
9191 #else
9192 epoch = strtoll (source_date_epoch, &endptr, 10);
9193 #endif
9194 if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
9195 || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
9197 error_at (input_location, "environment variable %qs must "
9198 "expand to a non-negative integer less than or equal to %wd",
9199 "SOURCE_DATE_EPOCH", MAX_SOURCE_DATE_EPOCH);
9200 return (time_t) -1;
9203 return (time_t) epoch;
9206 /* Callback for libcpp for offering spelling suggestions for misspelled
9207 directives. GOAL is an unrecognized string; CANDIDATES is a
9208 NULL-terminated array of candidate strings. Return the closest
9209 match to GOAL within CANDIDATES, or NULL if none are good
9210 suggestions. */
9212 const char *
9213 cb_get_suggestion (cpp_reader *, const char *goal,
9214 const char *const *candidates)
9216 best_match<const char *, const char *> bm (goal);
9217 while (*candidates)
9218 bm.consider (*candidates++);
9219 return bm.get_best_meaningful_candidate ();
9222 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
9223 modes X, Y. This isn't just >, as the FLT_EVAL_METHOD values added
9224 by C TS 18661-3 for interchange types that are computed in their
9225 native precision are larger than the C11 values for evaluating in the
9226 precision of float/double/long double. If either mode is
9227 FLT_EVAL_METHOD_UNPREDICTABLE, return that. */
9229 enum flt_eval_method
9230 excess_precision_mode_join (enum flt_eval_method x,
9231 enum flt_eval_method y)
9233 if (x == FLT_EVAL_METHOD_UNPREDICTABLE
9234 || y == FLT_EVAL_METHOD_UNPREDICTABLE)
9235 return FLT_EVAL_METHOD_UNPREDICTABLE;
9237 /* GCC only supports one interchange type right now, _Float16. If
9238 we're evaluating _Float16 in 16-bit precision, then flt_eval_method
9239 will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
9240 if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
9241 return y;
9242 if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
9243 return x;
9245 /* Other values for flt_eval_method are directly comparable, and we want
9246 the maximum. */
9247 return MAX (x, y);
9250 /* Return the value that should be set for FLT_EVAL_METHOD in the
9251 context of ISO/IEC TS 18861-3.
9253 This relates to the effective excess precision seen by the user,
9254 which is the join point of the precision the target requests for
9255 -fexcess-precision={standard,fast,16} and the implicit excess precision
9256 the target uses. */
9258 static enum flt_eval_method
9259 c_ts18661_flt_eval_method (void)
9261 enum flt_eval_method implicit
9262 = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
9264 enum excess_precision_type flag_type
9265 = (flag_excess_precision == EXCESS_PRECISION_STANDARD
9266 ? EXCESS_PRECISION_TYPE_STANDARD
9267 : (flag_excess_precision == EXCESS_PRECISION_FLOAT16
9268 ? EXCESS_PRECISION_TYPE_FLOAT16
9269 : EXCESS_PRECISION_TYPE_FAST));
9271 enum flt_eval_method requested
9272 = targetm.c.excess_precision (flag_type);
9274 return excess_precision_mode_join (implicit, requested);
9277 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
9278 those that were permitted by C11. That is to say, eliminates
9279 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
9281 static enum flt_eval_method
9282 c_c11_flt_eval_method (void)
9284 return excess_precision_mode_join (c_ts18661_flt_eval_method (),
9285 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
9288 /* Return the value that should be set for FLT_EVAL_METHOD.
9289 MAYBE_C11_ONLY_P is TRUE if we should check
9290 FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
9291 values we can return to those from C99/C11, and FALSE otherwise.
9292 See the comments on c_ts18661_flt_eval_method for what value we choose
9293 to set here. */
9296 c_flt_eval_method (bool maybe_c11_only_p)
9298 if (maybe_c11_only_p
9299 && flag_permitted_flt_eval_methods
9300 == PERMITTED_FLT_EVAL_METHODS_C11)
9301 return c_c11_flt_eval_method ();
9302 else
9303 return c_ts18661_flt_eval_method ();
9306 /* An enum for get_missing_token_insertion_kind for describing the best
9307 place to insert a missing token, if there is one. */
9309 enum missing_token_insertion_kind
9311 MTIK_IMPOSSIBLE,
9312 MTIK_INSERT_BEFORE_NEXT,
9313 MTIK_INSERT_AFTER_PREV
9316 /* Given a missing token of TYPE, determine if it is reasonable to
9317 emit a fix-it hint suggesting the insertion of the token, and,
9318 if so, where the token should be inserted relative to other tokens.
9320 It only makes sense to do this for values of TYPE that are symbols.
9322 Some symbols should go before the next token, e.g. in:
9323 if flag)
9324 we want to insert the missing '(' immediately before "flag",
9325 giving:
9326 if (flag)
9327 rather than:
9328 if( flag)
9329 These use MTIK_INSERT_BEFORE_NEXT.
9331 Other symbols should go after the previous token, e.g. in:
9332 if (flag
9333 do_something ();
9334 we want to insert the missing ')' immediately after the "flag",
9335 giving:
9336 if (flag)
9337 do_something ();
9338 rather than:
9339 if (flag
9340 )do_something ();
9341 These use MTIK_INSERT_AFTER_PREV. */
9343 static enum missing_token_insertion_kind
9344 get_missing_token_insertion_kind (enum cpp_ttype type)
9346 switch (type)
9348 /* Insert missing "opening" brackets immediately
9349 before the next token. */
9350 case CPP_OPEN_SQUARE:
9351 case CPP_OPEN_PAREN:
9352 return MTIK_INSERT_BEFORE_NEXT;
9354 /* Insert other missing symbols immediately after
9355 the previous token. */
9356 case CPP_CLOSE_PAREN:
9357 case CPP_CLOSE_SQUARE:
9358 case CPP_SEMICOLON:
9359 case CPP_COMMA:
9360 case CPP_COLON:
9361 return MTIK_INSERT_AFTER_PREV;
9363 /* Other kinds of token don't get fix-it hints. */
9364 default:
9365 return MTIK_IMPOSSIBLE;
9369 /* Given RICHLOC, a location for a diagnostic describing a missing token
9370 of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
9371 insertion of the token.
9373 The location of the attempted fix-it hint depends on TOKEN_TYPE:
9374 it will either be:
9375 (a) immediately after PREV_TOKEN_LOC, or
9377 (b) immediately before the primary location within RICHLOC (taken to
9378 be that of the token following where the token was expected).
9380 If we manage to add a fix-it hint, then the location of the
9381 fix-it hint is likely to be more useful as the primary location
9382 of the diagnostic than that of the following token, so we swap
9383 these locations.
9385 For example, given this bogus code:
9386 123456789012345678901234567890
9387 1 | int missing_semicolon (void)
9388 2 | {
9389 3 | return 42
9390 4 | }
9392 we will emit:
9394 "expected ';' before '}'"
9396 RICHLOC's primary location is at the closing brace, so before "swapping"
9397 we would emit the error at line 4 column 1:
9399 123456789012345678901234567890
9400 3 | return 42 |< fix-it hint emitted for this line
9401 | ; |
9402 4 | } |< "expected ';' before '}'" emitted at this line
9403 | ^ |
9405 It's more useful for the location of the diagnostic to be at the
9406 fix-it hint, so we swap the locations, so the primary location
9407 is at the fix-it hint, with the old primary location inserted
9408 as a secondary location, giving this, with the error at line 3
9409 column 12:
9411 123456789012345678901234567890
9412 3 | return 42 |< "expected ';' before '}'" emitted at this line,
9413 | ^ | with fix-it hint
9414 4 | ; |
9415 | } |< secondary range emitted here
9416 | ~ |. */
9418 void
9419 maybe_suggest_missing_token_insertion (rich_location *richloc,
9420 enum cpp_ttype token_type,
9421 location_t prev_token_loc)
9423 gcc_assert (richloc);
9425 enum missing_token_insertion_kind mtik
9426 = get_missing_token_insertion_kind (token_type);
9428 switch (mtik)
9430 default:
9431 gcc_unreachable ();
9432 break;
9434 case MTIK_IMPOSSIBLE:
9435 return;
9437 case MTIK_INSERT_BEFORE_NEXT:
9438 /* Attempt to add the fix-it hint before the primary location
9439 of RICHLOC. */
9440 richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
9441 break;
9443 case MTIK_INSERT_AFTER_PREV:
9444 /* Attempt to add the fix-it hint after PREV_TOKEN_LOC. */
9445 richloc->add_fixit_insert_after (prev_token_loc,
9446 cpp_type2name (token_type, 0));
9447 break;
9450 /* If we were successful, use the fix-it hint's location as the
9451 primary location within RICHLOC, adding the old primary location
9452 back as a secondary location. */
9453 if (!richloc->seen_impossible_fixit_p ())
9455 fixit_hint *hint = richloc->get_last_fixit_hint ();
9456 location_t hint_loc = hint->get_start_loc ();
9457 location_t old_loc = richloc->get_loc ();
9459 richloc->set_range (0, hint_loc, SHOW_RANGE_WITH_CARET);
9460 richloc->add_range (old_loc);
9464 #if CHECKING_P
9466 namespace selftest {
9468 /* Verify that fold_for_warn on error_mark_node is safe. */
9470 static void
9471 test_fold_for_warn ()
9473 ASSERT_EQ (error_mark_node, fold_for_warn (error_mark_node));
9476 /* Run all of the selftests within this file. */
9478 static void
9479 c_common_cc_tests ()
9481 test_fold_for_warn ();
9484 /* Run all of the tests within c-family. */
9486 void
9487 c_family_tests (void)
9489 c_common_cc_tests ();
9490 c_format_cc_tests ();
9491 c_indentation_cc_tests ();
9492 c_pretty_print_cc_tests ();
9493 c_spellcheck_cc_tests ();
9494 c_diagnostic_cc_tests ();
9495 c_opt_problem_cc_tests ();
9498 } // namespace selftest
9500 #endif /* #if CHECKING_P */
9502 /* Attempt to locate a suitable location within FILE for a
9503 #include directive to be inserted before.
9504 LOC is the location of the relevant diagnostic.
9506 Attempt to return the location within FILE immediately
9507 after the last #include within that file, or the start of
9508 that file if it has no #include directives.
9510 Return UNKNOWN_LOCATION if no suitable location is found,
9511 or if an error occurs. */
9513 static location_t
9514 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
9516 /* Locate the last ordinary map within FILE that ended with a #include. */
9517 const line_map_ordinary *last_include_ord_map = NULL;
9519 /* ...and the next ordinary map within FILE after that one. */
9520 const line_map_ordinary *last_ord_map_after_include = NULL;
9522 /* ...and the first ordinary map within FILE. */
9523 const line_map_ordinary *first_ord_map_in_file = NULL;
9525 /* Get ordinary map containing LOC (or its expansion). */
9526 const line_map_ordinary *ord_map_for_loc = NULL;
9527 linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
9528 &ord_map_for_loc);
9529 gcc_assert (ord_map_for_loc);
9531 for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
9533 const line_map_ordinary *ord_map
9534 = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
9536 if (const line_map_ordinary *from
9537 = linemap_included_from_linemap (line_table, ord_map))
9538 /* We cannot use pointer equality, because with preprocessed
9539 input all filename strings are unique. */
9540 if (0 == strcmp (from->to_file, file))
9542 last_include_ord_map = from;
9543 last_ord_map_after_include = NULL;
9546 /* Likewise, use strcmp, and reject any line-zero introductory
9547 map. */
9548 if (ord_map->to_line && 0 == strcmp (ord_map->to_file, file))
9550 if (!first_ord_map_in_file)
9551 first_ord_map_in_file = ord_map;
9552 if (last_include_ord_map && !last_ord_map_after_include)
9553 last_ord_map_after_include = ord_map;
9556 /* Stop searching when reaching the ord_map containing LOC,
9557 as it makes no sense to provide fix-it hints that appear
9558 after the diagnostic in question. */
9559 if (ord_map == ord_map_for_loc)
9560 break;
9563 /* Determine where to insert the #include. */
9564 const line_map_ordinary *ord_map_for_insertion;
9566 /* We want the next ordmap in the file after the last one that's a
9567 #include, but failing that, the start of the file. */
9568 if (last_ord_map_after_include)
9569 ord_map_for_insertion = last_ord_map_after_include;
9570 else
9571 ord_map_for_insertion = first_ord_map_in_file;
9573 if (!ord_map_for_insertion)
9574 return UNKNOWN_LOCATION;
9576 /* The "start_location" is column 0, meaning "the whole line".
9577 rich_location and edit_context can't cope with this, so use
9578 column 1 instead. */
9579 location_t col_0 = ord_map_for_insertion->start_location;
9580 return linemap_position_for_loc_and_offset (line_table, col_0, 1);
9583 /* A map from filenames to sets of headers added to them, for
9584 ensuring idempotency within maybe_add_include_fixit. */
9586 /* The values within the map. We need string comparison as there's
9587 no guarantee that two different diagnostics that are recommending
9588 adding e.g. "<stdio.h>" are using the same buffer. */
9590 typedef hash_set <const char *, false, nofree_string_hash> per_file_includes_t;
9592 /* The map itself. We don't need string comparison for the filename keys,
9593 as they come from libcpp. */
9595 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
9596 static added_includes_t *added_includes;
9598 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
9599 in a suitable location within the file of RICHLOC's primary
9600 location.
9602 This function is idempotent: a header will be added at most once to
9603 any given file.
9605 If OVERRIDE_LOCATION is true, then if a fix-it is added and will be
9606 printed, then RICHLOC's primary location will be replaced by that of
9607 the fix-it hint (for use by "inform" notes where the location of the
9608 issue has already been reported). */
9610 void
9611 maybe_add_include_fixit (rich_location *richloc, const char *header,
9612 bool override_location)
9614 location_t loc = richloc->get_loc ();
9615 const char *file = LOCATION_FILE (loc);
9616 if (!file)
9617 return;
9619 /* Idempotency: don't add the same header more than once to a given file. */
9620 if (!added_includes)
9621 added_includes = new added_includes_t ();
9622 per_file_includes_t *&set = added_includes->get_or_insert (file);
9623 if (set)
9624 if (set->contains (header))
9625 /* ...then we've already added HEADER to that file. */
9626 return;
9627 if (!set)
9628 set = new per_file_includes_t ();
9629 set->add (header);
9631 /* Attempt to locate a suitable place for the new directive. */
9632 location_t include_insert_loc
9633 = try_to_locate_new_include_insertion_point (file, loc);
9634 if (include_insert_loc == UNKNOWN_LOCATION)
9635 return;
9637 char *text = xasprintf ("#include %s\n", header);
9638 richloc->add_fixit_insert_before (include_insert_loc, text);
9639 free (text);
9641 if (override_location && global_dc->m_source_printing.enabled)
9643 /* Replace the primary location with that of the insertion point for the
9644 fix-it hint.
9646 We use SHOW_LINES_WITHOUT_RANGE so that we don't meaningless print a
9647 caret for the insertion point (or colorize it).
9649 Hence we print e.g.:
9651 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9652 73 | # include <debug/vector>
9653 +++ |+#include <vector>
9654 74 | #endif
9656 rather than:
9658 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
9659 73 | # include <debug/vector>
9660 +++ |+#include <vector>
9661 74 | #endif
9664 avoiding the caret on the first column of line 74. */
9665 richloc->set_range (0, include_insert_loc, SHOW_LINES_WITHOUT_RANGE);
9669 /* Attempt to convert a braced array initializer list CTOR for array
9670 TYPE into a STRING_CST for convenience and efficiency. Return
9671 the converted string on success or the original ctor on failure. */
9673 static tree
9674 braced_list_to_string (tree type, tree ctor, bool member)
9676 /* Ignore non-members with unknown size like arrays with unspecified
9677 bound. */
9678 tree typesize = TYPE_SIZE_UNIT (type);
9679 if (!member && !tree_fits_uhwi_p (typesize))
9680 return ctor;
9682 /* If the target char size differs from the host char size, we'd risk
9683 loosing data and getting object sizes wrong by converting to
9684 host chars. */
9685 if (TYPE_PRECISION (char_type_node) != CHAR_BIT)
9686 return ctor;
9688 /* STRING_CST doesn't support wide characters. */
9689 gcc_checking_assert (TYPE_PRECISION (TREE_TYPE (type)) == CHAR_BIT);
9691 /* If the array has an explicit bound, use it to constrain the size
9692 of the string. If it doesn't, be sure to create a string that's
9693 as long as implied by the index of the last zero specified via
9694 a designator, as in:
9695 const char a[] = { [7] = 0 }; */
9696 unsigned HOST_WIDE_INT maxelts;
9697 if (typesize)
9699 maxelts = tree_to_uhwi (typesize);
9700 maxelts /= tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type)));
9702 else
9703 maxelts = HOST_WIDE_INT_M1U;
9705 /* Avoid converting initializers for zero-length arrays (but do
9706 create them for flexible array members). */
9707 if (!maxelts)
9708 return ctor;
9710 unsigned HOST_WIDE_INT nelts = CONSTRUCTOR_NELTS (ctor);
9712 auto_vec<char> str;
9713 str.reserve (nelts + 1);
9715 unsigned HOST_WIDE_INT i;
9716 tree index, value;
9718 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, index, value)
9720 unsigned HOST_WIDE_INT idx = i;
9721 if (index)
9723 if (!tree_fits_uhwi_p (index))
9724 return ctor;
9725 idx = tree_to_uhwi (index);
9728 /* auto_vec is limited to UINT_MAX elements. */
9729 if (idx > UINT_MAX)
9730 return ctor;
9732 /* Avoid non-constant initializers. */
9733 if (!tree_fits_shwi_p (value))
9734 return ctor;
9736 /* Skip over embedded nuls except the last one (initializer
9737 elements are in ascending order of indices). */
9738 HOST_WIDE_INT val = tree_to_shwi (value);
9739 if (!val && i + 1 < nelts)
9740 continue;
9742 if (idx < str.length())
9743 return ctor;
9745 /* Bail if the CTOR has a block of more than 256 embedded nuls
9746 due to implicitly initialized elements. */
9747 unsigned nchars = (idx - str.length ()) + 1;
9748 if (nchars > 256)
9749 return ctor;
9751 if (nchars > 1)
9753 str.reserve (idx);
9754 str.quick_grow_cleared (idx);
9757 if (idx >= maxelts)
9758 return ctor;
9760 str.safe_insert (idx, val);
9763 /* Append a nul string termination. */
9764 if (maxelts != HOST_WIDE_INT_M1U && str.length () < maxelts)
9765 str.safe_push (0);
9767 /* Build a STRING_CST with the same type as the array. */
9768 tree res = build_string (str.length (), str.begin ());
9769 TREE_TYPE (res) = type;
9770 return res;
9773 /* Implementation of the two-argument braced_lists_to_string withe
9774 the same arguments plus MEMBER which is set for struct members
9775 to allow initializers for flexible member arrays. */
9777 static tree
9778 braced_lists_to_strings (tree type, tree ctor, bool member)
9780 if (TREE_CODE (ctor) != CONSTRUCTOR)
9781 return ctor;
9783 tree_code code = TREE_CODE (type);
9785 tree ttp;
9786 if (code == ARRAY_TYPE)
9787 ttp = TREE_TYPE (type);
9788 else if (code == RECORD_TYPE)
9790 ttp = TREE_TYPE (ctor);
9791 if (TREE_CODE (ttp) == ARRAY_TYPE)
9793 type = ttp;
9794 ttp = TREE_TYPE (ttp);
9797 else
9798 return ctor;
9800 if ((TREE_CODE (ttp) == ARRAY_TYPE || TREE_CODE (ttp) == INTEGER_TYPE)
9801 && TYPE_STRING_FLAG (ttp))
9802 return braced_list_to_string (type, ctor, member);
9804 code = TREE_CODE (ttp);
9805 if (code == ARRAY_TYPE || RECORD_OR_UNION_TYPE_P (ttp))
9807 bool rec = RECORD_OR_UNION_TYPE_P (ttp);
9809 /* Handle array of arrays or struct member initializers. */
9810 tree val;
9811 unsigned HOST_WIDE_INT idx;
9812 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, val)
9814 val = braced_lists_to_strings (ttp, val, rec);
9815 CONSTRUCTOR_ELT (ctor, idx)->value = val;
9819 return ctor;
9822 /* Attempt to convert a CTOR containing braced array initializer lists
9823 for array TYPE into one containing STRING_CSTs, for convenience and
9824 efficiency. Recurse for arrays of arrays and member initializers.
9825 Return the converted CTOR or STRING_CST on success or the original
9826 CTOR otherwise. */
9828 tree
9829 braced_lists_to_strings (tree type, tree ctor)
9831 return braced_lists_to_strings (type, ctor, false);
9835 /* Emit debug for functions before finalizing early debug. */
9837 void
9838 c_common_finalize_early_debug (void)
9840 /* Emit early debug for reachable functions, and by consequence,
9841 locally scoped symbols. Also emit debug for extern declared
9842 functions that are still reachable at this point. */
9843 struct cgraph_node *cnode;
9844 FOR_EACH_FUNCTION (cnode)
9845 if (!cnode->alias && !cnode->thunk
9846 && (cnode->has_gimple_body_p ()
9847 || !DECL_IS_UNDECLARED_BUILTIN (cnode->decl)))
9848 (*debug_hooks->early_global_decl) (cnode->decl);
9851 /* Get the LEVEL of the strict_flex_array for the ARRAY_FIELD based on the
9852 values of attribute strict_flex_array and the flag_strict_flex_arrays. */
9853 unsigned int
9854 c_strict_flex_array_level_of (tree array_field)
9856 gcc_assert (TREE_CODE (array_field) == FIELD_DECL);
9857 unsigned int strict_flex_array_level = flag_strict_flex_arrays;
9859 tree attr_strict_flex_array
9860 = lookup_attribute ("strict_flex_array", DECL_ATTRIBUTES (array_field));
9861 /* If there is a strict_flex_array attribute attached to the field,
9862 override the flag_strict_flex_arrays. */
9863 if (attr_strict_flex_array)
9865 /* Get the value of the level first from the attribute. */
9866 unsigned HOST_WIDE_INT attr_strict_flex_array_level = 0;
9867 gcc_assert (TREE_VALUE (attr_strict_flex_array) != NULL_TREE);
9868 attr_strict_flex_array = TREE_VALUE (attr_strict_flex_array);
9869 gcc_assert (TREE_VALUE (attr_strict_flex_array) != NULL_TREE);
9870 attr_strict_flex_array = TREE_VALUE (attr_strict_flex_array);
9871 gcc_assert (tree_fits_uhwi_p (attr_strict_flex_array));
9872 attr_strict_flex_array_level = tree_to_uhwi (attr_strict_flex_array);
9874 /* The attribute has higher priority than flag_struct_flex_array. */
9875 strict_flex_array_level = attr_strict_flex_array_level;
9877 return strict_flex_array_level;
9880 #include "gt-c-family-c-common.h"