testsuite: Correct requirements for vadsdu*, vslv and vsrv testcases.
[official-gcc.git] / gcc / c-family / c-common.c
blobd56238aeb019d9cb301e7aaff455d28ed52c17f6
1 /* Subroutines shared by all languages that are variants of C.
2 Copyright (C) 1992-2020 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"
55 cpp_reader *parse_in; /* Declared in c-pragma.h. */
57 /* Mode used to build pointers (VOIDmode means ptr_mode). */
59 machine_mode c_default_pointer_mode = VOIDmode;
61 /* The following symbols are subsumed in the c_global_trees array, and
62 listed here individually for documentation purposes.
64 INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
66 tree short_integer_type_node;
67 tree long_integer_type_node;
68 tree long_long_integer_type_node;
70 tree short_unsigned_type_node;
71 tree long_unsigned_type_node;
72 tree long_long_unsigned_type_node;
74 tree truthvalue_type_node;
75 tree truthvalue_false_node;
76 tree truthvalue_true_node;
78 tree ptrdiff_type_node;
80 tree unsigned_char_type_node;
81 tree signed_char_type_node;
82 tree wchar_type_node;
84 tree char8_type_node;
85 tree char16_type_node;
86 tree char32_type_node;
88 tree float_type_node;
89 tree double_type_node;
90 tree long_double_type_node;
92 tree complex_integer_type_node;
93 tree complex_float_type_node;
94 tree complex_double_type_node;
95 tree complex_long_double_type_node;
97 tree dfloat32_type_node;
98 tree dfloat64_type_node;
99 tree_dfloat128_type_node;
101 tree intQI_type_node;
102 tree intHI_type_node;
103 tree intSI_type_node;
104 tree intDI_type_node;
105 tree intTI_type_node;
107 tree unsigned_intQI_type_node;
108 tree unsigned_intHI_type_node;
109 tree unsigned_intSI_type_node;
110 tree unsigned_intDI_type_node;
111 tree unsigned_intTI_type_node;
113 tree widest_integer_literal_type_node;
114 tree widest_unsigned_literal_type_node;
116 Nodes for types `void *' and `const void *'.
118 tree ptr_type_node, const_ptr_type_node;
120 Nodes for types `char *' and `const char *'.
122 tree string_type_node, const_string_type_node;
124 Type `char[SOMENUMBER]'.
125 Used when an array of char is needed and the size is irrelevant.
127 tree char_array_type_node;
129 Type `wchar_t[SOMENUMBER]' or something like it.
130 Used when a wide string literal is created.
132 tree wchar_array_type_node;
134 Type `char8_t[SOMENUMBER]' or something like it.
135 Used when a UTF-8 string literal is created.
137 tree char8_array_type_node;
139 Type `char16_t[SOMENUMBER]' or something like it.
140 Used when a UTF-16 string literal is created.
142 tree char16_array_type_node;
144 Type `char32_t[SOMENUMBER]' or something like it.
145 Used when a UTF-32 string literal is created.
147 tree char32_array_type_node;
149 Type `int ()' -- used for implicit declaration of functions.
151 tree default_function_type;
153 A VOID_TYPE node, packaged in a TREE_LIST.
155 tree void_list_node;
157 The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
158 and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
159 VAR_DECLS, but C++ does.)
161 tree function_name_decl_node;
162 tree pretty_function_name_decl_node;
163 tree c99_function_name_decl_node;
165 Stack of nested function name VAR_DECLs.
167 tree saved_function_name_decls;
171 tree c_global_trees[CTI_MAX];
173 /* Switches common to the C front ends. */
175 /* Nonzero means don't output line number information. */
177 char flag_no_line_commands;
179 /* Nonzero causes -E output not to be done, but directives such as
180 #define that have side effects are still obeyed. */
182 char flag_no_output;
184 /* Nonzero means dump macros in some fashion. */
186 char flag_dump_macros;
188 /* Nonzero means pass #include lines through to the output. */
190 char flag_dump_includes;
192 /* Nonzero means process PCH files while preprocessing. */
194 bool flag_pch_preprocess;
196 /* The file name to which we should write a precompiled header, or
197 NULL if no header will be written in this compile. */
199 const char *pch_file;
201 /* Nonzero if an ISO standard was selected. It rejects macros in the
202 user's namespace. */
203 int flag_iso;
205 /* C/ObjC language option variables. */
208 /* Nonzero means allow type mismatches in conditional expressions;
209 just make their values `void'. */
211 int flag_cond_mismatch;
213 /* Nonzero means enable C89 Amendment 1 features. */
215 int flag_isoc94;
217 /* Nonzero means use the ISO C99 (or C11) dialect of C. */
219 int flag_isoc99;
221 /* Nonzero means use the ISO C11 dialect of C. */
223 int flag_isoc11;
225 /* Nonzero means use the ISO C2X dialect of C. */
227 int flag_isoc2x;
229 /* Nonzero means that we have builtin functions, and main is an int. */
231 int flag_hosted = 1;
234 /* ObjC language option variables. */
237 /* Tells the compiler that this is a special run. Do not perform any
238 compiling, instead we are to test some platform dependent features
239 and output a C header file with appropriate definitions. */
241 int print_struct_values;
243 /* Tells the compiler what is the constant string class for ObjC. */
245 const char *constant_string_class_name;
248 /* C++ language option variables. */
250 /* The reference version of the ABI for -Wabi. */
252 int warn_abi_version = -1;
254 /* The C++ dialect being used. Default set in c_common_post_options. */
256 enum cxx_dialect cxx_dialect = cxx_unset;
258 /* Maximum template instantiation depth. This limit exists to limit the
259 time it takes to notice excessively recursive template instantiations.
261 The default is lower than the 1024 recommended by the C++0x standard
262 because G++ runs out of stack before 1024 with highly recursive template
263 argument deduction substitution (g++.dg/cpp0x/enum11.C). */
265 int max_tinst_depth = 900;
267 /* The elements of `ridpointers' are identifier nodes for the reserved
268 type names and storage classes. It is indexed by a RID_... value. */
269 tree *ridpointers;
271 tree (*make_fname_decl) (location_t, tree, int);
273 /* Nonzero means don't warn about problems that occur when the code is
274 executed. */
275 int c_inhibit_evaluation_warnings;
277 /* Whether we are building a boolean conversion inside
278 convert_for_assignment, or some other late binary operation. If
279 build_binary_op is called for C (from code shared by C and C++) in
280 this case, then the operands have already been folded and the
281 result will not be folded again, so C_MAYBE_CONST_EXPR should not
282 be generated. */
283 bool in_late_binary_op;
285 /* Whether lexing has been completed, so subsequent preprocessor
286 errors should use the compiler's input_location. */
287 bool done_lexing = false;
289 /* Information about how a function name is generated. */
290 struct fname_var_t
292 tree *const decl; /* pointer to the VAR_DECL. */
293 const unsigned rid; /* RID number for the identifier. */
294 const int pretty; /* How pretty is it? */
297 /* The three ways of getting then name of the current function. */
299 const struct fname_var_t fname_vars[] =
301 /* C99 compliant __func__, must be first. */
302 {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
303 /* GCC __FUNCTION__ compliant. */
304 {&function_name_decl_node, RID_FUNCTION_NAME, 0},
305 /* GCC __PRETTY_FUNCTION__ compliant. */
306 {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
307 {NULL, 0, 0},
310 /* Global visibility options. */
311 struct visibility_flags visibility_options;
313 static tree check_case_value (location_t, tree);
316 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
317 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
319 /* Reserved words. The third field is a mask: keywords are disabled
320 if they match the mask.
322 Masks for languages:
323 C --std=c89: D_C99 | D_CXXONLY | D_OBJC | D_CXX_OBJC
324 C --std=c99: D_CXXONLY | D_OBJC
325 ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
326 C++ --std=c++98: D_CONLY | D_CXX11 | D_CXX20 | D_OBJC
327 C++ --std=c++11: D_CONLY | D_CXX20 | D_OBJC
328 C++ --std=c++20: D_CONLY | D_OBJC
329 ObjC++ is like C++ except that D_OBJC is not set
331 If -fno-asm is used, D_ASM is added to the mask. If
332 -fno-gnu-keywords is used, D_EXT is added. If -fno-asm and C in
333 C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
334 In C with -Wc++-compat, we warn if D_CXXWARN is set.
336 Note the complication of the D_CXX_OBJC keywords. These are
337 reserved words such as 'class'. In C++, 'class' is a reserved
338 word. In Objective-C++ it is too. In Objective-C, it is a
339 reserved word too, but only if it follows an '@' sign.
341 const struct c_common_resword c_common_reswords[] =
343 { "_Alignas", RID_ALIGNAS, D_CONLY },
344 { "_Alignof", RID_ALIGNOF, D_CONLY },
345 { "_Atomic", RID_ATOMIC, D_CONLY },
346 { "_Bool", RID_BOOL, D_CONLY },
347 { "_Complex", RID_COMPLEX, 0 },
348 { "_Imaginary", RID_IMAGINARY, D_CONLY },
349 { "_Float16", RID_FLOAT16, D_CONLY },
350 { "_Float32", RID_FLOAT32, D_CONLY },
351 { "_Float64", RID_FLOAT64, D_CONLY },
352 { "_Float128", RID_FLOAT128, D_CONLY },
353 { "_Float32x", RID_FLOAT32X, D_CONLY },
354 { "_Float64x", RID_FLOAT64X, D_CONLY },
355 { "_Float128x", RID_FLOAT128X, D_CONLY },
356 { "_Decimal32", RID_DFLOAT32, D_CONLY },
357 { "_Decimal64", RID_DFLOAT64, D_CONLY },
358 { "_Decimal128", RID_DFLOAT128, D_CONLY },
359 { "_Fract", RID_FRACT, D_CONLY | D_EXT },
360 { "_Accum", RID_ACCUM, D_CONLY | D_EXT },
361 { "_Sat", RID_SAT, D_CONLY | D_EXT },
362 { "_Static_assert", RID_STATIC_ASSERT, D_CONLY },
363 { "_Noreturn", RID_NORETURN, D_CONLY },
364 { "_Generic", RID_GENERIC, D_CONLY },
365 { "_Thread_local", RID_THREAD, D_CONLY },
366 { "__FUNCTION__", RID_FUNCTION_NAME, 0 },
367 { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
368 { "__alignof", RID_ALIGNOF, 0 },
369 { "__alignof__", RID_ALIGNOF, 0 },
370 { "__asm", RID_ASM, 0 },
371 { "__asm__", RID_ASM, 0 },
372 { "__attribute", RID_ATTRIBUTE, 0 },
373 { "__attribute__", RID_ATTRIBUTE, 0 },
374 { "__auto_type", RID_AUTO_TYPE, D_CONLY },
375 { "__bases", RID_BASES, D_CXXONLY },
376 { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
377 { "__builtin_call_with_static_chain",
378 RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
379 { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
380 { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
381 { "__builtin_convertvector", RID_BUILTIN_CONVERTVECTOR, 0 },
382 { "__builtin_has_attribute", RID_BUILTIN_HAS_ATTRIBUTE, 0 },
383 { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
384 { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
385 { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
386 { "__builtin_offsetof", RID_OFFSETOF, 0 },
387 { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
388 { "__builtin_va_arg", RID_VA_ARG, 0 },
389 { "__complex", RID_COMPLEX, 0 },
390 { "__complex__", RID_COMPLEX, 0 },
391 { "__const", RID_CONST, 0 },
392 { "__const__", RID_CONST, 0 },
393 { "__constinit", RID_CONSTINIT, D_CXXONLY },
394 { "__decltype", RID_DECLTYPE, D_CXXONLY },
395 { "__direct_bases", RID_DIRECT_BASES, D_CXXONLY },
396 { "__extension__", RID_EXTENSION, 0 },
397 { "__func__", RID_C99_FUNCTION_NAME, 0 },
398 { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
399 { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
400 { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
401 { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
402 { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
403 { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
404 { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
405 { "__has_unique_object_representations", RID_HAS_UNIQUE_OBJ_REPRESENTATIONS,
406 D_CXXONLY },
407 { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
408 { "__imag", RID_IMAGPART, 0 },
409 { "__imag__", RID_IMAGPART, 0 },
410 { "__inline", RID_INLINE, 0 },
411 { "__inline__", RID_INLINE, 0 },
412 { "__is_abstract", RID_IS_ABSTRACT, D_CXXONLY },
413 { "__is_aggregate", RID_IS_AGGREGATE, D_CXXONLY },
414 { "__is_base_of", RID_IS_BASE_OF, D_CXXONLY },
415 { "__is_class", RID_IS_CLASS, D_CXXONLY },
416 { "__is_empty", RID_IS_EMPTY, D_CXXONLY },
417 { "__is_enum", RID_IS_ENUM, D_CXXONLY },
418 { "__is_final", RID_IS_FINAL, D_CXXONLY },
419 { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
420 { "__is_pod", RID_IS_POD, D_CXXONLY },
421 { "__is_polymorphic", RID_IS_POLYMORPHIC, D_CXXONLY },
422 { "__is_same", RID_IS_SAME_AS, D_CXXONLY },
423 { "__is_same_as", RID_IS_SAME_AS, D_CXXONLY },
424 { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
425 { "__is_trivial", RID_IS_TRIVIAL, D_CXXONLY },
426 { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
427 { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
428 { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
429 { "__is_union", RID_IS_UNION, D_CXXONLY },
430 { "__label__", RID_LABEL, 0 },
431 { "__null", RID_NULL, 0 },
432 { "__real", RID_REALPART, 0 },
433 { "__real__", RID_REALPART, 0 },
434 { "__restrict", RID_RESTRICT, 0 },
435 { "__restrict__", RID_RESTRICT, 0 },
436 { "__signed", RID_SIGNED, 0 },
437 { "__signed__", RID_SIGNED, 0 },
438 { "__thread", RID_THREAD, 0 },
439 { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
440 { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
441 { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
442 { "__typeof", RID_TYPEOF, 0 },
443 { "__typeof__", RID_TYPEOF, 0 },
444 { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
445 { "__volatile", RID_VOLATILE, 0 },
446 { "__volatile__", RID_VOLATILE, 0 },
447 { "__GIMPLE", RID_GIMPLE, D_CONLY },
448 { "__PHI", RID_PHI, D_CONLY },
449 { "__RTL", RID_RTL, D_CONLY },
450 { "alignas", RID_ALIGNAS, D_CXXONLY | D_CXX11 | D_CXXWARN },
451 { "alignof", RID_ALIGNOF, D_CXXONLY | D_CXX11 | D_CXXWARN },
452 { "asm", RID_ASM, D_ASM },
453 { "auto", RID_AUTO, 0 },
454 { "bool", RID_BOOL, D_CXXONLY | D_CXXWARN },
455 { "break", RID_BREAK, 0 },
456 { "case", RID_CASE, 0 },
457 { "catch", RID_CATCH, D_CXX_OBJC | D_CXXWARN },
458 { "char", RID_CHAR, 0 },
459 { "char8_t", RID_CHAR8, D_CXX_CHAR8_T_FLAGS | D_CXXWARN },
460 { "char16_t", RID_CHAR16, D_CXXONLY | D_CXX11 | D_CXXWARN },
461 { "char32_t", RID_CHAR32, D_CXXONLY | D_CXX11 | D_CXXWARN },
462 { "class", RID_CLASS, D_CXX_OBJC | D_CXXWARN },
463 { "const", RID_CONST, 0 },
464 { "consteval", RID_CONSTEVAL, D_CXXONLY | D_CXX20 | D_CXXWARN },
465 { "constexpr", RID_CONSTEXPR, D_CXXONLY | D_CXX11 | D_CXXWARN },
466 { "constinit", RID_CONSTINIT, D_CXXONLY | D_CXX20 | D_CXXWARN },
467 { "const_cast", RID_CONSTCAST, D_CXXONLY | D_CXXWARN },
468 { "continue", RID_CONTINUE, 0 },
469 { "decltype", RID_DECLTYPE, D_CXXONLY | D_CXX11 | D_CXXWARN },
470 { "default", RID_DEFAULT, 0 },
471 { "delete", RID_DELETE, D_CXXONLY | D_CXXWARN },
472 { "do", RID_DO, 0 },
473 { "double", RID_DOUBLE, 0 },
474 { "dynamic_cast", RID_DYNCAST, D_CXXONLY | D_CXXWARN },
475 { "else", RID_ELSE, 0 },
476 { "enum", RID_ENUM, 0 },
477 { "explicit", RID_EXPLICIT, D_CXXONLY | D_CXXWARN },
478 { "export", RID_EXPORT, D_CXXONLY | D_CXXWARN },
479 { "extern", RID_EXTERN, 0 },
480 { "false", RID_FALSE, D_CXXONLY | D_CXXWARN },
481 { "float", RID_FLOAT, 0 },
482 { "for", RID_FOR, 0 },
483 { "friend", RID_FRIEND, D_CXXONLY | D_CXXWARN },
484 { "goto", RID_GOTO, 0 },
485 { "if", RID_IF, 0 },
486 { "inline", RID_INLINE, D_EXT89 },
487 { "int", RID_INT, 0 },
488 { "long", RID_LONG, 0 },
489 { "mutable", RID_MUTABLE, D_CXXONLY | D_CXXWARN },
490 { "namespace", RID_NAMESPACE, D_CXXONLY | D_CXXWARN },
491 { "new", RID_NEW, D_CXXONLY | D_CXXWARN },
492 { "noexcept", RID_NOEXCEPT, D_CXXONLY | D_CXX11 | D_CXXWARN },
493 { "nullptr", RID_NULLPTR, D_CXXONLY | D_CXX11 | D_CXXWARN },
494 { "operator", RID_OPERATOR, D_CXXONLY | D_CXXWARN },
495 { "private", RID_PRIVATE, D_CXX_OBJC | D_CXXWARN },
496 { "protected", RID_PROTECTED, D_CXX_OBJC | D_CXXWARN },
497 { "public", RID_PUBLIC, D_CXX_OBJC | D_CXXWARN },
498 { "register", RID_REGISTER, 0 },
499 { "reinterpret_cast", RID_REINTCAST, D_CXXONLY | D_CXXWARN },
500 { "restrict", RID_RESTRICT, D_CONLY | D_C99 },
501 { "return", RID_RETURN, 0 },
502 { "short", RID_SHORT, 0 },
503 { "signed", RID_SIGNED, 0 },
504 { "sizeof", RID_SIZEOF, 0 },
505 { "static", RID_STATIC, 0 },
506 { "static_assert", RID_STATIC_ASSERT, D_CXXONLY | D_CXX11 | D_CXXWARN },
507 { "static_cast", RID_STATCAST, D_CXXONLY | D_CXXWARN },
508 { "struct", RID_STRUCT, 0 },
509 { "switch", RID_SWITCH, 0 },
510 { "template", RID_TEMPLATE, D_CXXONLY | D_CXXWARN },
511 { "this", RID_THIS, D_CXXONLY | D_CXXWARN },
512 { "thread_local", RID_THREAD, D_CXXONLY | D_CXX11 | D_CXXWARN },
513 { "throw", RID_THROW, D_CXX_OBJC | D_CXXWARN },
514 { "true", RID_TRUE, D_CXXONLY | D_CXXWARN },
515 { "try", RID_TRY, D_CXX_OBJC | D_CXXWARN },
516 { "typedef", RID_TYPEDEF, 0 },
517 { "typename", RID_TYPENAME, D_CXXONLY | D_CXXWARN },
518 { "typeid", RID_TYPEID, D_CXXONLY | D_CXXWARN },
519 { "typeof", RID_TYPEOF, D_ASM | D_EXT },
520 { "union", RID_UNION, 0 },
521 { "unsigned", RID_UNSIGNED, 0 },
522 { "using", RID_USING, D_CXXONLY | D_CXXWARN },
523 { "virtual", RID_VIRTUAL, D_CXXONLY | D_CXXWARN },
524 { "void", RID_VOID, 0 },
525 { "volatile", RID_VOLATILE, 0 },
526 { "wchar_t", RID_WCHAR, D_CXXONLY },
527 { "while", RID_WHILE, 0 },
528 { "__is_assignable", RID_IS_ASSIGNABLE, D_CXXONLY },
529 { "__is_constructible", RID_IS_CONSTRUCTIBLE, D_CXXONLY },
530 { "__is_nothrow_assignable", RID_IS_NOTHROW_ASSIGNABLE, D_CXXONLY },
531 { "__is_nothrow_constructible", RID_IS_NOTHROW_CONSTRUCTIBLE, D_CXXONLY },
533 /* C++ transactional memory. */
534 { "synchronized", RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
535 { "atomic_noexcept", RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
536 { "atomic_cancel", RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
537 { "atomic_commit", RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
539 /* Concepts-related keywords */
540 { "concept", RID_CONCEPT, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
541 { "requires", RID_REQUIRES, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
543 /* Coroutines-related keywords */
544 { "co_await", RID_CO_AWAIT, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
545 { "co_yield", RID_CO_YIELD, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
546 { "co_return", RID_CO_RETURN, D_CXX_COROUTINES_FLAGS | D_CXXWARN },
548 /* These Objective-C keywords are recognized only immediately after
549 an '@'. */
550 { "compatibility_alias", RID_AT_ALIAS, D_OBJC },
551 { "defs", RID_AT_DEFS, D_OBJC },
552 { "encode", RID_AT_ENCODE, D_OBJC },
553 { "end", RID_AT_END, D_OBJC },
554 { "implementation", RID_AT_IMPLEMENTATION, D_OBJC },
555 { "interface", RID_AT_INTERFACE, D_OBJC },
556 { "protocol", RID_AT_PROTOCOL, D_OBJC },
557 { "selector", RID_AT_SELECTOR, D_OBJC },
558 { "finally", RID_AT_FINALLY, D_OBJC },
559 { "optional", RID_AT_OPTIONAL, D_OBJC },
560 { "required", RID_AT_REQUIRED, D_OBJC },
561 { "property", RID_AT_PROPERTY, D_OBJC },
562 { "package", RID_AT_PACKAGE, D_OBJC },
563 { "synthesize", RID_AT_SYNTHESIZE, D_OBJC },
564 { "dynamic", RID_AT_DYNAMIC, D_OBJC },
565 /* These are recognized only in protocol-qualifier context
566 (see above) */
567 { "bycopy", RID_BYCOPY, D_OBJC },
568 { "byref", RID_BYREF, D_OBJC },
569 { "in", RID_IN, D_OBJC },
570 { "inout", RID_INOUT, D_OBJC },
571 { "oneway", RID_ONEWAY, D_OBJC },
572 { "out", RID_OUT, D_OBJC },
573 /* These are recognized inside a property attribute list */
574 { "assign", RID_ASSIGN, D_OBJC },
575 { "copy", RID_COPY, D_OBJC },
576 { "getter", RID_GETTER, D_OBJC },
577 { "nonatomic", RID_NONATOMIC, D_OBJC },
578 { "readonly", RID_READONLY, D_OBJC },
579 { "readwrite", RID_READWRITE, D_OBJC },
580 { "retain", RID_RETAIN, D_OBJC },
581 { "setter", RID_SETTER, D_OBJC },
584 const unsigned int num_c_common_reswords =
585 sizeof c_common_reswords / sizeof (struct c_common_resword);
587 /* Return identifier for address space AS. */
589 const char *
590 c_addr_space_name (addr_space_t as)
592 int rid = RID_FIRST_ADDR_SPACE + as;
593 gcc_assert (ridpointers [rid]);
594 return IDENTIFIER_POINTER (ridpointers [rid]);
597 /* Push current bindings for the function name VAR_DECLS. */
599 void
600 start_fname_decls (void)
602 unsigned ix;
603 tree saved = NULL_TREE;
605 for (ix = 0; fname_vars[ix].decl; ix++)
607 tree decl = *fname_vars[ix].decl;
609 if (decl)
611 saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
612 saved);
613 *fname_vars[ix].decl = NULL_TREE;
616 if (saved || saved_function_name_decls)
617 /* Normally they'll have been NULL, so only push if we've got a
618 stack, or they are non-NULL. */
619 saved_function_name_decls = tree_cons (saved, NULL_TREE,
620 saved_function_name_decls);
623 /* Finish up the current bindings, adding them into the current function's
624 statement tree. This must be done _before_ finish_stmt_tree is called.
625 If there is no current function, we must be at file scope and no statements
626 are involved. Pop the previous bindings. */
628 void
629 finish_fname_decls (void)
631 unsigned ix;
632 tree stmts = NULL_TREE;
633 tree stack = saved_function_name_decls;
635 for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
636 append_to_statement_list (TREE_VALUE (stack), &stmts);
638 if (stmts)
640 tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
642 if (TREE_CODE (*bodyp) == BIND_EXPR)
643 bodyp = &BIND_EXPR_BODY (*bodyp);
645 append_to_statement_list_force (*bodyp, &stmts);
646 *bodyp = stmts;
649 for (ix = 0; fname_vars[ix].decl; ix++)
650 *fname_vars[ix].decl = NULL_TREE;
652 if (stack)
654 /* We had saved values, restore them. */
655 tree saved;
657 for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
659 tree decl = TREE_PURPOSE (saved);
660 unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
662 *fname_vars[ix].decl = decl;
664 stack = TREE_CHAIN (stack);
666 saved_function_name_decls = stack;
669 /* Return the text name of the current function, suitably prettified
670 by PRETTY_P. Return string must be freed by caller. */
672 const char *
673 fname_as_string (int pretty_p)
675 const char *name = "top level";
676 char *namep;
677 int vrb = 2, len;
678 cpp_string cstr = { 0, 0 }, strname;
680 if (!pretty_p)
682 name = "";
683 vrb = 0;
686 if (current_function_decl)
687 name = lang_hooks.decl_printable_name (current_function_decl, vrb);
689 len = strlen (name) + 3; /* Two for '"'s. One for NULL. */
691 namep = XNEWVEC (char, len);
692 snprintf (namep, len, "\"%s\"", name);
693 strname.text = (unsigned char *) namep;
694 strname.len = len - 1;
696 if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
698 XDELETEVEC (namep);
699 return (const char *) cstr.text;
702 return namep;
705 /* Return the VAR_DECL for a const char array naming the current
706 function. If the VAR_DECL has not yet been created, create it
707 now. RID indicates how it should be formatted and IDENTIFIER_NODE
708 ID is its name (unfortunately C and C++ hold the RID values of
709 keywords in different places, so we can't derive RID from ID in
710 this language independent code. LOC is the location of the
711 function. */
713 tree
714 fname_decl (location_t loc, unsigned int rid, tree id)
716 unsigned ix;
717 tree decl = NULL_TREE;
719 for (ix = 0; fname_vars[ix].decl; ix++)
720 if (fname_vars[ix].rid == rid)
721 break;
723 decl = *fname_vars[ix].decl;
724 if (!decl)
726 /* If a tree is built here, it would normally have the lineno of
727 the current statement. Later this tree will be moved to the
728 beginning of the function and this line number will be wrong.
729 To avoid this problem set the lineno to 0 here; that prevents
730 it from appearing in the RTL. */
731 tree stmts;
732 location_t saved_location = input_location;
733 input_location = UNKNOWN_LOCATION;
735 stmts = push_stmt_list ();
736 decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
737 stmts = pop_stmt_list (stmts);
738 if (!IS_EMPTY_STMT (stmts))
739 saved_function_name_decls
740 = tree_cons (decl, stmts, saved_function_name_decls);
741 *fname_vars[ix].decl = decl;
742 input_location = saved_location;
744 if (!ix && !current_function_decl)
745 pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
747 return decl;
750 /* Given a STRING_CST, give it a suitable array-of-chars data type. */
752 tree
753 fix_string_type (tree value)
755 int length = TREE_STRING_LENGTH (value);
756 int nchars, charsz;
757 tree e_type, i_type, a_type;
759 /* Compute the number of elements, for the array type. */
760 if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
762 charsz = 1;
763 e_type = char_type_node;
765 else if (flag_char8_t && TREE_TYPE (value) == char8_array_type_node)
767 charsz = TYPE_PRECISION (char8_type_node) / BITS_PER_UNIT;
768 e_type = char8_type_node;
770 else if (TREE_TYPE (value) == char16_array_type_node)
772 charsz = TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT;
773 e_type = char16_type_node;
775 else if (TREE_TYPE (value) == char32_array_type_node)
777 charsz = TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT;
778 e_type = char32_type_node;
780 else
782 charsz = TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT;
783 e_type = wchar_type_node;
786 /* This matters only for targets where ssizetype has smaller precision
787 than 32 bits. */
788 if (wi::lts_p (wi::to_wide (TYPE_MAX_VALUE (ssizetype)), length))
790 error ("size of string literal is too large");
791 length = tree_to_shwi (TYPE_MAX_VALUE (ssizetype)) / charsz * charsz;
792 char *str = CONST_CAST (char *, TREE_STRING_POINTER (value));
793 memset (str + length, '\0',
794 MIN (TREE_STRING_LENGTH (value) - length, charsz));
795 TREE_STRING_LENGTH (value) = length;
797 nchars = length / charsz;
799 /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits). The analogous
800 limit in C++98 Annex B is very large (65536) and is not normative,
801 so we do not diagnose it (warn_overlength_strings is forced off
802 in c_common_post_options). */
803 if (warn_overlength_strings)
805 const int nchars_max = flag_isoc99 ? 4095 : 509;
806 const int relevant_std = flag_isoc99 ? 99 : 90;
807 if (nchars - 1 > nchars_max)
808 /* Translators: The %d after 'ISO C' will be 90 or 99. Do not
809 separate the %d from the 'C'. 'ISO' should not be
810 translated, but it may be moved after 'C%d' in languages
811 where modifiers follow nouns. */
812 pedwarn (input_location, OPT_Woverlength_strings,
813 "string length %qd is greater than the length %qd "
814 "ISO C%d compilers are required to support",
815 nchars - 1, nchars_max, relevant_std);
818 /* Create the array type for the string constant. The ISO C++
819 standard says that a string literal has type `const char[N]' or
820 `const wchar_t[N]'. We use the same logic when invoked as a C
821 front-end with -Wwrite-strings.
822 ??? We should change the type of an expression depending on the
823 state of a warning flag. We should just be warning -- see how
824 this is handled in the C++ front-end for the deprecated implicit
825 conversion from string literals to `char*' or `wchar_t*'.
827 The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
828 array type being the unqualified version of that type.
829 Therefore, if we are constructing an array of const char, we must
830 construct the matching unqualified array type first. The C front
831 end does not require this, but it does no harm, so we do it
832 unconditionally. */
833 i_type = build_index_type (size_int (nchars - 1));
834 a_type = build_array_type (e_type, i_type);
835 if (c_dialect_cxx() || warn_write_strings)
836 a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
838 TREE_TYPE (value) = a_type;
839 TREE_CONSTANT (value) = 1;
840 TREE_READONLY (value) = 1;
841 TREE_STATIC (value) = 1;
842 return value;
845 /* Given a string of type STRING_TYPE, determine what kind of string
846 token would give an equivalent execution encoding: CPP_STRING,
847 CPP_STRING16, or CPP_STRING32. Return CPP_OTHER in case of error.
848 This may not be exactly the string token type that initially created
849 the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
850 string type, and CPP_UTF8STRING is indistinguishable from CPP_STRING
851 at this point.
853 This effectively reverses part of the logic in lex_string and
854 fix_string_type. */
856 static enum cpp_ttype
857 get_cpp_ttype_from_string_type (tree string_type)
859 gcc_assert (string_type);
860 if (TREE_CODE (string_type) == POINTER_TYPE)
861 string_type = TREE_TYPE (string_type);
863 if (TREE_CODE (string_type) != ARRAY_TYPE)
864 return CPP_OTHER;
866 tree element_type = TREE_TYPE (string_type);
867 if (TREE_CODE (element_type) != INTEGER_TYPE)
868 return CPP_OTHER;
870 int bits_per_character = TYPE_PRECISION (element_type);
871 switch (bits_per_character)
873 case 8:
874 return CPP_STRING; /* It could have also been CPP_UTF8STRING. */
875 case 16:
876 return CPP_STRING16;
877 case 32:
878 return CPP_STRING32;
881 return CPP_OTHER;
884 /* The global record of string concatentations, for use in
885 extracting locations within string literals. */
887 GTY(()) string_concat_db *g_string_concat_db;
889 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION. */
891 const char *
892 c_get_substring_location (const substring_loc &substr_loc,
893 location_t *out_loc)
895 enum cpp_ttype tok_type
896 = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
897 if (tok_type == CPP_OTHER)
898 return "unrecognized string type";
900 return get_location_within_string (parse_in, g_string_concat_db,
901 substr_loc.get_fmt_string_loc (),
902 tok_type,
903 substr_loc.get_caret_idx (),
904 substr_loc.get_start_idx (),
905 substr_loc.get_end_idx (),
906 out_loc);
910 /* Return true iff T is a boolean promoted to int. */
912 bool
913 bool_promoted_to_int_p (tree t)
915 return (CONVERT_EXPR_P (t)
916 && TREE_TYPE (t) == integer_type_node
917 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
920 /* vector_targets_convertible_p is used for vector pointer types. The
921 callers perform various checks that the qualifiers are satisfactory,
922 while OTOH vector_targets_convertible_p ignores the number of elements
923 in the vectors. That's fine with vector pointers as we can consider,
924 say, a vector of 8 elements as two consecutive vectors of 4 elements,
925 and that does not require and conversion of the pointer values.
926 In contrast, vector_types_convertible_p and
927 vector_types_compatible_elements_p are used for vector value types. */
928 /* True if pointers to distinct types T1 and T2 can be converted to
929 each other without an explicit cast. Only returns true for opaque
930 vector types. */
931 bool
932 vector_targets_convertible_p (const_tree t1, const_tree t2)
934 if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
935 && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
936 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
937 return true;
939 return false;
942 /* vector_types_convertible_p is used for vector value types.
943 It could in principle call vector_targets_convertible_p as a subroutine,
944 but then the check for vector type would be duplicated with its callers,
945 and also the purpose of vector_targets_convertible_p would become
946 muddled.
947 Where vector_types_convertible_p returns true, a conversion might still be
948 needed to make the types match.
949 In contrast, vector_targets_convertible_p is used for vector pointer
950 values, and vector_types_compatible_elements_p is used specifically
951 in the context for binary operators, as a check if use is possible without
952 conversion. */
953 /* True if vector types T1 and T2 can be converted to each other
954 without an explicit cast. If EMIT_LAX_NOTE is true, and T1 and T2
955 can only be converted with -flax-vector-conversions yet that is not
956 in effect, emit a note telling the user about that option if such
957 a note has not previously been emitted. */
958 bool
959 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
961 static bool emitted_lax_note = false;
962 bool convertible_lax;
964 if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
965 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
966 return true;
968 convertible_lax =
969 (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
970 && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
971 || known_eq (TYPE_VECTOR_SUBPARTS (t1),
972 TYPE_VECTOR_SUBPARTS (t2)))
973 && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
974 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
976 if (!convertible_lax || flag_lax_vector_conversions)
977 return convertible_lax;
979 if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
980 && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
981 return true;
983 if (emit_lax_note && !emitted_lax_note)
985 emitted_lax_note = true;
986 inform (input_location, "use %<-flax-vector-conversions%> to permit "
987 "conversions between vectors with differing "
988 "element types or numbers of subparts");
991 return false;
994 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
995 and have vector types, V0 has the same type as V1, and the number of
996 elements of V0, V1, MASK is the same.
998 In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
999 called with two arguments. In this case implementation passes the
1000 first argument twice in order to share the same tree code. This fact
1001 could enable the mask-values being twice the vector length. This is
1002 an implementation accident and this semantics is not guaranteed to
1003 the user. */
1004 tree
1005 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
1006 bool complain)
1008 tree ret;
1009 bool wrap = true;
1010 bool maybe_const = false;
1011 bool two_arguments = false;
1013 if (v1 == NULL_TREE)
1015 two_arguments = true;
1016 v1 = v0;
1019 if (v0 == error_mark_node || v1 == error_mark_node
1020 || mask == error_mark_node)
1021 return error_mark_node;
1023 if (!gnu_vector_type_p (TREE_TYPE (mask))
1024 || !VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
1026 if (complain)
1027 error_at (loc, "%<__builtin_shuffle%> last argument must "
1028 "be an integer vector");
1029 return error_mark_node;
1032 if (!gnu_vector_type_p (TREE_TYPE (v0))
1033 || !gnu_vector_type_p (TREE_TYPE (v1)))
1035 if (complain)
1036 error_at (loc, "%<__builtin_shuffle%> arguments must be vectors");
1037 return error_mark_node;
1040 if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1042 if (complain)
1043 error_at (loc, "%<__builtin_shuffle%> argument vectors must be of "
1044 "the same type");
1045 return error_mark_node;
1048 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1049 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1050 && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1051 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1053 if (complain)
1054 error_at (loc, "%<__builtin_shuffle%> number of elements of the "
1055 "argument vector(s) and the mask vector should "
1056 "be the same");
1057 return error_mark_node;
1060 if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1061 != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1063 if (complain)
1064 error_at (loc, "%<__builtin_shuffle%> argument vector(s) inner type "
1065 "must have the same size as inner type of the mask");
1066 return error_mark_node;
1069 if (!c_dialect_cxx ())
1071 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1072 v0 = c_fully_fold (v0, false, &maybe_const);
1073 wrap &= maybe_const;
1075 if (two_arguments)
1076 v1 = v0 = save_expr (v0);
1077 else
1079 v1 = c_fully_fold (v1, false, &maybe_const);
1080 wrap &= maybe_const;
1083 mask = c_fully_fold (mask, false, &maybe_const);
1084 wrap &= maybe_const;
1086 else if (two_arguments)
1087 v1 = v0 = save_expr (v0);
1089 ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1091 if (!c_dialect_cxx () && !wrap)
1092 ret = c_wrap_maybe_const (ret, true);
1094 return ret;
1097 /* Build a VEC_CONVERT ifn for __builtin_convertvector builtin. */
1099 tree
1100 c_build_vec_convert (location_t loc1, tree expr, location_t loc2, tree type,
1101 bool complain)
1103 if (error_operand_p (type))
1104 return error_mark_node;
1105 if (error_operand_p (expr))
1106 return error_mark_node;
1108 if (!gnu_vector_type_p (TREE_TYPE (expr))
1109 || (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1110 && !VECTOR_FLOAT_TYPE_P (TREE_TYPE (expr))))
1112 if (complain)
1113 error_at (loc1, "%<__builtin_convertvector%> first argument must "
1114 "be an integer or floating vector");
1115 return error_mark_node;
1118 if (!gnu_vector_type_p (type)
1119 || (!VECTOR_INTEGER_TYPE_P (type) && !VECTOR_FLOAT_TYPE_P (type)))
1121 if (complain)
1122 error_at (loc2, "%<__builtin_convertvector%> second argument must "
1123 "be an integer or floating vector type");
1124 return error_mark_node;
1127 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (expr)),
1128 TYPE_VECTOR_SUBPARTS (type)))
1130 if (complain)
1131 error_at (loc1, "%<__builtin_convertvector%> number of elements "
1132 "of the first argument vector and the second argument "
1133 "vector type should be the same");
1134 return error_mark_node;
1137 if ((TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (expr)))
1138 == TYPE_MAIN_VARIANT (TREE_TYPE (type)))
1139 || (VECTOR_INTEGER_TYPE_P (TREE_TYPE (expr))
1140 && VECTOR_INTEGER_TYPE_P (type)
1141 && (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (expr)))
1142 == TYPE_PRECISION (TREE_TYPE (type)))))
1143 return build1_loc (loc1, VIEW_CONVERT_EXPR, type, expr);
1145 bool wrap = true;
1146 bool maybe_const = false;
1147 tree ret;
1148 if (!c_dialect_cxx ())
1150 /* Avoid C_MAYBE_CONST_EXPRs inside of VEC_CONVERT argument. */
1151 expr = c_fully_fold (expr, false, &maybe_const);
1152 wrap &= maybe_const;
1155 ret = build_call_expr_internal_loc (loc1, IFN_VEC_CONVERT, type, 1, expr);
1157 if (!wrap)
1158 ret = c_wrap_maybe_const (ret, true);
1160 return ret;
1163 /* Like tree.c:get_narrower, but retain conversion from C++0x scoped enum
1164 to integral type. */
1166 tree
1167 c_common_get_narrower (tree op, int *unsignedp_ptr)
1169 op = get_narrower (op, unsignedp_ptr);
1171 if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1172 && ENUM_IS_SCOPED (TREE_TYPE (op)))
1174 /* C++0x scoped enumerations don't implicitly convert to integral
1175 type; if we stripped an explicit conversion to a larger type we
1176 need to replace it so common_type will still work. */
1177 tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1178 TYPE_UNSIGNED (TREE_TYPE (op)));
1179 op = fold_convert (type, op);
1181 return op;
1184 /* This is a helper function of build_binary_op.
1186 For certain operations if both args were extended from the same
1187 smaller type, do the arithmetic in that type and then extend.
1189 BITWISE indicates a bitwise operation.
1190 For them, this optimization is safe only if
1191 both args are zero-extended or both are sign-extended.
1192 Otherwise, we might change the result.
1193 Eg, (short)-1 | (unsigned short)-1 is (int)-1
1194 but calculated in (unsigned short) it would be (unsigned short)-1.
1196 tree
1197 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1199 int unsigned0, unsigned1;
1200 tree arg0, arg1;
1201 int uns;
1202 tree type;
1204 /* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
1205 excessive narrowing when we call get_narrower below. For
1206 example, suppose that OP0 is of unsigned int extended
1207 from signed char and that RESULT_TYPE is long long int.
1208 If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1209 like
1211 (long long int) (unsigned int) signed_char
1213 which get_narrower would narrow down to
1215 (unsigned int) signed char
1217 If we do not cast OP0 first, get_narrower would return
1218 signed_char, which is inconsistent with the case of the
1219 explicit cast. */
1220 op0 = convert (result_type, op0);
1221 op1 = convert (result_type, op1);
1223 arg0 = c_common_get_narrower (op0, &unsigned0);
1224 arg1 = c_common_get_narrower (op1, &unsigned1);
1226 /* UNS is 1 if the operation to be done is an unsigned one. */
1227 uns = TYPE_UNSIGNED (result_type);
1229 /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1230 but it *requires* conversion to FINAL_TYPE. */
1232 if ((TYPE_PRECISION (TREE_TYPE (op0))
1233 == TYPE_PRECISION (TREE_TYPE (arg0)))
1234 && TREE_TYPE (op0) != result_type)
1235 unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1236 if ((TYPE_PRECISION (TREE_TYPE (op1))
1237 == TYPE_PRECISION (TREE_TYPE (arg1)))
1238 && TREE_TYPE (op1) != result_type)
1239 unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1241 /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
1243 /* For bitwise operations, signedness of nominal type
1244 does not matter. Consider only how operands were extended. */
1245 if (bitwise)
1246 uns = unsigned0;
1248 /* Note that in all three cases below we refrain from optimizing
1249 an unsigned operation on sign-extended args.
1250 That would not be valid. */
1252 /* Both args variable: if both extended in same way
1253 from same width, do it in that width.
1254 Do it unsigned if args were zero-extended. */
1255 if ((TYPE_PRECISION (TREE_TYPE (arg0))
1256 < TYPE_PRECISION (result_type))
1257 && (TYPE_PRECISION (TREE_TYPE (arg1))
1258 == TYPE_PRECISION (TREE_TYPE (arg0)))
1259 && unsigned0 == unsigned1
1260 && (unsigned0 || !uns))
1261 return c_common_signed_or_unsigned_type
1262 (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
1264 else if (TREE_CODE (arg0) == INTEGER_CST
1265 && (unsigned1 || !uns)
1266 && (TYPE_PRECISION (TREE_TYPE (arg1))
1267 < TYPE_PRECISION (result_type))
1268 && (type
1269 = c_common_signed_or_unsigned_type (unsigned1,
1270 TREE_TYPE (arg1)))
1271 && !POINTER_TYPE_P (type)
1272 && int_fits_type_p (arg0, type))
1273 return type;
1275 else if (TREE_CODE (arg1) == INTEGER_CST
1276 && (unsigned0 || !uns)
1277 && (TYPE_PRECISION (TREE_TYPE (arg0))
1278 < TYPE_PRECISION (result_type))
1279 && (type
1280 = c_common_signed_or_unsigned_type (unsigned0,
1281 TREE_TYPE (arg0)))
1282 && !POINTER_TYPE_P (type)
1283 && int_fits_type_p (arg1, type))
1284 return type;
1286 return result_type;
1289 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1290 real of type TO_TYPE. This is a helper function for unsafe_conversion_p. */
1292 static bool
1293 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1295 tree type_low_bound = TYPE_MIN_VALUE (from_type);
1296 tree type_high_bound = TYPE_MAX_VALUE (from_type);
1297 REAL_VALUE_TYPE real_low_bound =
1298 real_value_from_int_cst (0, type_low_bound);
1299 REAL_VALUE_TYPE real_high_bound =
1300 real_value_from_int_cst (0, type_high_bound);
1302 return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1303 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1306 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1307 to the complex/real/integer type TYPE. Function returns non-zero when:
1308 * EXPR is a constant which cannot be exactly converted to TYPE.
1309 * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1310 for EXPR type and TYPE being both integers or both real, or both
1311 complex.
1312 * EXPR is not a constant of complex type and TYPE is a real or
1313 an integer.
1314 * EXPR is not a constant of real type and TYPE is an integer.
1315 * EXPR is not a constant of integer type which cannot be
1316 exactly converted to real type.
1318 Function allows conversions between types of different signedness if
1319 CHECK_SIGN is false and can return SAFE_CONVERSION (zero) in that
1320 case. Function can return UNSAFE_SIGN if CHECK_SIGN is true.
1322 RESULT, when non-null is the result of the conversion. When constant
1323 it is included in the text of diagnostics.
1325 Function allows conversions from complex constants to non-complex types,
1326 provided that imaginary part is zero and real part can be safely converted
1327 to TYPE. */
1329 enum conversion_safety
1330 unsafe_conversion_p (tree type, tree expr, tree result, bool check_sign)
1332 enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1333 tree expr_type = TREE_TYPE (expr);
1335 expr = fold_for_warn (expr);
1337 if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1339 /* If type is complex, we are interested in compatibility with
1340 underlying type. */
1341 if (TREE_CODE (type) == COMPLEX_TYPE)
1342 type = TREE_TYPE (type);
1344 /* Warn for real constant that is not an exact integer converted
1345 to integer type. */
1346 if (TREE_CODE (expr_type) == REAL_TYPE
1347 && TREE_CODE (type) == INTEGER_TYPE)
1349 if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1350 give_warning = UNSAFE_REAL;
1352 /* Warn for an integer constant that does not fit into integer type. */
1353 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1354 && TREE_CODE (type) == INTEGER_TYPE
1355 && !int_fits_type_p (expr, type))
1357 if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1358 && tree_int_cst_sgn (expr) < 0)
1360 if (check_sign)
1361 give_warning = UNSAFE_SIGN;
1363 else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1365 if (check_sign)
1366 give_warning = UNSAFE_SIGN;
1368 else
1369 give_warning = UNSAFE_OTHER;
1371 else if (TREE_CODE (type) == REAL_TYPE)
1373 /* Warn for an integer constant that does not fit into real type. */
1374 if (TREE_CODE (expr_type) == INTEGER_TYPE)
1376 REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1377 if (!exact_real_truncate (TYPE_MODE (type), &a))
1378 give_warning = UNSAFE_REAL;
1380 /* Warn for a real constant that does not fit into a smaller
1381 real type. */
1382 else if (TREE_CODE (expr_type) == REAL_TYPE
1383 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1385 REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1386 if (!exact_real_truncate (TYPE_MODE (type), &a))
1387 give_warning = UNSAFE_REAL;
1392 else if (TREE_CODE (expr) == COMPLEX_CST)
1394 tree imag_part = TREE_IMAGPART (expr);
1395 /* Conversion from complex constant with zero imaginary part,
1396 perform check for conversion of real part. */
1397 if ((TREE_CODE (imag_part) == REAL_CST
1398 && real_zerop (imag_part))
1399 || (TREE_CODE (imag_part) == INTEGER_CST
1400 && integer_zerop (imag_part)))
1401 /* Note: in this branch we use recursive call to unsafe_conversion_p
1402 with different type of EXPR, but it is still safe, because when EXPR
1403 is a constant, it's type is not used in text of generated warnings
1404 (otherwise they could sound misleading). */
1405 return unsafe_conversion_p (type, TREE_REALPART (expr), result,
1406 check_sign);
1407 /* Conversion from complex constant with non-zero imaginary part. */
1408 else
1410 /* Conversion to complex type.
1411 Perform checks for both real and imaginary parts. */
1412 if (TREE_CODE (type) == COMPLEX_TYPE)
1414 enum conversion_safety re_safety =
1415 unsafe_conversion_p (type, TREE_REALPART (expr),
1416 result, check_sign);
1417 enum conversion_safety im_safety =
1418 unsafe_conversion_p (type, imag_part, result, check_sign);
1420 /* Merge the results into appropriate single warning. */
1422 /* Note: this case includes SAFE_CONVERSION, i.e. success. */
1423 if (re_safety == im_safety)
1424 give_warning = re_safety;
1425 else if (!re_safety && im_safety)
1426 give_warning = im_safety;
1427 else if (re_safety && !im_safety)
1428 give_warning = re_safety;
1429 else
1430 give_warning = UNSAFE_OTHER;
1432 /* Warn about conversion from complex to real or integer type. */
1433 else
1434 give_warning = UNSAFE_IMAGINARY;
1438 /* Checks for remaining case: EXPR is not constant. */
1439 else
1441 /* Warn for real types converted to integer types. */
1442 if (TREE_CODE (expr_type) == REAL_TYPE
1443 && TREE_CODE (type) == INTEGER_TYPE)
1444 give_warning = UNSAFE_REAL;
1446 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1447 && TREE_CODE (type) == INTEGER_TYPE)
1449 /* Don't warn about unsigned char y = 0xff, x = (int) y; */
1450 expr = get_unwidened (expr, 0);
1451 expr_type = TREE_TYPE (expr);
1453 /* Don't warn for short y; short x = ((int)y & 0xff); */
1454 if (TREE_CODE (expr) == BIT_AND_EXPR
1455 || TREE_CODE (expr) == BIT_IOR_EXPR
1456 || TREE_CODE (expr) == BIT_XOR_EXPR)
1458 /* If both args were extended from a shortest type,
1459 use that type if that is safe. */
1460 expr_type = shorten_binary_op (expr_type,
1461 TREE_OPERAND (expr, 0),
1462 TREE_OPERAND (expr, 1),
1463 /* bitwise */1);
1465 if (TREE_CODE (expr) == BIT_AND_EXPR)
1467 tree op0 = TREE_OPERAND (expr, 0);
1468 tree op1 = TREE_OPERAND (expr, 1);
1469 bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1470 bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1472 /* If one of the operands is a non-negative constant
1473 that fits in the target type, then the type of the
1474 other operand does not matter. */
1475 if ((TREE_CODE (op0) == INTEGER_CST
1476 && int_fits_type_p (op0, c_common_signed_type (type))
1477 && int_fits_type_p (op0, c_common_unsigned_type (type)))
1478 || (TREE_CODE (op1) == INTEGER_CST
1479 && int_fits_type_p (op1, c_common_signed_type (type))
1480 && int_fits_type_p (op1,
1481 c_common_unsigned_type (type))))
1482 return SAFE_CONVERSION;
1483 /* If constant is unsigned and fits in the target
1484 type, then the result will also fit. */
1485 else if ((TREE_CODE (op0) == INTEGER_CST
1486 && unsigned0
1487 && int_fits_type_p (op0, type))
1488 || (TREE_CODE (op1) == INTEGER_CST
1489 && unsigned1
1490 && int_fits_type_p (op1, type)))
1491 return SAFE_CONVERSION;
1494 /* Warn for integer types converted to smaller integer types. */
1495 if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1496 give_warning = UNSAFE_OTHER;
1498 /* When they are the same width but different signedness,
1499 then the value may change. */
1500 else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1501 && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1502 /* Even when converted to a bigger type, if the type is
1503 unsigned but expr is signed, then negative values
1504 will be changed. */
1505 || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1506 && check_sign)
1507 give_warning = UNSAFE_SIGN;
1510 /* Warn for integer types converted to real types if and only if
1511 all the range of values of the integer type cannot be
1512 represented by the real type. */
1513 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1514 && TREE_CODE (type) == REAL_TYPE)
1516 /* Don't warn about char y = 0xff; float x = (int) y; */
1517 expr = get_unwidened (expr, 0);
1518 expr_type = TREE_TYPE (expr);
1520 if (!int_safely_convertible_to_real_p (expr_type, type))
1521 give_warning = UNSAFE_OTHER;
1524 /* Warn for real types converted to smaller real types. */
1525 else if (TREE_CODE (expr_type) == REAL_TYPE
1526 && TREE_CODE (type) == REAL_TYPE
1527 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1528 give_warning = UNSAFE_REAL;
1530 /* Check conversion between two complex types. */
1531 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1532 && TREE_CODE (type) == COMPLEX_TYPE)
1534 /* Extract underlying types (i.e., type of real and imaginary
1535 parts) of expr_type and type. */
1536 tree from_type = TREE_TYPE (expr_type);
1537 tree to_type = TREE_TYPE (type);
1539 /* Warn for real types converted to integer types. */
1540 if (TREE_CODE (from_type) == REAL_TYPE
1541 && TREE_CODE (to_type) == INTEGER_TYPE)
1542 give_warning = UNSAFE_REAL;
1544 /* Warn for real types converted to smaller real types. */
1545 else if (TREE_CODE (from_type) == REAL_TYPE
1546 && TREE_CODE (to_type) == REAL_TYPE
1547 && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1548 give_warning = UNSAFE_REAL;
1550 /* Check conversion for complex integer types. Here implementation
1551 is simpler than for real-domain integers because it does not
1552 involve sophisticated cases, such as bitmasks, casts, etc. */
1553 else if (TREE_CODE (from_type) == INTEGER_TYPE
1554 && TREE_CODE (to_type) == INTEGER_TYPE)
1556 /* Warn for integer types converted to smaller integer types. */
1557 if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1558 give_warning = UNSAFE_OTHER;
1560 /* Check for different signedness, see case for real-domain
1561 integers (above) for a more detailed comment. */
1562 else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1563 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1564 || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1565 && check_sign)
1566 give_warning = UNSAFE_SIGN;
1568 else if (TREE_CODE (from_type) == INTEGER_TYPE
1569 && TREE_CODE (to_type) == REAL_TYPE
1570 && !int_safely_convertible_to_real_p (from_type, to_type))
1571 give_warning = UNSAFE_OTHER;
1574 /* Warn for complex types converted to real or integer types. */
1575 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1576 && TREE_CODE (type) != COMPLEX_TYPE)
1577 give_warning = UNSAFE_IMAGINARY;
1580 return give_warning;
1584 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1585 Invoke this function on every expression that is converted implicitly,
1586 i.e. because of language rules and not because of an explicit cast. */
1588 tree
1589 convert_and_check (location_t loc, tree type, tree expr)
1591 tree result;
1592 tree expr_for_warning;
1594 /* Convert from a value with possible excess precision rather than
1595 via the semantic type, but do not warn about values not fitting
1596 exactly in the semantic type. */
1597 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1599 tree orig_type = TREE_TYPE (expr);
1600 expr = TREE_OPERAND (expr, 0);
1601 expr_for_warning = convert (orig_type, expr);
1602 if (orig_type == type)
1603 return expr_for_warning;
1605 else
1606 expr_for_warning = expr;
1608 if (TREE_TYPE (expr) == type)
1609 return expr;
1611 result = convert (type, expr);
1613 if (c_inhibit_evaluation_warnings == 0
1614 && !TREE_OVERFLOW_P (expr)
1615 && result != error_mark_node)
1616 warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1618 return result;
1621 /* A node in a list that describes references to variables (EXPR), which are
1622 either read accesses if WRITER is zero, or write accesses, in which case
1623 WRITER is the parent of EXPR. */
1624 struct tlist
1626 struct tlist *next;
1627 tree expr, writer;
1630 /* Used to implement a cache the results of a call to verify_tree. We only
1631 use this for SAVE_EXPRs. */
1632 struct tlist_cache
1634 struct tlist_cache *next;
1635 struct tlist *cache_before_sp;
1636 struct tlist *cache_after_sp;
1637 tree expr;
1640 /* Obstack to use when allocating tlist structures, and corresponding
1641 firstobj. */
1642 static struct obstack tlist_obstack;
1643 static char *tlist_firstobj = 0;
1645 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1646 warnings. */
1647 static struct tlist *warned_ids;
1648 /* SAVE_EXPRs need special treatment. We process them only once and then
1649 cache the results. */
1650 static struct tlist_cache *save_expr_cache;
1652 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1653 static void merge_tlist (struct tlist **, struct tlist *, int);
1654 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1655 static bool warning_candidate_p (tree);
1656 static bool candidate_equal_p (const_tree, const_tree);
1657 static void warn_for_collisions (struct tlist *);
1658 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1659 static struct tlist *new_tlist (struct tlist *, tree, tree);
1661 /* Create a new struct tlist and fill in its fields. */
1662 static struct tlist *
1663 new_tlist (struct tlist *next, tree t, tree writer)
1665 struct tlist *l;
1666 l = XOBNEW (&tlist_obstack, struct tlist);
1667 l->next = next;
1668 l->expr = t;
1669 l->writer = writer;
1670 return l;
1673 /* Add duplicates of the nodes found in ADD to the list *TO. If EXCLUDE_WRITER
1674 is nonnull, we ignore any node we find which has a writer equal to it. */
1676 static void
1677 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1679 while (add)
1681 struct tlist *next = add->next;
1682 if (!copy)
1683 add->next = *to;
1684 if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1685 *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1686 add = next;
1690 /* Merge the nodes of ADD into TO. This merging process is done so that for
1691 each variable that already exists in TO, no new node is added; however if
1692 there is a write access recorded in ADD, and an occurrence on TO is only
1693 a read access, then the occurrence in TO will be modified to record the
1694 write. */
1696 static void
1697 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1699 struct tlist **end = to;
1701 while (*end)
1702 end = &(*end)->next;
1704 while (add)
1706 int found = 0;
1707 struct tlist *tmp2;
1708 struct tlist *next = add->next;
1710 for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1711 if (candidate_equal_p (tmp2->expr, add->expr))
1713 found = 1;
1714 if (!tmp2->writer)
1715 tmp2->writer = add->writer;
1717 if (!found)
1719 *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1720 end = &(*end)->next;
1721 *end = 0;
1723 add = next;
1727 /* WRITTEN is a variable, WRITER is its parent. Warn if any of the variable
1728 references in list LIST conflict with it, excluding reads if ONLY writers
1729 is nonzero. */
1731 static void
1732 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1733 int only_writes)
1735 struct tlist *tmp;
1737 /* Avoid duplicate warnings. */
1738 for (tmp = warned_ids; tmp; tmp = tmp->next)
1739 if (candidate_equal_p (tmp->expr, written))
1740 return;
1742 while (list)
1744 if (candidate_equal_p (list->expr, written)
1745 && !candidate_equal_p (list->writer, writer)
1746 && (!only_writes || list->writer))
1748 warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1749 warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1750 OPT_Wsequence_point, "operation on %qE may be undefined",
1751 list->expr);
1753 list = list->next;
1757 /* Given a list LIST of references to variables, find whether any of these
1758 can cause conflicts due to missing sequence points. */
1760 static void
1761 warn_for_collisions (struct tlist *list)
1763 struct tlist *tmp;
1765 for (tmp = list; tmp; tmp = tmp->next)
1767 if (tmp->writer)
1768 warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1772 /* Return nonzero if X is a tree that can be verified by the sequence point
1773 warnings. */
1775 static bool
1776 warning_candidate_p (tree x)
1778 if (DECL_P (x) && DECL_ARTIFICIAL (x))
1779 return false;
1781 if (TREE_CODE (x) == BLOCK)
1782 return false;
1784 /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.c
1785 (lvalue_p) crash on TRY/CATCH. */
1786 if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1787 return false;
1789 if (!lvalue_p (x))
1790 return false;
1792 /* No point to track non-const calls, they will never satisfy
1793 operand_equal_p. */
1794 if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1795 return false;
1797 if (TREE_CODE (x) == STRING_CST)
1798 return false;
1800 return true;
1803 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1804 static bool
1805 candidate_equal_p (const_tree x, const_tree y)
1807 return (x == y) || (x && y && operand_equal_p (x, y, 0));
1810 /* Walk the tree X, and record accesses to variables. If X is written by the
1811 parent tree, WRITER is the parent.
1812 We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP. If this
1813 expression or its only operand forces a sequence point, then everything up
1814 to the sequence point is stored in PBEFORE_SP. Everything else gets stored
1815 in PNO_SP.
1816 Once we return, we will have emitted warnings if any subexpression before
1817 such a sequence point could be undefined. On a higher level, however, the
1818 sequence point may not be relevant, and we'll merge the two lists.
1820 Example: (b++, a) + b;
1821 The call that processes the COMPOUND_EXPR will store the increment of B
1822 in PBEFORE_SP, and the use of A in PNO_SP. The higher-level call that
1823 processes the PLUS_EXPR will need to merge the two lists so that
1824 eventually, all accesses end up on the same list (and we'll warn about the
1825 unordered subexpressions b++ and b.
1827 A note on merging. If we modify the former example so that our expression
1828 becomes
1829 (b++, b) + a
1830 care must be taken not simply to add all three expressions into the final
1831 PNO_SP list. The function merge_tlist takes care of that by merging the
1832 before-SP list of the COMPOUND_EXPR into its after-SP list in a special
1833 way, so that no more than one access to B is recorded. */
1835 static void
1836 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
1837 tree writer)
1839 struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
1840 enum tree_code code;
1841 enum tree_code_class cl;
1843 /* X may be NULL if it is the operand of an empty statement expression
1844 ({ }). */
1845 if (x == NULL)
1846 return;
1848 restart:
1849 code = TREE_CODE (x);
1850 cl = TREE_CODE_CLASS (code);
1852 if (warning_candidate_p (x))
1853 *pno_sp = new_tlist (*pno_sp, x, writer);
1855 switch (code)
1857 case CONSTRUCTOR:
1858 case SIZEOF_EXPR:
1859 case PAREN_SIZEOF_EXPR:
1860 return;
1862 case COMPOUND_EXPR:
1863 case TRUTH_ANDIF_EXPR:
1864 case TRUTH_ORIF_EXPR:
1865 sequenced_binary:
1866 tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
1867 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1868 warn_for_collisions (tmp_nosp);
1869 merge_tlist (pbefore_sp, tmp_before, 0);
1870 merge_tlist (pbefore_sp, tmp_nosp, 0);
1871 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
1872 warn_for_collisions (tmp_list2);
1873 merge_tlist (pbefore_sp, tmp_list3, 0);
1874 merge_tlist (pno_sp, tmp_list2, 0);
1875 return;
1877 case COND_EXPR:
1878 tmp_before = tmp_list2 = 0;
1879 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
1880 warn_for_collisions (tmp_list2);
1881 merge_tlist (pbefore_sp, tmp_before, 0);
1882 merge_tlist (pbefore_sp, tmp_list2, 0);
1884 tmp_list3 = tmp_nosp = 0;
1885 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
1886 warn_for_collisions (tmp_nosp);
1887 merge_tlist (pbefore_sp, tmp_list3, 0);
1889 tmp_list3 = tmp_list2 = 0;
1890 verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
1891 warn_for_collisions (tmp_list2);
1892 merge_tlist (pbefore_sp, tmp_list3, 0);
1893 /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
1894 two first, to avoid warning for (a ? b++ : b++). */
1895 merge_tlist (&tmp_nosp, tmp_list2, 0);
1896 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1897 return;
1899 case PREDECREMENT_EXPR:
1900 case PREINCREMENT_EXPR:
1901 case POSTDECREMENT_EXPR:
1902 case POSTINCREMENT_EXPR:
1903 verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
1904 return;
1906 case MODIFY_EXPR:
1907 tmp_before = tmp_nosp = tmp_list3 = 0;
1908 verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
1909 verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
1910 /* Expressions inside the LHS are not ordered wrt. the sequence points
1911 in the RHS. Example:
1912 *a = (a++, 2)
1913 Despite the fact that the modification of "a" is in the before_sp
1914 list (tmp_before), it conflicts with the use of "a" in the LHS.
1915 We can handle this by adding the contents of tmp_list3
1916 to those of tmp_before, and redoing the collision warnings for that
1917 list. */
1918 add_tlist (&tmp_before, tmp_list3, x, 1);
1919 warn_for_collisions (tmp_before);
1920 /* Exclude the LHS itself here; we first have to merge it into the
1921 tmp_nosp list. This is done to avoid warning for "a = a"; if we
1922 didn't exclude the LHS, we'd get it twice, once as a read and once
1923 as a write. */
1924 add_tlist (pno_sp, tmp_list3, x, 0);
1925 warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
1927 merge_tlist (pbefore_sp, tmp_before, 0);
1928 if (warning_candidate_p (TREE_OPERAND (x, 0)))
1929 merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
1930 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
1931 return;
1933 case CALL_EXPR:
1934 /* We need to warn about conflicts among arguments and conflicts between
1935 args and the function address. Side effects of the function address,
1936 however, are not ordered by the sequence point of the call. */
1938 call_expr_arg_iterator iter;
1939 tree arg;
1940 tmp_before = tmp_nosp = 0;
1941 verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
1942 FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
1944 tmp_list2 = tmp_list3 = 0;
1945 verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
1946 merge_tlist (&tmp_list3, tmp_list2, 0);
1947 add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
1949 add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
1950 warn_for_collisions (tmp_before);
1951 add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
1952 return;
1955 case TREE_LIST:
1956 /* Scan all the list, e.g. indices of multi dimensional array. */
1957 while (x)
1959 tmp_before = tmp_nosp = 0;
1960 verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
1961 merge_tlist (&tmp_nosp, tmp_before, 0);
1962 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1963 x = TREE_CHAIN (x);
1965 return;
1967 case SAVE_EXPR:
1969 struct tlist_cache *t;
1970 for (t = save_expr_cache; t; t = t->next)
1971 if (candidate_equal_p (t->expr, x))
1972 break;
1974 if (!t)
1976 t = XOBNEW (&tlist_obstack, struct tlist_cache);
1977 t->next = save_expr_cache;
1978 t->expr = x;
1979 save_expr_cache = t;
1981 tmp_before = tmp_nosp = 0;
1982 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1983 warn_for_collisions (tmp_nosp);
1985 tmp_list3 = 0;
1986 merge_tlist (&tmp_list3, tmp_nosp, 0);
1987 t->cache_before_sp = tmp_before;
1988 t->cache_after_sp = tmp_list3;
1990 merge_tlist (pbefore_sp, t->cache_before_sp, 1);
1991 add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
1992 return;
1995 case ADDR_EXPR:
1996 x = TREE_OPERAND (x, 0);
1997 if (DECL_P (x))
1998 return;
1999 writer = 0;
2000 goto restart;
2002 case VIEW_CONVERT_EXPR:
2003 if (location_wrapper_p (x))
2005 x = TREE_OPERAND (x, 0);
2006 goto restart;
2008 goto do_default;
2010 case LSHIFT_EXPR:
2011 case RSHIFT_EXPR:
2012 case COMPONENT_REF:
2013 case ARRAY_REF:
2014 if (cxx_dialect >= cxx17)
2015 goto sequenced_binary;
2016 goto do_default;
2018 default:
2019 do_default:
2020 /* For other expressions, simply recurse on their operands.
2021 Manual tail recursion for unary expressions.
2022 Other non-expressions need not be processed. */
2023 if (cl == tcc_unary)
2025 x = TREE_OPERAND (x, 0);
2026 writer = 0;
2027 goto restart;
2029 else if (IS_EXPR_CODE_CLASS (cl))
2031 int lp;
2032 int max = TREE_OPERAND_LENGTH (x);
2033 for (lp = 0; lp < max; lp++)
2035 tmp_before = tmp_nosp = 0;
2036 verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
2037 merge_tlist (&tmp_nosp, tmp_before, 0);
2038 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
2041 return;
2045 /* Try to warn for undefined behavior in EXPR due to missing sequence
2046 points. */
2048 DEBUG_FUNCTION void
2049 verify_sequence_points (tree expr)
2051 struct tlist *before_sp = 0, *after_sp = 0;
2053 warned_ids = 0;
2054 save_expr_cache = 0;
2055 if (tlist_firstobj == 0)
2057 gcc_obstack_init (&tlist_obstack);
2058 tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
2061 verify_tree (expr, &before_sp, &after_sp, 0);
2062 warn_for_collisions (after_sp);
2063 obstack_free (&tlist_obstack, tlist_firstobj);
2066 /* Validate the expression after `case' and apply default promotions. */
2068 static tree
2069 check_case_value (location_t loc, tree value)
2071 if (value == NULL_TREE)
2072 return value;
2074 if (TREE_CODE (value) == INTEGER_CST)
2075 /* Promote char or short to int. */
2076 value = perform_integral_promotions (value);
2077 else if (value != error_mark_node)
2079 error_at (loc, "case label does not reduce to an integer constant");
2080 value = error_mark_node;
2083 constant_expression_warning (value);
2085 return value;
2088 /* Return an integer type with BITS bits of precision,
2089 that is unsigned if UNSIGNEDP is nonzero, otherwise signed. */
2091 tree
2092 c_common_type_for_size (unsigned int bits, int unsignedp)
2094 int i;
2096 if (bits == TYPE_PRECISION (integer_type_node))
2097 return unsignedp ? unsigned_type_node : integer_type_node;
2099 if (bits == TYPE_PRECISION (signed_char_type_node))
2100 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2102 if (bits == TYPE_PRECISION (short_integer_type_node))
2103 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2105 if (bits == TYPE_PRECISION (long_integer_type_node))
2106 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2108 if (bits == TYPE_PRECISION (long_long_integer_type_node))
2109 return (unsignedp ? long_long_unsigned_type_node
2110 : long_long_integer_type_node);
2112 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2113 if (int_n_enabled_p[i]
2114 && bits == int_n_data[i].bitsize)
2115 return (unsignedp ? int_n_trees[i].unsigned_type
2116 : int_n_trees[i].signed_type);
2118 if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2119 return (unsignedp ? widest_unsigned_literal_type_node
2120 : widest_integer_literal_type_node);
2122 if (bits <= TYPE_PRECISION (intQI_type_node))
2123 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2125 if (bits <= TYPE_PRECISION (intHI_type_node))
2126 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2128 if (bits <= TYPE_PRECISION (intSI_type_node))
2129 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2131 if (bits <= TYPE_PRECISION (intDI_type_node))
2132 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2134 return NULL_TREE;
2137 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2138 that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2139 and saturating if SATP is nonzero, otherwise not saturating. */
2141 tree
2142 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2143 int unsignedp, int satp)
2145 enum mode_class mclass;
2146 if (ibit == 0)
2147 mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2148 else
2149 mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2151 opt_scalar_mode opt_mode;
2152 scalar_mode mode;
2153 FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2155 mode = opt_mode.require ();
2156 if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2157 break;
2160 if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2162 sorry ("GCC cannot support operators with integer types and "
2163 "fixed-point types that have too many integral and "
2164 "fractional bits together");
2165 return NULL_TREE;
2168 return c_common_type_for_mode (mode, satp);
2171 /* Used for communication between c_common_type_for_mode and
2172 c_register_builtin_type. */
2173 tree registered_builtin_types;
2175 /* Return a data type that has machine mode MODE.
2176 If the mode is an integer,
2177 then UNSIGNEDP selects between signed and unsigned types.
2178 If the mode is a fixed-point mode,
2179 then UNSIGNEDP selects between saturating and nonsaturating types. */
2181 tree
2182 c_common_type_for_mode (machine_mode mode, int unsignedp)
2184 tree t;
2185 int i;
2187 if (mode == TYPE_MODE (integer_type_node))
2188 return unsignedp ? unsigned_type_node : integer_type_node;
2190 if (mode == TYPE_MODE (signed_char_type_node))
2191 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2193 if (mode == TYPE_MODE (short_integer_type_node))
2194 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2196 if (mode == TYPE_MODE (long_integer_type_node))
2197 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2199 if (mode == TYPE_MODE (long_long_integer_type_node))
2200 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2202 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2203 if (int_n_enabled_p[i]
2204 && mode == int_n_data[i].m)
2205 return (unsignedp ? int_n_trees[i].unsigned_type
2206 : int_n_trees[i].signed_type);
2208 if (mode == QImode)
2209 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2211 if (mode == HImode)
2212 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2214 if (mode == SImode)
2215 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2217 if (mode == DImode)
2218 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2220 #if HOST_BITS_PER_WIDE_INT >= 64
2221 if (mode == TYPE_MODE (intTI_type_node))
2222 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2223 #endif
2225 if (mode == TYPE_MODE (float_type_node))
2226 return float_type_node;
2228 if (mode == TYPE_MODE (double_type_node))
2229 return double_type_node;
2231 if (mode == TYPE_MODE (long_double_type_node))
2232 return long_double_type_node;
2234 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2235 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2236 && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2237 return FLOATN_NX_TYPE_NODE (i);
2239 if (mode == TYPE_MODE (void_type_node))
2240 return void_type_node;
2242 if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2243 || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2245 unsigned int precision
2246 = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2247 return (unsignedp
2248 ? make_unsigned_type (precision)
2249 : make_signed_type (precision));
2252 if (COMPLEX_MODE_P (mode))
2254 machine_mode inner_mode;
2255 tree inner_type;
2257 if (mode == TYPE_MODE (complex_float_type_node))
2258 return complex_float_type_node;
2259 if (mode == TYPE_MODE (complex_double_type_node))
2260 return complex_double_type_node;
2261 if (mode == TYPE_MODE (complex_long_double_type_node))
2262 return complex_long_double_type_node;
2264 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2265 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2266 && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2267 return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2269 if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2270 return complex_integer_type_node;
2272 inner_mode = GET_MODE_INNER (mode);
2273 inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2274 if (inner_type != NULL_TREE)
2275 return build_complex_type (inner_type);
2277 else if (GET_MODE_CLASS (mode) == MODE_VECTOR_BOOL
2278 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2280 unsigned int elem_bits = vector_element_size (GET_MODE_BITSIZE (mode),
2281 GET_MODE_NUNITS (mode));
2282 tree bool_type = build_nonstandard_boolean_type (elem_bits);
2283 return build_vector_type_for_mode (bool_type, mode);
2285 else if (VECTOR_MODE_P (mode)
2286 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2288 machine_mode inner_mode = GET_MODE_INNER (mode);
2289 tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2290 if (inner_type != NULL_TREE)
2291 return build_vector_type_for_mode (inner_type, mode);
2294 if (dfloat32_type_node != NULL_TREE
2295 && mode == TYPE_MODE (dfloat32_type_node))
2296 return dfloat32_type_node;
2297 if (dfloat64_type_node != NULL_TREE
2298 && mode == TYPE_MODE (dfloat64_type_node))
2299 return dfloat64_type_node;
2300 if (dfloat128_type_node != NULL_TREE
2301 && mode == TYPE_MODE (dfloat128_type_node))
2302 return dfloat128_type_node;
2304 if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2306 if (mode == TYPE_MODE (short_fract_type_node))
2307 return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2308 if (mode == TYPE_MODE (fract_type_node))
2309 return unsignedp ? sat_fract_type_node : fract_type_node;
2310 if (mode == TYPE_MODE (long_fract_type_node))
2311 return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2312 if (mode == TYPE_MODE (long_long_fract_type_node))
2313 return unsignedp ? sat_long_long_fract_type_node
2314 : long_long_fract_type_node;
2316 if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2317 return unsignedp ? sat_unsigned_short_fract_type_node
2318 : unsigned_short_fract_type_node;
2319 if (mode == TYPE_MODE (unsigned_fract_type_node))
2320 return unsignedp ? sat_unsigned_fract_type_node
2321 : unsigned_fract_type_node;
2322 if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2323 return unsignedp ? sat_unsigned_long_fract_type_node
2324 : unsigned_long_fract_type_node;
2325 if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2326 return unsignedp ? sat_unsigned_long_long_fract_type_node
2327 : unsigned_long_long_fract_type_node;
2329 if (mode == TYPE_MODE (short_accum_type_node))
2330 return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2331 if (mode == TYPE_MODE (accum_type_node))
2332 return unsignedp ? sat_accum_type_node : accum_type_node;
2333 if (mode == TYPE_MODE (long_accum_type_node))
2334 return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2335 if (mode == TYPE_MODE (long_long_accum_type_node))
2336 return unsignedp ? sat_long_long_accum_type_node
2337 : long_long_accum_type_node;
2339 if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2340 return unsignedp ? sat_unsigned_short_accum_type_node
2341 : unsigned_short_accum_type_node;
2342 if (mode == TYPE_MODE (unsigned_accum_type_node))
2343 return unsignedp ? sat_unsigned_accum_type_node
2344 : unsigned_accum_type_node;
2345 if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2346 return unsignedp ? sat_unsigned_long_accum_type_node
2347 : unsigned_long_accum_type_node;
2348 if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2349 return unsignedp ? sat_unsigned_long_long_accum_type_node
2350 : unsigned_long_long_accum_type_node;
2352 if (mode == QQmode)
2353 return unsignedp ? sat_qq_type_node : qq_type_node;
2354 if (mode == HQmode)
2355 return unsignedp ? sat_hq_type_node : hq_type_node;
2356 if (mode == SQmode)
2357 return unsignedp ? sat_sq_type_node : sq_type_node;
2358 if (mode == DQmode)
2359 return unsignedp ? sat_dq_type_node : dq_type_node;
2360 if (mode == TQmode)
2361 return unsignedp ? sat_tq_type_node : tq_type_node;
2363 if (mode == UQQmode)
2364 return unsignedp ? sat_uqq_type_node : uqq_type_node;
2365 if (mode == UHQmode)
2366 return unsignedp ? sat_uhq_type_node : uhq_type_node;
2367 if (mode == USQmode)
2368 return unsignedp ? sat_usq_type_node : usq_type_node;
2369 if (mode == UDQmode)
2370 return unsignedp ? sat_udq_type_node : udq_type_node;
2371 if (mode == UTQmode)
2372 return unsignedp ? sat_utq_type_node : utq_type_node;
2374 if (mode == HAmode)
2375 return unsignedp ? sat_ha_type_node : ha_type_node;
2376 if (mode == SAmode)
2377 return unsignedp ? sat_sa_type_node : sa_type_node;
2378 if (mode == DAmode)
2379 return unsignedp ? sat_da_type_node : da_type_node;
2380 if (mode == TAmode)
2381 return unsignedp ? sat_ta_type_node : ta_type_node;
2383 if (mode == UHAmode)
2384 return unsignedp ? sat_uha_type_node : uha_type_node;
2385 if (mode == USAmode)
2386 return unsignedp ? sat_usa_type_node : usa_type_node;
2387 if (mode == UDAmode)
2388 return unsignedp ? sat_uda_type_node : uda_type_node;
2389 if (mode == UTAmode)
2390 return unsignedp ? sat_uta_type_node : uta_type_node;
2393 for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2395 tree type = TREE_VALUE (t);
2396 if (TYPE_MODE (type) == mode
2397 && VECTOR_TYPE_P (type) == VECTOR_MODE_P (mode)
2398 && !!unsignedp == !!TYPE_UNSIGNED (type))
2399 return type;
2401 return NULL_TREE;
2404 tree
2405 c_common_unsigned_type (tree type)
2407 return c_common_signed_or_unsigned_type (1, type);
2410 /* Return a signed type the same as TYPE in other respects. */
2412 tree
2413 c_common_signed_type (tree type)
2415 return c_common_signed_or_unsigned_type (0, type);
2418 /* Return a type the same as TYPE except unsigned or
2419 signed according to UNSIGNEDP. */
2421 tree
2422 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2424 tree type1;
2425 int i;
2427 /* This block of code emulates the behavior of the old
2428 c_common_unsigned_type. In particular, it returns
2429 long_unsigned_type_node if passed a long, even when a int would
2430 have the same size. This is necessary for warnings to work
2431 correctly in archs where sizeof(int) == sizeof(long) */
2433 type1 = TYPE_MAIN_VARIANT (type);
2434 if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2435 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2436 if (type1 == integer_type_node || type1 == unsigned_type_node)
2437 return unsignedp ? unsigned_type_node : integer_type_node;
2438 if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2439 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2440 if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2441 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2442 if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2443 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2445 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2446 if (int_n_enabled_p[i]
2447 && (type1 == int_n_trees[i].unsigned_type
2448 || type1 == int_n_trees[i].signed_type))
2449 return (unsignedp ? int_n_trees[i].unsigned_type
2450 : int_n_trees[i].signed_type);
2452 #if HOST_BITS_PER_WIDE_INT >= 64
2453 if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2454 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2455 #endif
2456 if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2457 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2458 if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2459 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2460 if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2461 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2462 if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2463 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2465 #define C_COMMON_FIXED_TYPES(NAME) \
2466 if (type1 == short_ ## NAME ## _type_node \
2467 || type1 == unsigned_short_ ## NAME ## _type_node) \
2468 return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2469 : short_ ## NAME ## _type_node; \
2470 if (type1 == NAME ## _type_node \
2471 || type1 == unsigned_ ## NAME ## _type_node) \
2472 return unsignedp ? unsigned_ ## NAME ## _type_node \
2473 : NAME ## _type_node; \
2474 if (type1 == long_ ## NAME ## _type_node \
2475 || type1 == unsigned_long_ ## NAME ## _type_node) \
2476 return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2477 : long_ ## NAME ## _type_node; \
2478 if (type1 == long_long_ ## NAME ## _type_node \
2479 || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2480 return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2481 : long_long_ ## NAME ## _type_node;
2483 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2484 if (type1 == NAME ## _type_node \
2485 || type1 == u ## NAME ## _type_node) \
2486 return unsignedp ? u ## NAME ## _type_node \
2487 : NAME ## _type_node;
2489 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2490 if (type1 == sat_ ## short_ ## NAME ## _type_node \
2491 || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2492 return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2493 : sat_ ## short_ ## NAME ## _type_node; \
2494 if (type1 == sat_ ## NAME ## _type_node \
2495 || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2496 return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2497 : sat_ ## NAME ## _type_node; \
2498 if (type1 == sat_ ## long_ ## NAME ## _type_node \
2499 || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2500 return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2501 : sat_ ## long_ ## NAME ## _type_node; \
2502 if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2503 || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2504 return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2505 : sat_ ## long_long_ ## NAME ## _type_node;
2507 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME) \
2508 if (type1 == sat_ ## NAME ## _type_node \
2509 || type1 == sat_ ## u ## NAME ## _type_node) \
2510 return unsignedp ? sat_ ## u ## NAME ## _type_node \
2511 : sat_ ## NAME ## _type_node;
2513 C_COMMON_FIXED_TYPES (fract);
2514 C_COMMON_FIXED_TYPES_SAT (fract);
2515 C_COMMON_FIXED_TYPES (accum);
2516 C_COMMON_FIXED_TYPES_SAT (accum);
2518 C_COMMON_FIXED_MODE_TYPES (qq);
2519 C_COMMON_FIXED_MODE_TYPES (hq);
2520 C_COMMON_FIXED_MODE_TYPES (sq);
2521 C_COMMON_FIXED_MODE_TYPES (dq);
2522 C_COMMON_FIXED_MODE_TYPES (tq);
2523 C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2524 C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2525 C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2526 C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2527 C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2528 C_COMMON_FIXED_MODE_TYPES (ha);
2529 C_COMMON_FIXED_MODE_TYPES (sa);
2530 C_COMMON_FIXED_MODE_TYPES (da);
2531 C_COMMON_FIXED_MODE_TYPES (ta);
2532 C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2533 C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2534 C_COMMON_FIXED_MODE_TYPES_SAT (da);
2535 C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2537 /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2538 the precision; they have precision set to match their range, but
2539 may use a wider mode to match an ABI. If we change modes, we may
2540 wind up with bad conversions. For INTEGER_TYPEs in C, must check
2541 the precision as well, so as to yield correct results for
2542 bit-field types. C++ does not have these separate bit-field
2543 types, and producing a signed or unsigned variant of an
2544 ENUMERAL_TYPE may cause other problems as well. */
2546 if (!INTEGRAL_TYPE_P (type)
2547 || TYPE_UNSIGNED (type) == unsignedp)
2548 return type;
2550 #define TYPE_OK(node) \
2551 (TYPE_MODE (type) == TYPE_MODE (node) \
2552 && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2553 if (TYPE_OK (signed_char_type_node))
2554 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2555 if (TYPE_OK (integer_type_node))
2556 return unsignedp ? unsigned_type_node : integer_type_node;
2557 if (TYPE_OK (short_integer_type_node))
2558 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2559 if (TYPE_OK (long_integer_type_node))
2560 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2561 if (TYPE_OK (long_long_integer_type_node))
2562 return (unsignedp ? long_long_unsigned_type_node
2563 : long_long_integer_type_node);
2565 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2566 if (int_n_enabled_p[i]
2567 && TYPE_MODE (type) == int_n_data[i].m
2568 && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2569 return (unsignedp ? int_n_trees[i].unsigned_type
2570 : int_n_trees[i].signed_type);
2572 #if HOST_BITS_PER_WIDE_INT >= 64
2573 if (TYPE_OK (intTI_type_node))
2574 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2575 #endif
2576 if (TYPE_OK (intDI_type_node))
2577 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2578 if (TYPE_OK (intSI_type_node))
2579 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2580 if (TYPE_OK (intHI_type_node))
2581 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2582 if (TYPE_OK (intQI_type_node))
2583 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2584 #undef TYPE_OK
2586 return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2589 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP. */
2591 tree
2592 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2594 int i;
2596 /* Extended integer types of the same width as a standard type have
2597 lesser rank, so those of the same width as int promote to int or
2598 unsigned int and are valid for printf formats expecting int or
2599 unsigned int. To avoid such special cases, avoid creating
2600 extended integer types for bit-fields if a standard integer type
2601 is available. */
2602 if (width == TYPE_PRECISION (integer_type_node))
2603 return unsignedp ? unsigned_type_node : integer_type_node;
2604 if (width == TYPE_PRECISION (signed_char_type_node))
2605 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2606 if (width == TYPE_PRECISION (short_integer_type_node))
2607 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2608 if (width == TYPE_PRECISION (long_integer_type_node))
2609 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2610 if (width == TYPE_PRECISION (long_long_integer_type_node))
2611 return (unsignedp ? long_long_unsigned_type_node
2612 : long_long_integer_type_node);
2613 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2614 if (int_n_enabled_p[i]
2615 && width == int_n_data[i].bitsize)
2616 return (unsignedp ? int_n_trees[i].unsigned_type
2617 : int_n_trees[i].signed_type);
2618 return build_nonstandard_integer_type (width, unsignedp);
2621 /* The C version of the register_builtin_type langhook. */
2623 void
2624 c_register_builtin_type (tree type, const char* name)
2626 tree decl;
2628 decl = build_decl (UNKNOWN_LOCATION,
2629 TYPE_DECL, get_identifier (name), type);
2630 DECL_ARTIFICIAL (decl) = 1;
2631 if (!TYPE_NAME (type))
2632 TYPE_NAME (type) = decl;
2633 lang_hooks.decls.pushdecl (decl);
2635 registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2638 /* Print an error message for invalid operands to arith operation
2639 CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2640 RICHLOC is a rich location for the message, containing either
2641 three separate locations for each of the operator and operands
2643 lhs op rhs
2644 ~~~ ^~ ~~~
2646 (C FE), or one location ranging over all over them
2648 lhs op rhs
2649 ~~~~^~~~~~
2651 (C++ FE). */
2653 void
2654 binary_op_error (rich_location *richloc, enum tree_code code,
2655 tree type0, tree type1)
2657 const char *opname;
2659 switch (code)
2661 case PLUS_EXPR:
2662 opname = "+"; break;
2663 case MINUS_EXPR:
2664 opname = "-"; break;
2665 case MULT_EXPR:
2666 opname = "*"; break;
2667 case MAX_EXPR:
2668 opname = "max"; break;
2669 case MIN_EXPR:
2670 opname = "min"; break;
2671 case EQ_EXPR:
2672 opname = "=="; break;
2673 case NE_EXPR:
2674 opname = "!="; break;
2675 case LE_EXPR:
2676 opname = "<="; break;
2677 case GE_EXPR:
2678 opname = ">="; break;
2679 case LT_EXPR:
2680 opname = "<"; break;
2681 case GT_EXPR:
2682 opname = ">"; break;
2683 case LSHIFT_EXPR:
2684 opname = "<<"; break;
2685 case RSHIFT_EXPR:
2686 opname = ">>"; break;
2687 case TRUNC_MOD_EXPR:
2688 case FLOOR_MOD_EXPR:
2689 opname = "%"; break;
2690 case TRUNC_DIV_EXPR:
2691 case FLOOR_DIV_EXPR:
2692 opname = "/"; break;
2693 case BIT_AND_EXPR:
2694 opname = "&"; break;
2695 case BIT_IOR_EXPR:
2696 opname = "|"; break;
2697 case TRUTH_ANDIF_EXPR:
2698 opname = "&&"; break;
2699 case TRUTH_ORIF_EXPR:
2700 opname = "||"; break;
2701 case BIT_XOR_EXPR:
2702 opname = "^"; break;
2703 default:
2704 gcc_unreachable ();
2706 error_at (richloc,
2707 "invalid operands to binary %s (have %qT and %qT)",
2708 opname, type0, type1);
2711 /* Given an expression as a tree, return its original type. Do this
2712 by stripping any conversion that preserves the sign and precision. */
2713 static tree
2714 expr_original_type (tree expr)
2716 STRIP_SIGN_NOPS (expr);
2717 return TREE_TYPE (expr);
2720 /* Subroutine of build_binary_op, used for comparison operations.
2721 See if the operands have both been converted from subword integer types
2722 and, if so, perhaps change them both back to their original type.
2723 This function is also responsible for converting the two operands
2724 to the proper common type for comparison.
2726 The arguments of this function are all pointers to local variables
2727 of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2728 RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2730 LOC is the location of the comparison.
2732 If this function returns non-NULL_TREE, it means that the comparison has
2733 a constant value. What this function returns is an expression for
2734 that value. */
2736 tree
2737 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2738 tree *restype_ptr, enum tree_code *rescode_ptr)
2740 tree type;
2741 tree op0 = *op0_ptr;
2742 tree op1 = *op1_ptr;
2743 int unsignedp0, unsignedp1;
2744 int real1, real2;
2745 tree primop0, primop1;
2746 enum tree_code code = *rescode_ptr;
2748 /* Throw away any conversions to wider types
2749 already present in the operands. */
2751 primop0 = c_common_get_narrower (op0, &unsignedp0);
2752 primop1 = c_common_get_narrower (op1, &unsignedp1);
2754 /* If primopN is first sign-extended from primopN's precision to opN's
2755 precision, then zero-extended from opN's precision to
2756 *restype_ptr precision, shortenings might be invalid. */
2757 if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2758 && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2759 && !unsignedp0
2760 && TYPE_UNSIGNED (TREE_TYPE (op0)))
2761 primop0 = op0;
2762 if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2763 && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2764 && !unsignedp1
2765 && TYPE_UNSIGNED (TREE_TYPE (op1)))
2766 primop1 = op1;
2768 /* Handle the case that OP0 does not *contain* a conversion
2769 but it *requires* conversion to FINAL_TYPE. */
2771 if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2772 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2773 if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2774 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2776 /* If one of the operands must be floated, we cannot optimize. */
2777 real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
2778 real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
2780 /* If first arg is constant, swap the args (changing operation
2781 so value is preserved), for canonicalization. Don't do this if
2782 the second arg is 0. */
2784 if (TREE_CONSTANT (primop0)
2785 && !integer_zerop (primop1) && !real_zerop (primop1)
2786 && !fixed_zerop (primop1))
2788 std::swap (primop0, primop1);
2789 std::swap (op0, op1);
2790 *op0_ptr = op0;
2791 *op1_ptr = op1;
2792 std::swap (unsignedp0, unsignedp1);
2793 std::swap (real1, real2);
2795 switch (code)
2797 case LT_EXPR:
2798 code = GT_EXPR;
2799 break;
2800 case GT_EXPR:
2801 code = LT_EXPR;
2802 break;
2803 case LE_EXPR:
2804 code = GE_EXPR;
2805 break;
2806 case GE_EXPR:
2807 code = LE_EXPR;
2808 break;
2809 default:
2810 break;
2812 *rescode_ptr = code;
2815 /* If comparing an integer against a constant more bits wide,
2816 maybe we can deduce a value of 1 or 0 independent of the data.
2817 Or else truncate the constant now
2818 rather than extend the variable at run time.
2820 This is only interesting if the constant is the wider arg.
2821 Also, it is not safe if the constant is unsigned and the
2822 variable arg is signed, since in this case the variable
2823 would be sign-extended and then regarded as unsigned.
2824 Our technique fails in this case because the lowest/highest
2825 possible unsigned results don't follow naturally from the
2826 lowest/highest possible values of the variable operand.
2827 For just EQ_EXPR and NE_EXPR there is another technique that
2828 could be used: see if the constant can be faithfully represented
2829 in the other operand's type, by truncating it and reextending it
2830 and see if that preserves the constant's value. */
2832 if (!real1 && !real2
2833 && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
2834 && TREE_CODE (primop1) == INTEGER_CST
2835 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
2837 int min_gt, max_gt, min_lt, max_lt;
2838 tree maxval, minval;
2839 /* 1 if comparison is nominally unsigned. */
2840 int unsignedp = TYPE_UNSIGNED (*restype_ptr);
2841 tree val;
2843 type = c_common_signed_or_unsigned_type (unsignedp0,
2844 TREE_TYPE (primop0));
2846 maxval = TYPE_MAX_VALUE (type);
2847 minval = TYPE_MIN_VALUE (type);
2849 if (unsignedp && !unsignedp0)
2850 *restype_ptr = c_common_signed_type (*restype_ptr);
2852 if (TREE_TYPE (primop1) != *restype_ptr)
2854 /* Convert primop1 to target type, but do not introduce
2855 additional overflow. We know primop1 is an int_cst. */
2856 primop1 = force_fit_type (*restype_ptr,
2857 wi::to_wide
2858 (primop1,
2859 TYPE_PRECISION (*restype_ptr)),
2860 0, TREE_OVERFLOW (primop1));
2862 if (type != *restype_ptr)
2864 minval = convert (*restype_ptr, minval);
2865 maxval = convert (*restype_ptr, maxval);
2868 min_gt = tree_int_cst_lt (primop1, minval);
2869 max_gt = tree_int_cst_lt (primop1, maxval);
2870 min_lt = tree_int_cst_lt (minval, primop1);
2871 max_lt = tree_int_cst_lt (maxval, primop1);
2873 val = 0;
2874 /* This used to be a switch, but Genix compiler can't handle that. */
2875 if (code == NE_EXPR)
2877 if (max_lt || min_gt)
2878 val = truthvalue_true_node;
2880 else if (code == EQ_EXPR)
2882 if (max_lt || min_gt)
2883 val = truthvalue_false_node;
2885 else if (code == LT_EXPR)
2887 if (max_lt)
2888 val = truthvalue_true_node;
2889 if (!min_lt)
2890 val = truthvalue_false_node;
2892 else if (code == GT_EXPR)
2894 if (min_gt)
2895 val = truthvalue_true_node;
2896 if (!max_gt)
2897 val = truthvalue_false_node;
2899 else if (code == LE_EXPR)
2901 if (!max_gt)
2902 val = truthvalue_true_node;
2903 if (min_gt)
2904 val = truthvalue_false_node;
2906 else if (code == GE_EXPR)
2908 if (!min_lt)
2909 val = truthvalue_true_node;
2910 if (max_lt)
2911 val = truthvalue_false_node;
2914 /* If primop0 was sign-extended and unsigned comparison specd,
2915 we did a signed comparison above using the signed type bounds.
2916 But the comparison we output must be unsigned.
2918 Also, for inequalities, VAL is no good; but if the signed
2919 comparison had *any* fixed result, it follows that the
2920 unsigned comparison just tests the sign in reverse
2921 (positive values are LE, negative ones GE).
2922 So we can generate an unsigned comparison
2923 against an extreme value of the signed type. */
2925 if (unsignedp && !unsignedp0)
2927 if (val != 0)
2928 switch (code)
2930 case LT_EXPR:
2931 case GE_EXPR:
2932 primop1 = TYPE_MIN_VALUE (type);
2933 val = 0;
2934 break;
2936 case LE_EXPR:
2937 case GT_EXPR:
2938 primop1 = TYPE_MAX_VALUE (type);
2939 val = 0;
2940 break;
2942 default:
2943 break;
2945 type = c_common_unsigned_type (type);
2948 if (TREE_CODE (primop0) != INTEGER_CST
2949 /* Don't warn if it's from a (non-system) macro. */
2950 && !(from_macro_expansion_at
2951 (expansion_point_location_if_in_system_header
2952 (EXPR_LOCATION (primop0)))))
2954 if (val == truthvalue_false_node)
2955 warning_at (loc, OPT_Wtype_limits,
2956 "comparison is always false due to limited range of data type");
2957 if (val == truthvalue_true_node)
2958 warning_at (loc, OPT_Wtype_limits,
2959 "comparison is always true due to limited range of data type");
2962 if (val != 0)
2964 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
2965 if (TREE_SIDE_EFFECTS (primop0))
2966 return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
2967 return val;
2970 /* Value is not predetermined, but do the comparison
2971 in the type of the operand that is not constant.
2972 TYPE is already properly set. */
2975 /* If either arg is decimal float and the other is float, find the
2976 proper common type to use for comparison. */
2977 else if (real1 && real2
2978 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2979 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
2980 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
2982 /* If either arg is decimal float and the other is float, fail. */
2983 else if (real1 && real2
2984 && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2985 || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
2986 return NULL_TREE;
2988 else if (real1 && real2
2989 && (TYPE_PRECISION (TREE_TYPE (primop0))
2990 == TYPE_PRECISION (TREE_TYPE (primop1))))
2991 type = TREE_TYPE (primop0);
2993 /* If args' natural types are both narrower than nominal type
2994 and both extend in the same manner, compare them
2995 in the type of the wider arg.
2996 Otherwise must actually extend both to the nominal
2997 common type lest different ways of extending
2998 alter the result.
2999 (eg, (short)-1 == (unsigned short)-1 should be 0.) */
3001 else if (unsignedp0 == unsignedp1 && real1 == real2
3002 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
3003 && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
3005 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
3006 type = c_common_signed_or_unsigned_type (unsignedp0
3007 || TYPE_UNSIGNED (*restype_ptr),
3008 type);
3009 /* Make sure shorter operand is extended the right way
3010 to match the longer operand. */
3011 primop0
3012 = convert (c_common_signed_or_unsigned_type (unsignedp0,
3013 TREE_TYPE (primop0)),
3014 primop0);
3015 primop1
3016 = convert (c_common_signed_or_unsigned_type (unsignedp1,
3017 TREE_TYPE (primop1)),
3018 primop1);
3020 else
3022 /* Here we must do the comparison on the nominal type
3023 using the args exactly as we received them. */
3024 type = *restype_ptr;
3025 primop0 = op0;
3026 primop1 = op1;
3028 /* We want to fold unsigned comparisons of >= and < against zero.
3029 For these, we may also issue a warning if we have a non-constant
3030 compared against zero, where the zero was spelled as "0" (rather
3031 than merely folding to it).
3032 If we have at least one constant, then op1 is constant
3033 and we may have a non-constant expression as op0. */
3034 if (!real1 && !real2 && integer_zerop (primop1)
3035 && TYPE_UNSIGNED (*restype_ptr))
3037 tree value = NULL_TREE;
3038 /* All unsigned values are >= 0, so we warn. However,
3039 if OP0 is a constant that is >= 0, the signedness of
3040 the comparison isn't an issue, so suppress the
3041 warning. */
3042 tree folded_op0 = fold_for_warn (op0);
3043 bool warn =
3044 warn_type_limits && !in_system_header_at (loc)
3045 && !(TREE_CODE (folded_op0) == INTEGER_CST
3046 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3047 folded_op0)))
3048 /* Do not warn for enumeration types. */
3049 && (TREE_CODE (expr_original_type (folded_op0)) != ENUMERAL_TYPE);
3051 switch (code)
3053 case GE_EXPR:
3054 if (warn)
3055 warning_at (loc, OPT_Wtype_limits,
3056 "comparison of unsigned expression in %<>= 0%> "
3057 "is always true");
3058 value = truthvalue_true_node;
3059 break;
3061 case LT_EXPR:
3062 if (warn)
3063 warning_at (loc, OPT_Wtype_limits,
3064 "comparison of unsigned expression in %<< 0%> "
3065 "is always false");
3066 value = truthvalue_false_node;
3067 break;
3069 default:
3070 break;
3073 if (value != NULL_TREE)
3075 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3076 if (TREE_SIDE_EFFECTS (primop0))
3077 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3078 primop0, value);
3079 return value;
3084 *op0_ptr = convert (type, primop0);
3085 *op1_ptr = convert (type, primop1);
3087 *restype_ptr = truthvalue_type_node;
3089 return NULL_TREE;
3092 /* Return a tree for the sum or difference (RESULTCODE says which)
3093 of pointer PTROP and integer INTOP. */
3095 tree
3096 pointer_int_sum (location_t loc, enum tree_code resultcode,
3097 tree ptrop, tree intop, bool complain)
3099 tree size_exp, ret;
3101 /* The result is a pointer of the same type that is being added. */
3102 tree result_type = TREE_TYPE (ptrop);
3104 if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
3106 if (complain && warn_pointer_arith)
3107 pedwarn (loc, OPT_Wpointer_arith,
3108 "pointer of type %<void *%> used in arithmetic");
3109 else if (!complain)
3110 return error_mark_node;
3111 size_exp = integer_one_node;
3113 else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3115 if (complain && warn_pointer_arith)
3116 pedwarn (loc, OPT_Wpointer_arith,
3117 "pointer to a function used in arithmetic");
3118 else if (!complain)
3119 return error_mark_node;
3120 size_exp = integer_one_node;
3122 else if (!verify_type_context (loc, TCTX_POINTER_ARITH,
3123 TREE_TYPE (result_type)))
3124 size_exp = integer_one_node;
3125 else
3126 size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3128 /* We are manipulating pointer values, so we don't need to warn
3129 about relying on undefined signed overflow. We disable the
3130 warning here because we use integer types so fold won't know that
3131 they are really pointers. */
3132 fold_defer_overflow_warnings ();
3134 /* If what we are about to multiply by the size of the elements
3135 contains a constant term, apply distributive law
3136 and multiply that constant term separately.
3137 This helps produce common subexpressions. */
3138 if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3139 && !TREE_CONSTANT (intop)
3140 && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3141 && TREE_CONSTANT (size_exp)
3142 /* If the constant comes from pointer subtraction,
3143 skip this optimization--it would cause an error. */
3144 && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3145 /* If the constant is unsigned, and smaller than the pointer size,
3146 then we must skip this optimization. This is because it could cause
3147 an overflow error if the constant is negative but INTOP is not. */
3148 && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (intop))
3149 || (TYPE_PRECISION (TREE_TYPE (intop))
3150 == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3152 enum tree_code subcode = resultcode;
3153 tree int_type = TREE_TYPE (intop);
3154 if (TREE_CODE (intop) == MINUS_EXPR)
3155 subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3156 /* Convert both subexpression types to the type of intop,
3157 because weird cases involving pointer arithmetic
3158 can result in a sum or difference with different type args. */
3159 ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3160 subcode, ptrop,
3161 convert (int_type, TREE_OPERAND (intop, 1)),
3162 true);
3163 intop = convert (int_type, TREE_OPERAND (intop, 0));
3166 /* Convert the integer argument to a type the same size as sizetype
3167 so the multiply won't overflow spuriously. */
3168 if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3169 || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3170 intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3171 TYPE_UNSIGNED (sizetype)), intop);
3173 /* Replace the integer argument with a suitable product by the object size.
3174 Do this multiplication as signed, then convert to the appropriate type
3175 for the pointer operation and disregard an overflow that occurred only
3176 because of the sign-extension change in the latter conversion. */
3178 tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3179 convert (TREE_TYPE (intop), size_exp));
3180 intop = convert (sizetype, t);
3181 if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3182 intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3185 /* Create the sum or difference. */
3186 if (resultcode == MINUS_EXPR)
3187 intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3189 ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3191 fold_undefer_and_ignore_overflow_warnings ();
3193 return ret;
3196 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3197 and if NON_CONST is known not to be permitted in an evaluated part
3198 of a constant expression. */
3200 tree
3201 c_wrap_maybe_const (tree expr, bool non_const)
3203 bool nowarning = TREE_NO_WARNING (expr);
3204 location_t loc = EXPR_LOCATION (expr);
3206 /* This should never be called for C++. */
3207 if (c_dialect_cxx ())
3208 gcc_unreachable ();
3210 /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING. */
3211 STRIP_TYPE_NOPS (expr);
3212 expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3213 C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3214 if (nowarning)
3215 TREE_NO_WARNING (expr) = 1;
3216 protected_set_expr_location (expr, loc);
3218 return expr;
3221 /* Return whether EXPR is a declaration whose address can never be
3222 NULL. */
3224 bool
3225 decl_with_nonnull_addr_p (const_tree expr)
3227 return (DECL_P (expr)
3228 && (TREE_CODE (expr) == PARM_DECL
3229 || TREE_CODE (expr) == LABEL_DECL
3230 || !DECL_WEAK (expr)));
3233 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3234 or for an `if' or `while' statement or ?..: exp. It should already
3235 have been validated to be of suitable type; otherwise, a bad
3236 diagnostic may result.
3238 The EXPR is located at LOCATION.
3240 This preparation consists of taking the ordinary
3241 representation of an expression expr and producing a valid tree
3242 boolean expression describing whether expr is nonzero. We could
3243 simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3244 but we optimize comparisons, &&, ||, and !.
3246 The resulting type should always be `truthvalue_type_node'. */
3248 tree
3249 c_common_truthvalue_conversion (location_t location, tree expr)
3251 STRIP_ANY_LOCATION_WRAPPER (expr);
3252 switch (TREE_CODE (expr))
3254 case EQ_EXPR: case NE_EXPR: case UNEQ_EXPR: case LTGT_EXPR:
3255 case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
3256 case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3257 case ORDERED_EXPR: case UNORDERED_EXPR:
3258 if (TREE_TYPE (expr) == truthvalue_type_node)
3259 return expr;
3260 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3261 TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3262 goto ret;
3264 case TRUTH_ANDIF_EXPR:
3265 case TRUTH_ORIF_EXPR:
3266 case TRUTH_AND_EXPR:
3267 case TRUTH_OR_EXPR:
3268 case TRUTH_XOR_EXPR:
3269 if (TREE_TYPE (expr) == truthvalue_type_node)
3270 return expr;
3271 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3272 c_common_truthvalue_conversion (location,
3273 TREE_OPERAND (expr, 0)),
3274 c_common_truthvalue_conversion (location,
3275 TREE_OPERAND (expr, 1)));
3276 goto ret;
3278 case TRUTH_NOT_EXPR:
3279 if (TREE_TYPE (expr) == truthvalue_type_node)
3280 return expr;
3281 expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3282 c_common_truthvalue_conversion (location,
3283 TREE_OPERAND (expr, 0)));
3284 goto ret;
3286 case ERROR_MARK:
3287 return expr;
3289 case INTEGER_CST:
3290 if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3291 && !integer_zerop (expr)
3292 && !integer_onep (expr))
3293 warning_at (location, OPT_Wint_in_bool_context,
3294 "enum constant in boolean context");
3295 return integer_zerop (expr) ? truthvalue_false_node
3296 : truthvalue_true_node;
3298 case REAL_CST:
3299 return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3300 ? truthvalue_true_node
3301 : truthvalue_false_node;
3303 case FIXED_CST:
3304 return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3305 &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3306 ? truthvalue_true_node
3307 : truthvalue_false_node;
3309 case FUNCTION_DECL:
3310 expr = build_unary_op (location, ADDR_EXPR, expr, false);
3311 /* Fall through. */
3313 case ADDR_EXPR:
3315 tree inner = TREE_OPERAND (expr, 0);
3316 if (decl_with_nonnull_addr_p (inner))
3318 /* Common Ada programmer's mistake. */
3319 warning_at (location,
3320 OPT_Waddress,
3321 "the address of %qD will always evaluate as %<true%>",
3322 inner);
3323 return truthvalue_true_node;
3325 break;
3328 case COMPLEX_EXPR:
3329 expr = build_binary_op (EXPR_LOCATION (expr),
3330 (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3331 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3332 c_common_truthvalue_conversion (location,
3333 TREE_OPERAND (expr, 0)),
3334 c_common_truthvalue_conversion (location,
3335 TREE_OPERAND (expr, 1)),
3336 false);
3337 goto ret;
3339 case NEGATE_EXPR:
3340 case ABS_EXPR:
3341 case ABSU_EXPR:
3342 case FLOAT_EXPR:
3343 case EXCESS_PRECISION_EXPR:
3344 /* These don't change whether an object is nonzero or zero. */
3345 return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3347 case LROTATE_EXPR:
3348 case RROTATE_EXPR:
3349 /* These don't change whether an object is zero or nonzero, but
3350 we can't ignore them if their second arg has side-effects. */
3351 if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3353 expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3354 TREE_OPERAND (expr, 1),
3355 c_common_truthvalue_conversion
3356 (location, TREE_OPERAND (expr, 0)));
3357 goto ret;
3359 else
3360 return c_common_truthvalue_conversion (location,
3361 TREE_OPERAND (expr, 0));
3363 case MULT_EXPR:
3364 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3365 "%<*%> in boolean context, suggest %<&&%> instead");
3366 break;
3368 case LSHIFT_EXPR:
3369 /* We will only warn on signed shifts here, because the majority of
3370 false positive warnings happen in code where unsigned arithmetic
3371 was used in anticipation of a possible overflow.
3372 Furthermore, if we see an unsigned type here we know that the
3373 result of the shift is not subject to integer promotion rules. */
3374 if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3375 && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3376 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3377 "%<<<%> in boolean context, did you mean %<<%>?");
3378 break;
3380 case COND_EXPR:
3381 if (warn_int_in_bool_context
3382 && !from_macro_definition_at (EXPR_LOCATION (expr)))
3384 tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3385 tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3386 if (TREE_CODE (val1) == INTEGER_CST
3387 && TREE_CODE (val2) == INTEGER_CST
3388 && !integer_zerop (val1)
3389 && !integer_zerop (val2)
3390 && (!integer_onep (val1)
3391 || !integer_onep (val2)))
3392 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3393 "%<?:%> using integer constants in boolean context, "
3394 "the expression will always evaluate to %<true%>");
3395 else if ((TREE_CODE (val1) == INTEGER_CST
3396 && !integer_zerop (val1)
3397 && !integer_onep (val1))
3398 || (TREE_CODE (val2) == INTEGER_CST
3399 && !integer_zerop (val2)
3400 && !integer_onep (val2)))
3401 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3402 "%<?:%> using integer constants in boolean context");
3404 /* Distribute the conversion into the arms of a COND_EXPR. */
3405 if (c_dialect_cxx ())
3406 /* Avoid premature folding. */
3407 break;
3408 else
3410 int w = warn_int_in_bool_context;
3411 warn_int_in_bool_context = 0;
3412 /* Folding will happen later for C. */
3413 expr = build3 (COND_EXPR, truthvalue_type_node,
3414 TREE_OPERAND (expr, 0),
3415 c_common_truthvalue_conversion (location,
3416 TREE_OPERAND (expr, 1)),
3417 c_common_truthvalue_conversion (location,
3418 TREE_OPERAND (expr, 2)));
3419 warn_int_in_bool_context = w;
3420 goto ret;
3423 CASE_CONVERT:
3425 tree totype = TREE_TYPE (expr);
3426 tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3428 if (POINTER_TYPE_P (totype)
3429 && !c_inhibit_evaluation_warnings
3430 && TREE_CODE (fromtype) == REFERENCE_TYPE)
3432 tree inner = expr;
3433 STRIP_NOPS (inner);
3435 if (DECL_P (inner))
3436 warning_at (location,
3437 OPT_Waddress,
3438 "the compiler can assume that the address of "
3439 "%qD will always evaluate to %<true%>",
3440 inner);
3443 /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3444 since that affects how `default_conversion' will behave. */
3445 if (TREE_CODE (totype) == REFERENCE_TYPE
3446 || TREE_CODE (fromtype) == REFERENCE_TYPE)
3447 break;
3448 /* Don't strip a conversion from C++0x scoped enum, since they
3449 don't implicitly convert to other types. */
3450 if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3451 && ENUM_IS_SCOPED (fromtype))
3452 break;
3453 /* If this isn't narrowing the argument, we can ignore it. */
3454 if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3455 return c_common_truthvalue_conversion (location,
3456 TREE_OPERAND (expr, 0));
3458 break;
3460 case MODIFY_EXPR:
3461 if (!TREE_NO_WARNING (expr)
3462 && warn_parentheses
3463 && warning_at (location, OPT_Wparentheses,
3464 "suggest parentheses around assignment used as "
3465 "truth value"))
3466 TREE_NO_WARNING (expr) = 1;
3467 break;
3469 case CONST_DECL:
3471 tree folded_expr = fold_for_warn (expr);
3472 if (folded_expr != expr)
3473 return c_common_truthvalue_conversion (location, folded_expr);
3475 break;
3477 default:
3478 break;
3481 if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3483 tree t = save_expr (expr);
3484 expr = (build_binary_op
3485 (EXPR_LOCATION (expr),
3486 (TREE_SIDE_EFFECTS (expr)
3487 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3488 c_common_truthvalue_conversion
3489 (location,
3490 build_unary_op (location, REALPART_EXPR, t, false)),
3491 c_common_truthvalue_conversion
3492 (location,
3493 build_unary_op (location, IMAGPART_EXPR, t, false)),
3494 false));
3495 goto ret;
3498 if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
3500 tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3501 FCONST0 (TYPE_MODE
3502 (TREE_TYPE (expr))));
3503 return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3505 else
3506 return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3508 ret:
3509 protected_set_expr_location (expr, location);
3510 return expr;
3513 static void def_builtin_1 (enum built_in_function fncode,
3514 const char *name,
3515 enum built_in_class fnclass,
3516 tree fntype, tree libtype,
3517 bool both_p, bool fallback_p, bool nonansi_p,
3518 tree fnattrs, bool implicit_p);
3521 /* Apply the TYPE_QUALS to the new DECL. */
3523 void
3524 c_apply_type_quals_to_decl (int type_quals, tree decl)
3526 tree type = TREE_TYPE (decl);
3528 if (type == error_mark_node)
3529 return;
3531 if ((type_quals & TYPE_QUAL_CONST)
3532 || (type && TREE_CODE (type) == REFERENCE_TYPE))
3533 /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3534 constructor can produce constant init, so rely on cp_finish_decl to
3535 clear TREE_READONLY if the variable has non-constant init. */
3536 TREE_READONLY (decl) = 1;
3537 if (type_quals & TYPE_QUAL_VOLATILE)
3539 TREE_SIDE_EFFECTS (decl) = 1;
3540 TREE_THIS_VOLATILE (decl) = 1;
3542 if (type_quals & TYPE_QUAL_RESTRICT)
3544 while (type && TREE_CODE (type) == ARRAY_TYPE)
3545 /* Allow 'restrict' on arrays of pointers.
3546 FIXME currently we just ignore it. */
3547 type = TREE_TYPE (type);
3548 if (!type
3549 || !POINTER_TYPE_P (type)
3550 || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3551 error ("invalid use of %<restrict%>");
3555 /* Return the typed-based alias set for T, which may be an expression
3556 or a type. Return -1 if we don't do anything special. */
3558 alias_set_type
3559 c_common_get_alias_set (tree t)
3561 /* For VLAs, use the alias set of the element type rather than the
3562 default of alias set 0 for types compared structurally. */
3563 if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3565 if (TREE_CODE (t) == ARRAY_TYPE)
3566 return get_alias_set (TREE_TYPE (t));
3567 return -1;
3570 /* That's all the expressions we handle specially. */
3571 if (!TYPE_P (t))
3572 return -1;
3574 /* Unlike char, char8_t doesn't alias. */
3575 if (flag_char8_t && t == char8_type_node)
3576 return -1;
3578 /* The C standard guarantees that any object may be accessed via an
3579 lvalue that has narrow character type (except char8_t). */
3580 if (t == char_type_node
3581 || t == signed_char_type_node
3582 || t == unsigned_char_type_node)
3583 return 0;
3585 /* The C standard specifically allows aliasing between signed and
3586 unsigned variants of the same type. We treat the signed
3587 variant as canonical. */
3588 if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
3590 tree t1 = c_common_signed_type (t);
3592 /* t1 == t can happen for boolean nodes which are always unsigned. */
3593 if (t1 != t)
3594 return get_alias_set (t1);
3597 return -1;
3600 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3601 the IS_SIZEOF parameter indicates which operator is being applied.
3602 The COMPLAIN flag controls whether we should diagnose possibly
3603 ill-formed constructs or not. LOC is the location of the SIZEOF or
3604 TYPEOF operator. If MIN_ALIGNOF, the least alignment required for
3605 a type in any context should be returned, rather than the normal
3606 alignment for that type. */
3608 tree
3609 c_sizeof_or_alignof_type (location_t loc,
3610 tree type, bool is_sizeof, bool min_alignof,
3611 int complain)
3613 const char *op_name;
3614 tree value = NULL;
3615 enum tree_code type_code = TREE_CODE (type);
3617 op_name = is_sizeof ? "sizeof" : "__alignof__";
3619 if (type_code == FUNCTION_TYPE)
3621 if (is_sizeof)
3623 if (complain && warn_pointer_arith)
3624 pedwarn (loc, OPT_Wpointer_arith,
3625 "invalid application of %<sizeof%> to a function type");
3626 else if (!complain)
3627 return error_mark_node;
3628 value = size_one_node;
3630 else
3632 if (complain)
3634 if (c_dialect_cxx ())
3635 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3636 "%<alignof%> applied to a function type");
3637 else
3638 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3639 "%<_Alignof%> applied to a function type");
3641 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3644 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3646 if (type_code == VOID_TYPE
3647 && complain && warn_pointer_arith)
3648 pedwarn (loc, OPT_Wpointer_arith,
3649 "invalid application of %qs to a void type", op_name);
3650 else if (!complain)
3651 return error_mark_node;
3652 value = size_one_node;
3654 else if (!COMPLETE_TYPE_P (type)
3655 && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3657 if (complain)
3658 error_at (loc, "invalid application of %qs to incomplete type %qT",
3659 op_name, type);
3660 return error_mark_node;
3662 else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3663 && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3665 if (complain)
3666 error_at (loc, "invalid application of %qs to array type %qT of "
3667 "incomplete element type", op_name, type);
3668 return error_mark_node;
3670 else if (!verify_type_context (loc, is_sizeof ? TCTX_SIZEOF : TCTX_ALIGNOF,
3671 type, !complain))
3673 if (!complain)
3674 return error_mark_node;
3675 value = size_one_node;
3677 else
3679 if (is_sizeof)
3680 /* Convert in case a char is more than one unit. */
3681 value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3682 size_int (TYPE_PRECISION (char_type_node)
3683 / BITS_PER_UNIT));
3684 else if (min_alignof)
3685 value = size_int (min_align_of_type (type));
3686 else
3687 value = size_int (TYPE_ALIGN_UNIT (type));
3690 /* VALUE will have the middle-end integer type sizetype.
3691 However, we should really return a value of type `size_t',
3692 which is just a typedef for an ordinary integer type. */
3693 value = fold_convert_loc (loc, size_type_node, value);
3695 return value;
3698 /* Implement the __alignof keyword: Return the minimum required
3699 alignment of EXPR, measured in bytes. For VAR_DECLs,
3700 FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3701 from an "aligned" __attribute__ specification). LOC is the
3702 location of the ALIGNOF operator. */
3704 tree
3705 c_alignof_expr (location_t loc, tree expr)
3707 tree t;
3709 if (!verify_type_context (loc, TCTX_ALIGNOF, TREE_TYPE (expr)))
3710 t = size_one_node;
3712 else if (VAR_OR_FUNCTION_DECL_P (expr))
3713 t = size_int (DECL_ALIGN_UNIT (expr));
3715 else if (TREE_CODE (expr) == COMPONENT_REF
3716 && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3718 error_at (loc, "%<__alignof%> applied to a bit-field");
3719 t = size_one_node;
3721 else if (TREE_CODE (expr) == COMPONENT_REF
3722 && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3723 t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3725 else if (INDIRECT_REF_P (expr))
3727 tree t = TREE_OPERAND (expr, 0);
3728 tree best = t;
3729 int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3731 while (CONVERT_EXPR_P (t)
3732 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3734 int thisalign;
3736 t = TREE_OPERAND (t, 0);
3737 thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3738 if (thisalign > bestalign)
3739 best = t, bestalign = thisalign;
3741 return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
3743 else
3744 return c_alignof (loc, TREE_TYPE (expr));
3746 return fold_convert_loc (loc, size_type_node, t);
3749 /* Handle C and C++ default attributes. */
3751 enum built_in_attribute
3753 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
3754 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
3755 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
3756 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
3757 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
3758 #include "builtin-attrs.def"
3759 #undef DEF_ATTR_NULL_TREE
3760 #undef DEF_ATTR_INT
3761 #undef DEF_ATTR_STRING
3762 #undef DEF_ATTR_IDENT
3763 #undef DEF_ATTR_TREE_LIST
3764 ATTR_LAST
3767 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
3769 static void c_init_attributes (void);
3771 enum c_builtin_type
3773 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
3774 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
3775 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
3776 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
3777 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3778 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3779 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
3780 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3781 ARG6) NAME,
3782 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3783 ARG6, ARG7) NAME,
3784 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3785 ARG6, ARG7, ARG8) NAME,
3786 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3787 ARG6, ARG7, ARG8, ARG9) NAME,
3788 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3789 ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
3790 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3791 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
3792 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
3793 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
3794 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
3795 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3796 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3797 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3798 NAME,
3799 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3800 ARG6) NAME,
3801 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3802 ARG6, ARG7) NAME,
3803 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
3804 #include "builtin-types.def"
3805 #undef DEF_PRIMITIVE_TYPE
3806 #undef DEF_FUNCTION_TYPE_0
3807 #undef DEF_FUNCTION_TYPE_1
3808 #undef DEF_FUNCTION_TYPE_2
3809 #undef DEF_FUNCTION_TYPE_3
3810 #undef DEF_FUNCTION_TYPE_4
3811 #undef DEF_FUNCTION_TYPE_5
3812 #undef DEF_FUNCTION_TYPE_6
3813 #undef DEF_FUNCTION_TYPE_7
3814 #undef DEF_FUNCTION_TYPE_8
3815 #undef DEF_FUNCTION_TYPE_9
3816 #undef DEF_FUNCTION_TYPE_10
3817 #undef DEF_FUNCTION_TYPE_11
3818 #undef DEF_FUNCTION_TYPE_VAR_0
3819 #undef DEF_FUNCTION_TYPE_VAR_1
3820 #undef DEF_FUNCTION_TYPE_VAR_2
3821 #undef DEF_FUNCTION_TYPE_VAR_3
3822 #undef DEF_FUNCTION_TYPE_VAR_4
3823 #undef DEF_FUNCTION_TYPE_VAR_5
3824 #undef DEF_FUNCTION_TYPE_VAR_6
3825 #undef DEF_FUNCTION_TYPE_VAR_7
3826 #undef DEF_POINTER_TYPE
3827 BT_LAST
3830 typedef enum c_builtin_type builtin_type;
3832 /* A temporary array for c_common_nodes_and_builtins. Used in
3833 communication with def_fn_type. */
3834 static tree builtin_types[(int) BT_LAST + 1];
3836 /* A helper function for c_common_nodes_and_builtins. Build function type
3837 for DEF with return type RET and N arguments. If VAR is true, then the
3838 function should be variadic after those N arguments.
3840 Takes special care not to ICE if any of the types involved are
3841 error_mark_node, which indicates that said type is not in fact available
3842 (see builtin_type_for_size). In which case the function type as a whole
3843 should be error_mark_node. */
3845 static void
3846 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
3848 tree t;
3849 tree *args = XALLOCAVEC (tree, n);
3850 va_list list;
3851 int i;
3853 va_start (list, n);
3854 for (i = 0; i < n; ++i)
3856 builtin_type a = (builtin_type) va_arg (list, int);
3857 t = builtin_types[a];
3858 if (t == error_mark_node)
3859 goto egress;
3860 args[i] = t;
3863 t = builtin_types[ret];
3864 if (t == error_mark_node)
3865 goto egress;
3866 if (var)
3867 t = build_varargs_function_type_array (t, n, args);
3868 else
3869 t = build_function_type_array (t, n, args);
3871 egress:
3872 builtin_types[def] = t;
3873 va_end (list);
3876 /* Build builtin functions common to both C and C++ language
3877 frontends. */
3879 static void
3880 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
3882 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
3883 builtin_types[ENUM] = VALUE;
3884 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
3885 def_fn_type (ENUM, RETURN, 0, 0);
3886 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
3887 def_fn_type (ENUM, RETURN, 0, 1, ARG1);
3888 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
3889 def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
3890 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3891 def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
3892 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3893 def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
3894 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3895 def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3896 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3897 ARG6) \
3898 def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3899 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3900 ARG6, ARG7) \
3901 def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3902 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3903 ARG6, ARG7, ARG8) \
3904 def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3905 ARG7, ARG8);
3906 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3907 ARG6, ARG7, ARG8, ARG9) \
3908 def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3909 ARG7, ARG8, ARG9);
3910 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3911 ARG6, ARG7, ARG8, ARG9, ARG10) \
3912 def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3913 ARG7, ARG8, ARG9, ARG10);
3914 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3915 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
3916 def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3917 ARG7, ARG8, ARG9, ARG10, ARG11);
3918 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
3919 def_fn_type (ENUM, RETURN, 1, 0);
3920 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
3921 def_fn_type (ENUM, RETURN, 1, 1, ARG1);
3922 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
3923 def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
3924 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3925 def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
3926 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3927 def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
3928 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3929 def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3930 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3931 ARG6) \
3932 def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3933 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3934 ARG6, ARG7) \
3935 def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3936 #define DEF_POINTER_TYPE(ENUM, TYPE) \
3937 builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
3939 #include "builtin-types.def"
3941 #undef DEF_PRIMITIVE_TYPE
3942 #undef DEF_FUNCTION_TYPE_0
3943 #undef DEF_FUNCTION_TYPE_1
3944 #undef DEF_FUNCTION_TYPE_2
3945 #undef DEF_FUNCTION_TYPE_3
3946 #undef DEF_FUNCTION_TYPE_4
3947 #undef DEF_FUNCTION_TYPE_5
3948 #undef DEF_FUNCTION_TYPE_6
3949 #undef DEF_FUNCTION_TYPE_7
3950 #undef DEF_FUNCTION_TYPE_8
3951 #undef DEF_FUNCTION_TYPE_9
3952 #undef DEF_FUNCTION_TYPE_10
3953 #undef DEF_FUNCTION_TYPE_11
3954 #undef DEF_FUNCTION_TYPE_VAR_0
3955 #undef DEF_FUNCTION_TYPE_VAR_1
3956 #undef DEF_FUNCTION_TYPE_VAR_2
3957 #undef DEF_FUNCTION_TYPE_VAR_3
3958 #undef DEF_FUNCTION_TYPE_VAR_4
3959 #undef DEF_FUNCTION_TYPE_VAR_5
3960 #undef DEF_FUNCTION_TYPE_VAR_6
3961 #undef DEF_FUNCTION_TYPE_VAR_7
3962 #undef DEF_POINTER_TYPE
3963 builtin_types[(int) BT_LAST] = NULL_TREE;
3965 c_init_attributes ();
3967 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
3968 NONANSI_P, ATTRS, IMPLICIT, COND) \
3969 if (NAME && COND) \
3970 def_builtin_1 (ENUM, NAME, CLASS, \
3971 builtin_types[(int) TYPE], \
3972 builtin_types[(int) LIBTYPE], \
3973 BOTH_P, FALLBACK_P, NONANSI_P, \
3974 built_in_attributes[(int) ATTRS], IMPLICIT);
3975 #include "builtins.def"
3977 targetm.init_builtins ();
3979 build_common_builtin_nodes ();
3982 /* Like get_identifier, but avoid warnings about null arguments when
3983 the argument may be NULL for targets where GCC lacks stdint.h type
3984 information. */
3986 static inline tree
3987 c_get_ident (const char *id)
3989 return get_identifier (id);
3992 /* Build tree nodes and builtin functions common to both C and C++ language
3993 frontends. */
3995 void
3996 c_common_nodes_and_builtins (void)
3998 int char8_type_size;
3999 int char16_type_size;
4000 int char32_type_size;
4001 int wchar_type_size;
4002 tree array_domain_type;
4003 tree va_list_ref_type_node;
4004 tree va_list_arg_type_node;
4005 int i;
4007 build_common_tree_nodes (flag_signed_char);
4009 /* Define `int' and `char' first so that dbx will output them first. */
4010 record_builtin_type (RID_INT, NULL, integer_type_node);
4011 record_builtin_type (RID_CHAR, "char", char_type_node);
4013 /* `signed' is the same as `int'. FIXME: the declarations of "signed",
4014 "unsigned long", "long long unsigned" and "unsigned short" were in C++
4015 but not C. Are the conditionals here needed? */
4016 if (c_dialect_cxx ())
4017 record_builtin_type (RID_SIGNED, NULL, integer_type_node);
4018 record_builtin_type (RID_LONG, "long int", long_integer_type_node);
4019 record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
4020 record_builtin_type (RID_MAX, "long unsigned int",
4021 long_unsigned_type_node);
4023 for (i = 0; i < NUM_INT_N_ENTS; i ++)
4025 char name[25];
4027 sprintf (name, "__int%d", int_n_data[i].bitsize);
4028 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4029 int_n_trees[i].signed_type);
4030 sprintf (name, "__int%d__", int_n_data[i].bitsize);
4031 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
4032 int_n_trees[i].signed_type);
4034 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
4035 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4036 sprintf (name, "__int%d__ unsigned", int_n_data[i].bitsize);
4037 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
4040 if (c_dialect_cxx ())
4041 record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
4042 record_builtin_type (RID_MAX, "long long int",
4043 long_long_integer_type_node);
4044 record_builtin_type (RID_MAX, "long long unsigned int",
4045 long_long_unsigned_type_node);
4046 if (c_dialect_cxx ())
4047 record_builtin_type (RID_MAX, "long long unsigned",
4048 long_long_unsigned_type_node);
4049 record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4050 record_builtin_type (RID_MAX, "short unsigned int",
4051 short_unsigned_type_node);
4052 if (c_dialect_cxx ())
4053 record_builtin_type (RID_MAX, "unsigned short",
4054 short_unsigned_type_node);
4056 /* Define both `signed char' and `unsigned char'. */
4057 record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4058 record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4060 /* These are types that c_common_type_for_size and
4061 c_common_type_for_mode use. */
4062 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4063 TYPE_DECL, NULL_TREE,
4064 intQI_type_node));
4065 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4066 TYPE_DECL, NULL_TREE,
4067 intHI_type_node));
4068 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4069 TYPE_DECL, NULL_TREE,
4070 intSI_type_node));
4071 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4072 TYPE_DECL, NULL_TREE,
4073 intDI_type_node));
4074 #if HOST_BITS_PER_WIDE_INT >= 64
4075 /* Note that this is different than the __int128 type that's part of
4076 the generic __intN support. */
4077 if (targetm.scalar_mode_supported_p (TImode))
4078 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4079 TYPE_DECL,
4080 get_identifier ("__int128_t"),
4081 intTI_type_node));
4082 #endif
4083 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4084 TYPE_DECL, NULL_TREE,
4085 unsigned_intQI_type_node));
4086 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4087 TYPE_DECL, NULL_TREE,
4088 unsigned_intHI_type_node));
4089 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4090 TYPE_DECL, NULL_TREE,
4091 unsigned_intSI_type_node));
4092 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4093 TYPE_DECL, NULL_TREE,
4094 unsigned_intDI_type_node));
4095 #if HOST_BITS_PER_WIDE_INT >= 64
4096 if (targetm.scalar_mode_supported_p (TImode))
4097 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4098 TYPE_DECL,
4099 get_identifier ("__uint128_t"),
4100 unsigned_intTI_type_node));
4101 #endif
4103 /* Create the widest literal types. */
4104 if (targetm.scalar_mode_supported_p (TImode))
4106 widest_integer_literal_type_node = intTI_type_node;
4107 widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4109 else
4111 widest_integer_literal_type_node = intDI_type_node;
4112 widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4115 signed_size_type_node = c_common_signed_type (size_type_node);
4117 pid_type_node =
4118 TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4120 record_builtin_type (RID_FLOAT, NULL, float_type_node);
4121 record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4122 record_builtin_type (RID_MAX, "long double", long_double_type_node);
4124 if (!c_dialect_cxx ())
4125 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4126 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4127 record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4128 FLOATN_NX_TYPE_NODE (i));
4130 /* Only supported decimal floating point extension if the target
4131 actually supports underlying modes. */
4132 if (targetm.scalar_mode_supported_p (SDmode)
4133 && targetm.scalar_mode_supported_p (DDmode)
4134 && targetm.scalar_mode_supported_p (TDmode))
4136 record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4137 record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4138 record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4141 if (targetm.fixed_point_supported_p ())
4143 record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4144 record_builtin_type (RID_FRACT, NULL, fract_type_node);
4145 record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4146 record_builtin_type (RID_MAX, "long long _Fract",
4147 long_long_fract_type_node);
4148 record_builtin_type (RID_MAX, "unsigned short _Fract",
4149 unsigned_short_fract_type_node);
4150 record_builtin_type (RID_MAX, "unsigned _Fract",
4151 unsigned_fract_type_node);
4152 record_builtin_type (RID_MAX, "unsigned long _Fract",
4153 unsigned_long_fract_type_node);
4154 record_builtin_type (RID_MAX, "unsigned long long _Fract",
4155 unsigned_long_long_fract_type_node);
4156 record_builtin_type (RID_MAX, "_Sat short _Fract",
4157 sat_short_fract_type_node);
4158 record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4159 record_builtin_type (RID_MAX, "_Sat long _Fract",
4160 sat_long_fract_type_node);
4161 record_builtin_type (RID_MAX, "_Sat long long _Fract",
4162 sat_long_long_fract_type_node);
4163 record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4164 sat_unsigned_short_fract_type_node);
4165 record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4166 sat_unsigned_fract_type_node);
4167 record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4168 sat_unsigned_long_fract_type_node);
4169 record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4170 sat_unsigned_long_long_fract_type_node);
4171 record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4172 record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4173 record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4174 record_builtin_type (RID_MAX, "long long _Accum",
4175 long_long_accum_type_node);
4176 record_builtin_type (RID_MAX, "unsigned short _Accum",
4177 unsigned_short_accum_type_node);
4178 record_builtin_type (RID_MAX, "unsigned _Accum",
4179 unsigned_accum_type_node);
4180 record_builtin_type (RID_MAX, "unsigned long _Accum",
4181 unsigned_long_accum_type_node);
4182 record_builtin_type (RID_MAX, "unsigned long long _Accum",
4183 unsigned_long_long_accum_type_node);
4184 record_builtin_type (RID_MAX, "_Sat short _Accum",
4185 sat_short_accum_type_node);
4186 record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4187 record_builtin_type (RID_MAX, "_Sat long _Accum",
4188 sat_long_accum_type_node);
4189 record_builtin_type (RID_MAX, "_Sat long long _Accum",
4190 sat_long_long_accum_type_node);
4191 record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4192 sat_unsigned_short_accum_type_node);
4193 record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4194 sat_unsigned_accum_type_node);
4195 record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4196 sat_unsigned_long_accum_type_node);
4197 record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4198 sat_unsigned_long_long_accum_type_node);
4202 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4203 TYPE_DECL,
4204 get_identifier ("complex int"),
4205 complex_integer_type_node));
4206 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4207 TYPE_DECL,
4208 get_identifier ("complex float"),
4209 complex_float_type_node));
4210 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4211 TYPE_DECL,
4212 get_identifier ("complex double"),
4213 complex_double_type_node));
4214 lang_hooks.decls.pushdecl
4215 (build_decl (UNKNOWN_LOCATION,
4216 TYPE_DECL, get_identifier ("complex long double"),
4217 complex_long_double_type_node));
4219 if (!c_dialect_cxx ())
4220 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4221 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4223 char buf[30];
4224 sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4225 floatn_nx_types[i].extended ? "x" : "");
4226 lang_hooks.decls.pushdecl
4227 (build_decl (UNKNOWN_LOCATION,
4228 TYPE_DECL,
4229 get_identifier (buf),
4230 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4233 /* Make fileptr_type_node a distinct void * type until
4234 FILE type is defined. Likewise for const struct tm*. */
4235 for (unsigned i = 0;
4236 i < sizeof (builtin_structptr_types) / sizeof (builtin_structptr_type);
4237 ++i)
4238 builtin_structptr_types[i].node
4239 = build_variant_type_copy (builtin_structptr_types[i].base);
4241 record_builtin_type (RID_VOID, NULL, void_type_node);
4243 /* Set the TYPE_NAME for any variants that were built before
4244 record_builtin_type gave names to the built-in types. */
4246 tree void_name = TYPE_NAME (void_type_node);
4247 TYPE_NAME (void_type_node) = NULL_TREE;
4248 TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4249 = void_name;
4250 TYPE_NAME (void_type_node) = void_name;
4253 void_list_node = build_void_list_node ();
4255 /* Make a type to be the domain of a few array types
4256 whose domains don't really matter.
4257 200 is small enough that it always fits in size_t
4258 and large enough that it can hold most function names for the
4259 initializations of __FUNCTION__ and __PRETTY_FUNCTION__. */
4260 array_domain_type = build_index_type (size_int (200));
4262 /* Make a type for arrays of characters.
4263 With luck nothing will ever really depend on the length of this
4264 array type. */
4265 char_array_type_node
4266 = build_array_type (char_type_node, array_domain_type);
4268 string_type_node = build_pointer_type (char_type_node);
4269 const_string_type_node
4270 = build_pointer_type (build_qualified_type
4271 (char_type_node, TYPE_QUAL_CONST));
4273 /* This is special for C++ so functions can be overloaded. */
4274 wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4275 wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4276 wchar_type_size = TYPE_PRECISION (wchar_type_node);
4277 underlying_wchar_type_node = wchar_type_node;
4278 if (c_dialect_cxx ())
4280 if (TYPE_UNSIGNED (wchar_type_node))
4281 wchar_type_node = make_unsigned_type (wchar_type_size);
4282 else
4283 wchar_type_node = make_signed_type (wchar_type_size);
4284 record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4287 /* This is for wide string constants. */
4288 wchar_array_type_node
4289 = build_array_type (wchar_type_node, array_domain_type);
4291 /* Define 'char8_t'. */
4292 char8_type_node = get_identifier (CHAR8_TYPE);
4293 char8_type_node = TREE_TYPE (identifier_global_value (char8_type_node));
4294 char8_type_size = TYPE_PRECISION (char8_type_node);
4295 if (c_dialect_cxx ())
4297 char8_type_node = make_unsigned_type (char8_type_size);
4299 if (flag_char8_t)
4300 record_builtin_type (RID_CHAR8, "char8_t", char8_type_node);
4303 /* This is for UTF-8 string constants. */
4304 char8_array_type_node
4305 = build_array_type (char8_type_node, array_domain_type);
4307 /* Define 'char16_t'. */
4308 char16_type_node = get_identifier (CHAR16_TYPE);
4309 char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4310 char16_type_size = TYPE_PRECISION (char16_type_node);
4311 if (c_dialect_cxx ())
4313 char16_type_node = make_unsigned_type (char16_type_size);
4315 if (cxx_dialect >= cxx11)
4316 record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4319 /* This is for UTF-16 string constants. */
4320 char16_array_type_node
4321 = build_array_type (char16_type_node, array_domain_type);
4323 /* Define 'char32_t'. */
4324 char32_type_node = get_identifier (CHAR32_TYPE);
4325 char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4326 char32_type_size = TYPE_PRECISION (char32_type_node);
4327 if (c_dialect_cxx ())
4329 char32_type_node = make_unsigned_type (char32_type_size);
4331 if (cxx_dialect >= cxx11)
4332 record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4335 /* This is for UTF-32 string constants. */
4336 char32_array_type_node
4337 = build_array_type (char32_type_node, array_domain_type);
4339 wint_type_node =
4340 TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4342 intmax_type_node =
4343 TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4344 uintmax_type_node =
4345 TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4347 if (SIG_ATOMIC_TYPE)
4348 sig_atomic_type_node =
4349 TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4350 if (INT8_TYPE)
4351 int8_type_node =
4352 TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4353 if (INT16_TYPE)
4354 int16_type_node =
4355 TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4356 if (INT32_TYPE)
4357 int32_type_node =
4358 TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4359 if (INT64_TYPE)
4360 int64_type_node =
4361 TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4362 if (UINT8_TYPE)
4363 uint8_type_node =
4364 TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4365 if (UINT16_TYPE)
4366 c_uint16_type_node = uint16_type_node =
4367 TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4368 if (UINT32_TYPE)
4369 c_uint32_type_node = uint32_type_node =
4370 TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4371 if (UINT64_TYPE)
4372 c_uint64_type_node = uint64_type_node =
4373 TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4374 if (INT_LEAST8_TYPE)
4375 int_least8_type_node =
4376 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4377 if (INT_LEAST16_TYPE)
4378 int_least16_type_node =
4379 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4380 if (INT_LEAST32_TYPE)
4381 int_least32_type_node =
4382 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4383 if (INT_LEAST64_TYPE)
4384 int_least64_type_node =
4385 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4386 if (UINT_LEAST8_TYPE)
4387 uint_least8_type_node =
4388 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4389 if (UINT_LEAST16_TYPE)
4390 uint_least16_type_node =
4391 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4392 if (UINT_LEAST32_TYPE)
4393 uint_least32_type_node =
4394 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4395 if (UINT_LEAST64_TYPE)
4396 uint_least64_type_node =
4397 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4398 if (INT_FAST8_TYPE)
4399 int_fast8_type_node =
4400 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4401 if (INT_FAST16_TYPE)
4402 int_fast16_type_node =
4403 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4404 if (INT_FAST32_TYPE)
4405 int_fast32_type_node =
4406 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4407 if (INT_FAST64_TYPE)
4408 int_fast64_type_node =
4409 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4410 if (UINT_FAST8_TYPE)
4411 uint_fast8_type_node =
4412 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4413 if (UINT_FAST16_TYPE)
4414 uint_fast16_type_node =
4415 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4416 if (UINT_FAST32_TYPE)
4417 uint_fast32_type_node =
4418 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4419 if (UINT_FAST64_TYPE)
4420 uint_fast64_type_node =
4421 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4422 if (INTPTR_TYPE)
4423 intptr_type_node =
4424 TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4425 if (UINTPTR_TYPE)
4426 uintptr_type_node =
4427 TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4429 default_function_type
4430 = build_varargs_function_type_list (integer_type_node, NULL_TREE);
4431 unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4433 lang_hooks.decls.pushdecl
4434 (build_decl (UNKNOWN_LOCATION,
4435 TYPE_DECL, get_identifier ("__builtin_va_list"),
4436 va_list_type_node));
4437 if (targetm.enum_va_list_p)
4439 int l;
4440 const char *pname;
4441 tree ptype;
4443 for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4445 lang_hooks.decls.pushdecl
4446 (build_decl (UNKNOWN_LOCATION,
4447 TYPE_DECL, get_identifier (pname),
4448 ptype));
4453 if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4455 va_list_arg_type_node = va_list_ref_type_node =
4456 build_pointer_type (TREE_TYPE (va_list_type_node));
4458 else
4460 va_list_arg_type_node = va_list_type_node;
4461 va_list_ref_type_node = build_reference_type (va_list_type_node);
4464 c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4466 main_identifier_node = get_identifier ("main");
4468 /* Create the built-in __null node. It is important that this is
4469 not shared. */
4470 null_node = make_int_cst (1, 1);
4471 TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4473 /* Since builtin_types isn't gc'ed, don't export these nodes. */
4474 memset (builtin_types, 0, sizeof (builtin_types));
4477 /* The number of named compound-literals generated thus far. */
4478 static GTY(()) int compound_literal_number;
4480 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal. */
4482 void
4483 set_compound_literal_name (tree decl)
4485 char *name;
4486 ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4487 compound_literal_number);
4488 compound_literal_number++;
4489 DECL_NAME (decl) = get_identifier (name);
4492 /* build_va_arg helper function. Return a VA_ARG_EXPR with location LOC, type
4493 TYPE and operand OP. */
4495 static tree
4496 build_va_arg_1 (location_t loc, tree type, tree op)
4498 tree expr = build1 (VA_ARG_EXPR, type, op);
4499 SET_EXPR_LOCATION (expr, loc);
4500 return expr;
4503 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4504 va_arg (EXPR, TYPE) at source location LOC. */
4506 tree
4507 build_va_arg (location_t loc, tree expr, tree type)
4509 tree va_type = TREE_TYPE (expr);
4510 tree canon_va_type = (va_type == error_mark_node
4511 ? error_mark_node
4512 : targetm.canonical_va_list_type (va_type));
4514 if (va_type == error_mark_node
4515 || canon_va_type == NULL_TREE)
4517 if (canon_va_type == NULL_TREE)
4518 error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4520 /* Let's handle things neutrallly, if expr:
4521 - has undeclared type, or
4522 - is not an va_list type. */
4523 return build_va_arg_1 (loc, type, error_mark_node);
4526 if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4528 /* Case 1: Not an array type. */
4530 /* Take the address, to get '&ap'. Note that &ap is not a va_list
4531 type. */
4532 mark_addressable (expr);
4533 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4535 return build_va_arg_1 (loc, type, expr);
4538 /* Case 2: Array type.
4540 Background:
4542 For contrast, let's start with the simple case (case 1). If
4543 canon_va_type is not an array type, but say a char *, then when
4544 passing-by-value a va_list, the type of the va_list param decl is
4545 the same as for another va_list decl (all ap's are char *):
4547 f2_1 (char * ap)
4548 D.1815 = VA_ARG (&ap, 0B, 1);
4549 return D.1815;
4551 f2 (int i)
4552 char * ap.0;
4553 char * ap;
4554 __builtin_va_start (&ap, 0);
4555 ap.0 = ap;
4556 res = f2_1 (ap.0);
4557 __builtin_va_end (&ap);
4558 D.1812 = res;
4559 return D.1812;
4561 However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4562 va_list the type of the va_list param decl (case 2b, struct * ap) is not
4563 the same as for another va_list decl (case 2a, struct ap[1]).
4565 f2_1 (struct * ap)
4566 D.1844 = VA_ARG (ap, 0B, 0);
4567 return D.1844;
4569 f2 (int i)
4570 struct ap[1];
4571 __builtin_va_start (&ap, 0);
4572 res = f2_1 (&ap);
4573 __builtin_va_end (&ap);
4574 D.1841 = res;
4575 return D.1841;
4577 Case 2b is different because:
4578 - on the callee side, the parm decl has declared type va_list, but
4579 grokdeclarator changes the type of the parm decl to a pointer to the
4580 array elem type.
4581 - on the caller side, the pass-by-value uses &ap.
4583 We unify these two cases (case 2a: va_list is array type,
4584 case 2b: va_list is pointer to array elem type), by adding '&' for the
4585 array type case, such that we have a pointer to array elem in both
4586 cases. */
4588 if (TREE_CODE (va_type) == ARRAY_TYPE)
4590 /* Case 2a: va_list is array type. */
4592 /* Take the address, to get '&ap'. Make sure it's a pointer to array
4593 elem type. */
4594 mark_addressable (expr);
4595 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4596 expr);
4598 /* Verify that &ap is still recognized as having va_list type. */
4599 tree canon_expr_type
4600 = targetm.canonical_va_list_type (TREE_TYPE (expr));
4601 gcc_assert (canon_expr_type != NULL_TREE);
4603 else
4605 /* Case 2b: va_list is pointer to array elem type. */
4606 gcc_assert (POINTER_TYPE_P (va_type));
4608 /* Comparison as in std_canonical_va_list_type. */
4609 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4610 == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4612 /* Don't take the address. We've already got '&ap'. */
4616 return build_va_arg_1 (loc, type, expr);
4620 /* Linked list of disabled built-in functions. */
4622 struct disabled_builtin
4624 const char *name;
4625 struct disabled_builtin *next;
4627 static disabled_builtin *disabled_builtins = NULL;
4629 static bool builtin_function_disabled_p (const char *);
4631 /* Disable a built-in function specified by -fno-builtin-NAME. If NAME
4632 begins with "__builtin_", give an error. */
4634 void
4635 disable_builtin_function (const char *name)
4637 if (strncmp (name, "__builtin_", strlen ("__builtin_")) == 0)
4638 error ("cannot disable built-in function %qs", name);
4639 else
4641 disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4642 new_disabled_builtin->name = name;
4643 new_disabled_builtin->next = disabled_builtins;
4644 disabled_builtins = new_disabled_builtin;
4649 /* Return true if the built-in function NAME has been disabled, false
4650 otherwise. */
4652 static bool
4653 builtin_function_disabled_p (const char *name)
4655 disabled_builtin *p;
4656 for (p = disabled_builtins; p != NULL; p = p->next)
4658 if (strcmp (name, p->name) == 0)
4659 return true;
4661 return false;
4665 /* Worker for DEF_BUILTIN.
4666 Possibly define a builtin function with one or two names.
4667 Does not declare a non-__builtin_ function if flag_no_builtin, or if
4668 nonansi_p and flag_no_nonansi_builtin. */
4670 static void
4671 def_builtin_1 (enum built_in_function fncode,
4672 const char *name,
4673 enum built_in_class fnclass,
4674 tree fntype, tree libtype,
4675 bool both_p, bool fallback_p, bool nonansi_p,
4676 tree fnattrs, bool implicit_p)
4678 tree decl;
4679 const char *libname;
4681 if (fntype == error_mark_node)
4682 return;
4684 gcc_assert ((!both_p && !fallback_p)
4685 || !strncmp (name, "__builtin_",
4686 strlen ("__builtin_")));
4688 libname = name + strlen ("__builtin_");
4689 decl = add_builtin_function (name, fntype, fncode, fnclass,
4690 (fallback_p ? libname : NULL),
4691 fnattrs);
4693 set_builtin_decl (fncode, decl, implicit_p);
4695 if (both_p
4696 && !flag_no_builtin && !builtin_function_disabled_p (libname)
4697 && !(nonansi_p && flag_no_nonansi_builtin))
4698 add_builtin_function (libname, libtype, fncode, fnclass,
4699 NULL, fnattrs);
4702 /* Nonzero if the type T promotes to int. This is (nearly) the
4703 integral promotions defined in ISO C99 6.3.1.1/2. */
4705 bool
4706 c_promoting_integer_type_p (const_tree t)
4708 switch (TREE_CODE (t))
4710 case INTEGER_TYPE:
4711 return (TYPE_MAIN_VARIANT (t) == char_type_node
4712 || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4713 || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4714 || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4715 || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
4716 || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
4718 case ENUMERAL_TYPE:
4719 /* ??? Technically all enumerations not larger than an int
4720 promote to an int. But this is used along code paths
4721 that only want to notice a size change. */
4722 return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
4724 case BOOLEAN_TYPE:
4725 return true;
4727 default:
4728 return false;
4732 /* Return 1 if PARMS specifies a fixed number of parameters
4733 and none of their types is affected by default promotions. */
4735 bool
4736 self_promoting_args_p (const_tree parms)
4738 const_tree t;
4739 for (t = parms; t; t = TREE_CHAIN (t))
4741 tree type = TREE_VALUE (t);
4743 if (type == error_mark_node)
4744 continue;
4746 if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
4747 return false;
4749 if (type == NULL_TREE)
4750 return false;
4752 if (TYPE_MAIN_VARIANT (type) == float_type_node)
4753 return false;
4755 if (c_promoting_integer_type_p (type))
4756 return false;
4758 return true;
4761 /* Recursively remove any '*' or '&' operator from TYPE. */
4762 tree
4763 strip_pointer_operator (tree t)
4765 while (POINTER_TYPE_P (t))
4766 t = TREE_TYPE (t);
4767 return t;
4770 /* Recursively remove pointer or array type from TYPE. */
4771 tree
4772 strip_pointer_or_array_types (tree t)
4774 while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
4775 t = TREE_TYPE (t);
4776 return t;
4779 /* Used to compare case labels. K1 and K2 are actually tree nodes
4780 representing case labels, or NULL_TREE for a `default' label.
4781 Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
4782 K2, and 0 if K1 and K2 are equal. */
4785 case_compare (splay_tree_key k1, splay_tree_key k2)
4787 /* Consider a NULL key (such as arises with a `default' label) to be
4788 smaller than anything else. */
4789 if (!k1)
4790 return k2 ? -1 : 0;
4791 else if (!k2)
4792 return k1 ? 1 : 0;
4794 return tree_int_cst_compare ((tree) k1, (tree) k2);
4797 /* Process a case label, located at LOC, for the range LOW_VALUE
4798 ... HIGH_VALUE. If LOW_VALUE and HIGH_VALUE are both NULL_TREE
4799 then this case label is actually a `default' label. If only
4800 HIGH_VALUE is NULL_TREE, then case label was declared using the
4801 usual C/C++ syntax, rather than the GNU case range extension.
4802 CASES is a tree containing all the case ranges processed so far;
4803 COND is the condition for the switch-statement itself.
4804 Returns the CASE_LABEL_EXPR created, or ERROR_MARK_NODE if no
4805 CASE_LABEL_EXPR is created. */
4807 tree
4808 c_add_case_label (location_t loc, splay_tree cases, tree cond,
4809 tree low_value, tree high_value)
4811 tree type;
4812 tree label;
4813 tree case_label;
4814 splay_tree_node node;
4816 /* Create the LABEL_DECL itself. */
4817 label = create_artificial_label (loc);
4819 /* If there was an error processing the switch condition, bail now
4820 before we get more confused. */
4821 if (!cond || cond == error_mark_node)
4822 goto error_out;
4824 if ((low_value && TREE_TYPE (low_value)
4825 && POINTER_TYPE_P (TREE_TYPE (low_value)))
4826 || (high_value && TREE_TYPE (high_value)
4827 && POINTER_TYPE_P (TREE_TYPE (high_value))))
4829 error_at (loc, "pointers are not permitted as case values");
4830 goto error_out;
4833 /* Case ranges are a GNU extension. */
4834 if (high_value)
4835 pedwarn (loc, OPT_Wpedantic,
4836 "range expressions in switch statements are non-standard");
4838 type = TREE_TYPE (cond);
4839 if (low_value)
4841 low_value = check_case_value (loc, low_value);
4842 low_value = convert_and_check (loc, type, low_value);
4843 low_value = fold (low_value);
4844 if (low_value == error_mark_node)
4845 goto error_out;
4847 if (high_value)
4849 high_value = check_case_value (loc, high_value);
4850 high_value = convert_and_check (loc, type, high_value);
4851 high_value = fold (high_value);
4852 if (high_value == error_mark_node)
4853 goto error_out;
4856 if (low_value && high_value)
4858 /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
4859 really a case range, even though it was written that way.
4860 Remove the HIGH_VALUE to simplify later processing. */
4861 if (tree_int_cst_equal (low_value, high_value))
4862 high_value = NULL_TREE;
4863 else if (!tree_int_cst_lt (low_value, high_value))
4864 warning_at (loc, 0, "empty range specified");
4867 /* Look up the LOW_VALUE in the table of case labels we already
4868 have. */
4869 node = splay_tree_lookup (cases, (splay_tree_key) low_value);
4870 /* If there was not an exact match, check for overlapping ranges.
4871 There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
4872 that's a `default' label and the only overlap is an exact match. */
4873 if (!node && (low_value || high_value))
4875 splay_tree_node low_bound;
4876 splay_tree_node high_bound;
4878 /* Even though there wasn't an exact match, there might be an
4879 overlap between this case range and another case range.
4880 Since we've (inductively) not allowed any overlapping case
4881 ranges, we simply need to find the greatest low case label
4882 that is smaller that LOW_VALUE, and the smallest low case
4883 label that is greater than LOW_VALUE. If there is an overlap
4884 it will occur in one of these two ranges. */
4885 low_bound = splay_tree_predecessor (cases,
4886 (splay_tree_key) low_value);
4887 high_bound = splay_tree_successor (cases,
4888 (splay_tree_key) low_value);
4890 /* Check to see if the LOW_BOUND overlaps. It is smaller than
4891 the LOW_VALUE, so there is no need to check unless the
4892 LOW_BOUND is in fact itself a case range. */
4893 if (low_bound
4894 && CASE_HIGH ((tree) low_bound->value)
4895 && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
4896 low_value) >= 0)
4897 node = low_bound;
4898 /* Check to see if the HIGH_BOUND overlaps. The low end of that
4899 range is bigger than the low end of the current range, so we
4900 are only interested if the current range is a real range, and
4901 not an ordinary case label. */
4902 else if (high_bound
4903 && high_value
4904 && (tree_int_cst_compare ((tree) high_bound->key,
4905 high_value)
4906 <= 0))
4907 node = high_bound;
4909 /* If there was an overlap, issue an error. */
4910 if (node)
4912 tree duplicate = CASE_LABEL ((tree) node->value);
4914 if (high_value)
4916 error_at (loc, "duplicate (or overlapping) case value");
4917 inform (DECL_SOURCE_LOCATION (duplicate),
4918 "this is the first entry overlapping that value");
4920 else if (low_value)
4922 error_at (loc, "duplicate case value") ;
4923 inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
4925 else
4927 error_at (loc, "multiple default labels in one switch");
4928 inform (DECL_SOURCE_LOCATION (duplicate),
4929 "this is the first default label");
4931 goto error_out;
4934 /* Add a CASE_LABEL to the statement-tree. */
4935 case_label = add_stmt (build_case_label (low_value, high_value, label));
4936 /* Register this case label in the splay tree. */
4937 splay_tree_insert (cases,
4938 (splay_tree_key) low_value,
4939 (splay_tree_value) case_label);
4941 return case_label;
4943 error_out:
4944 /* Add a label so that the back-end doesn't think that the beginning of
4945 the switch is unreachable. Note that we do not add a case label, as
4946 that just leads to duplicates and thence to failure later on. */
4947 if (!cases->root)
4949 tree t = create_artificial_label (loc);
4950 add_stmt (build_stmt (loc, LABEL_EXPR, t));
4952 return error_mark_node;
4955 /* Subroutine of c_switch_covers_all_cases_p, called via
4956 splay_tree_foreach. Return 1 if it doesn't cover all the cases.
4957 ARGS[0] is initially NULL and after the first iteration is the
4958 so far highest case label. ARGS[1] is the minimum of SWITCH_COND's
4959 type. */
4961 static int
4962 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
4964 tree label = (tree) node->value;
4965 tree *args = (tree *) data;
4967 /* If there is a default case, we shouldn't have called this. */
4968 gcc_assert (CASE_LOW (label));
4970 if (args[0] == NULL_TREE)
4972 if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
4973 return 1;
4975 else if (wi::add (wi::to_widest (args[0]), 1)
4976 != wi::to_widest (CASE_LOW (label)))
4977 return 1;
4978 if (CASE_HIGH (label))
4979 args[0] = CASE_HIGH (label);
4980 else
4981 args[0] = CASE_LOW (label);
4982 return 0;
4985 /* Return true if switch with CASES and switch condition with type
4986 covers all possible values in the case labels. */
4988 bool
4989 c_switch_covers_all_cases_p (splay_tree cases, tree type)
4991 /* If there is default:, this is always the case. */
4992 splay_tree_node default_node
4993 = splay_tree_lookup (cases, (splay_tree_key) NULL);
4994 if (default_node)
4995 return true;
4997 if (!INTEGRAL_TYPE_P (type))
4998 return false;
5000 tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
5001 if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
5002 return false;
5004 /* If there are no cases at all, or if the highest case label
5005 is smaller than TYPE_MAX_VALUE, return false. */
5006 if (args[0] == NULL_TREE
5007 || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
5008 return false;
5010 return true;
5013 /* Return true if stmt can fall through. Used by block_may_fallthru
5014 default case. */
5016 bool
5017 c_block_may_fallthru (const_tree stmt)
5019 switch (TREE_CODE (stmt))
5021 case SWITCH_STMT:
5022 return (!SWITCH_STMT_ALL_CASES_P (stmt)
5023 || !SWITCH_STMT_NO_BREAK_P (stmt)
5024 || block_may_fallthru (SWITCH_STMT_BODY (stmt)));
5026 default:
5027 return true;
5031 /* Finish an expression taking the address of LABEL (an
5032 IDENTIFIER_NODE). Returns an expression for the address.
5034 LOC is the location for the expression returned. */
5036 tree
5037 finish_label_address_expr (tree label, location_t loc)
5039 tree result;
5041 pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
5043 if (label == error_mark_node)
5044 return error_mark_node;
5046 label = lookup_label (label);
5047 if (label == NULL_TREE)
5048 result = null_pointer_node;
5049 else
5051 TREE_USED (label) = 1;
5052 result = build1 (ADDR_EXPR, ptr_type_node, label);
5053 /* The current function is not necessarily uninlinable.
5054 Computed gotos are incompatible with inlining, but the value
5055 here could be used only in a diagnostic, for example. */
5056 protected_set_expr_location (result, loc);
5059 return result;
5063 /* Given a boolean expression ARG, return a tree representing an increment
5064 or decrement (as indicated by CODE) of ARG. The front end must check for
5065 invalid cases (e.g., decrement in C++). */
5066 tree
5067 boolean_increment (enum tree_code code, tree arg)
5069 tree val;
5070 tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5072 arg = stabilize_reference (arg);
5073 switch (code)
5075 case PREINCREMENT_EXPR:
5076 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5077 break;
5078 case POSTINCREMENT_EXPR:
5079 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5080 arg = save_expr (arg);
5081 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5082 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5083 break;
5084 case PREDECREMENT_EXPR:
5085 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5086 invert_truthvalue_loc (input_location, arg));
5087 break;
5088 case POSTDECREMENT_EXPR:
5089 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5090 invert_truthvalue_loc (input_location, arg));
5091 arg = save_expr (arg);
5092 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5093 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5094 break;
5095 default:
5096 gcc_unreachable ();
5098 TREE_SIDE_EFFECTS (val) = 1;
5099 return val;
5102 /* Built-in macros for stddef.h and stdint.h, that require macros
5103 defined in this file. */
5104 void
5105 c_stddef_cpp_builtins(void)
5107 builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5108 builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5109 builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5110 builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5111 builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5112 builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5113 if (flag_char8_t)
5114 builtin_define_with_value ("__CHAR8_TYPE__", CHAR8_TYPE, 0);
5115 builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5116 builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5117 if (SIG_ATOMIC_TYPE)
5118 builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5119 if (INT8_TYPE)
5120 builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5121 if (INT16_TYPE)
5122 builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5123 if (INT32_TYPE)
5124 builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5125 if (INT64_TYPE)
5126 builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5127 if (UINT8_TYPE)
5128 builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5129 if (UINT16_TYPE)
5130 builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5131 if (UINT32_TYPE)
5132 builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5133 if (UINT64_TYPE)
5134 builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5135 if (INT_LEAST8_TYPE)
5136 builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5137 if (INT_LEAST16_TYPE)
5138 builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5139 if (INT_LEAST32_TYPE)
5140 builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5141 if (INT_LEAST64_TYPE)
5142 builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5143 if (UINT_LEAST8_TYPE)
5144 builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5145 if (UINT_LEAST16_TYPE)
5146 builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5147 if (UINT_LEAST32_TYPE)
5148 builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5149 if (UINT_LEAST64_TYPE)
5150 builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5151 if (INT_FAST8_TYPE)
5152 builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5153 if (INT_FAST16_TYPE)
5154 builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5155 if (INT_FAST32_TYPE)
5156 builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5157 if (INT_FAST64_TYPE)
5158 builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5159 if (UINT_FAST8_TYPE)
5160 builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5161 if (UINT_FAST16_TYPE)
5162 builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5163 if (UINT_FAST32_TYPE)
5164 builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5165 if (UINT_FAST64_TYPE)
5166 builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5167 if (INTPTR_TYPE)
5168 builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5169 if (UINTPTR_TYPE)
5170 builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5171 /* GIMPLE FE testcases need access to the GCC internal 'sizetype'.
5172 Expose it as __SIZETYPE__. */
5173 if (flag_gimple)
5174 builtin_define_with_value ("__SIZETYPE__", SIZETYPE, 0);
5177 static void
5178 c_init_attributes (void)
5180 /* Fill in the built_in_attributes array. */
5181 #define DEF_ATTR_NULL_TREE(ENUM) \
5182 built_in_attributes[(int) ENUM] = NULL_TREE;
5183 #define DEF_ATTR_INT(ENUM, VALUE) \
5184 built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5185 #define DEF_ATTR_STRING(ENUM, VALUE) \
5186 built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5187 #define DEF_ATTR_IDENT(ENUM, STRING) \
5188 built_in_attributes[(int) ENUM] = get_identifier (STRING);
5189 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5190 built_in_attributes[(int) ENUM] \
5191 = tree_cons (built_in_attributes[(int) PURPOSE], \
5192 built_in_attributes[(int) VALUE], \
5193 built_in_attributes[(int) CHAIN]);
5194 #include "builtin-attrs.def"
5195 #undef DEF_ATTR_NULL_TREE
5196 #undef DEF_ATTR_INT
5197 #undef DEF_ATTR_IDENT
5198 #undef DEF_ATTR_TREE_LIST
5201 /* Check whether the byte alignment ALIGN is a valid user-specified
5202 alignment less than the supported maximum. If so, return ALIGN's
5203 base-2 log; if not, output an error and return -1. If OBJFILE
5204 then reject alignments greater than MAX_OFILE_ALIGNMENT when
5205 converted to bits. Otherwise, consider valid only alignments
5206 that are less than HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT.
5207 Zero is not considered a valid argument (and results in -1 on
5208 return) but it only triggers a warning when WARN_ZERO is set. */
5211 check_user_alignment (const_tree align, bool objfile, bool warn_zero)
5213 if (error_operand_p (align))
5214 return -1;
5216 if (TREE_CODE (align) != INTEGER_CST
5217 || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5219 error ("requested alignment is not an integer constant");
5220 return -1;
5223 if (integer_zerop (align))
5225 if (warn_zero)
5226 warning (OPT_Wattributes,
5227 "requested alignment %qE is not a positive power of 2",
5228 align);
5229 return -1;
5232 /* Log2 of the byte alignment ALIGN. */
5233 int log2align;
5234 if (tree_int_cst_sgn (align) == -1
5235 || (log2align = tree_log2 (align)) == -1)
5237 error ("requested alignment %qE is not a positive power of 2",
5238 align);
5239 return -1;
5242 if (objfile)
5244 unsigned maxalign = MAX_OFILE_ALIGNMENT / BITS_PER_UNIT;
5245 if (!tree_fits_uhwi_p (align) || tree_to_uhwi (align) > maxalign)
5247 error ("requested alignment %qE exceeds object file maximum %u",
5248 align, maxalign);
5249 return -1;
5253 if (log2align >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5255 error ("requested alignment %qE exceeds maximum %u",
5256 align, 1U << (HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT - 1));
5257 return -1;
5260 return log2align;
5263 /* Determine the ELF symbol visibility for DECL, which is either a
5264 variable or a function. It is an error to use this function if a
5265 definition of DECL is not available in this translation unit.
5266 Returns true if the final visibility has been determined by this
5267 function; false if the caller is free to make additional
5268 modifications. */
5270 bool
5271 c_determine_visibility (tree decl)
5273 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5275 /* If the user explicitly specified the visibility with an
5276 attribute, honor that. DECL_VISIBILITY will have been set during
5277 the processing of the attribute. We check for an explicit
5278 attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5279 to distinguish the use of an attribute from the use of a "#pragma
5280 GCC visibility push(...)"; in the latter case we still want other
5281 considerations to be able to overrule the #pragma. */
5282 if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5283 || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5284 && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5285 || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5286 return true;
5288 /* Set default visibility to whatever the user supplied with
5289 visibility_specified depending on #pragma GCC visibility. */
5290 if (!DECL_VISIBILITY_SPECIFIED (decl))
5292 if (visibility_options.inpragma
5293 || DECL_VISIBILITY (decl) != default_visibility)
5295 DECL_VISIBILITY (decl) = default_visibility;
5296 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5297 /* If visibility changed and DECL already has DECL_RTL, ensure
5298 symbol flags are updated. */
5299 if (((VAR_P (decl) && TREE_STATIC (decl))
5300 || TREE_CODE (decl) == FUNCTION_DECL)
5301 && DECL_RTL_SET_P (decl))
5302 make_decl_rtl (decl);
5305 return false;
5308 /* Data to communicate through check_function_arguments_recurse between
5309 check_function_nonnull and check_nonnull_arg. */
5311 struct nonnull_arg_ctx
5313 /* Location of the call. */
5314 location_t loc;
5315 /* The function whose arguments are being checked and its type (used
5316 for calls through function pointers). */
5317 const_tree fndecl, fntype;
5318 /* True if a warning has been issued. */
5319 bool warned_p;
5322 /* Check the argument list of a function call to CTX.FNDECL of CTX.FNTYPE
5323 for null in argument slots that are marked as requiring a non-null
5324 pointer argument. The NARGS arguments are passed in the array ARGARRAY.
5325 Return true if we have warned. */
5327 static bool
5328 check_function_nonnull (nonnull_arg_ctx &ctx, int nargs, tree *argarray)
5330 int firstarg = 0;
5331 if (TREE_CODE (ctx.fntype) == METHOD_TYPE)
5333 bool closure = false;
5334 if (ctx.fndecl)
5336 /* For certain lambda expressions the C++ front end emits calls
5337 that pass a null this pointer as an argument named __closure
5338 to the member operator() of empty function. Detect those
5339 and avoid checking them, but proceed to check the remaining
5340 arguments. */
5341 tree arg0 = DECL_ARGUMENTS (ctx.fndecl);
5342 if (tree arg0name = DECL_NAME (arg0))
5343 closure = id_equal (arg0name, "__closure");
5346 /* In calls to C++ non-static member functions check the this
5347 pointer regardless of whether the function is declared with
5348 attribute nonnull. */
5349 firstarg = 1;
5350 if (!closure)
5351 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[0],
5352 firstarg);
5355 tree attrs = lookup_attribute ("nonnull", TYPE_ATTRIBUTES (ctx.fntype));
5356 if (attrs == NULL_TREE)
5357 return ctx.warned_p;
5359 tree a = attrs;
5360 /* See if any of the nonnull attributes has no arguments. If so,
5361 then every pointer argument is checked (in which case the check
5362 for pointer type is done in check_nonnull_arg). */
5363 if (TREE_VALUE (a) != NULL_TREE)
5365 a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5366 while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5368 if (a != NULL_TREE)
5369 for (int i = firstarg; i < nargs; i++)
5370 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5371 i + 1);
5372 else
5374 /* Walk the argument list. If we encounter an argument number we
5375 should check for non-null, do it. */
5376 for (int i = firstarg; i < nargs; i++)
5378 for (a = attrs; ; a = TREE_CHAIN (a))
5380 a = lookup_attribute ("nonnull", a);
5381 if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5382 break;
5385 if (a != NULL_TREE)
5386 check_function_arguments_recurse (check_nonnull_arg, &ctx,
5387 argarray[i], i + 1);
5390 return ctx.warned_p;
5393 /* Check that the Nth argument of a function call (counting backwards
5394 from the end) is a (pointer)0. The NARGS arguments are passed in the
5395 array ARGARRAY. */
5397 static void
5398 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5400 tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5402 if (attr)
5404 int len = 0;
5405 int pos = 0;
5406 tree sentinel;
5407 function_args_iterator iter;
5408 tree t;
5410 /* Skip over the named arguments. */
5411 FOREACH_FUNCTION_ARGS (fntype, t, iter)
5413 if (len == nargs)
5414 break;
5415 len++;
5418 if (TREE_VALUE (attr))
5420 tree p = TREE_VALUE (TREE_VALUE (attr));
5421 pos = TREE_INT_CST_LOW (p);
5424 /* The sentinel must be one of the varargs, i.e.
5425 in position >= the number of fixed arguments. */
5426 if ((nargs - 1 - pos) < len)
5428 warning (OPT_Wformat_,
5429 "not enough variable arguments to fit a sentinel");
5430 return;
5433 /* Validate the sentinel. */
5434 sentinel = fold_for_warn (argarray[nargs - 1 - pos]);
5435 if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5436 || !integer_zerop (sentinel))
5437 /* Although __null (in C++) is only an integer we allow it
5438 nevertheless, as we are guaranteed that it's exactly
5439 as wide as a pointer, and we don't want to force
5440 users to cast the NULL they have written there.
5441 We warn with -Wstrict-null-sentinel, though. */
5442 && (warn_strict_null_sentinel || null_node != sentinel))
5443 warning (OPT_Wformat_, "missing sentinel in function call");
5447 /* Check that the same argument isn't passed to two or more
5448 restrict-qualified formal and issue a -Wrestrict warning
5449 if it is. Return true if a warning has been issued. */
5451 static bool
5452 check_function_restrict (const_tree fndecl, const_tree fntype,
5453 int nargs, tree *unfolded_argarray)
5455 int i;
5456 tree parms = TYPE_ARG_TYPES (fntype);
5458 /* Call fold_for_warn on all of the arguments. */
5459 auto_vec<tree> argarray (nargs);
5460 for (i = 0; i < nargs; i++)
5461 argarray.quick_push (fold_for_warn (unfolded_argarray[i]));
5463 if (fndecl
5464 && TREE_CODE (fndecl) == FUNCTION_DECL)
5466 /* Avoid diagnosing calls built-ins with a zero size/bound
5467 here. They are checked in more detail elsewhere. */
5468 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
5469 && nargs == 3
5470 && TREE_CODE (argarray[2]) == INTEGER_CST
5471 && integer_zerop (argarray[2]))
5472 return false;
5474 if (DECL_ARGUMENTS (fndecl))
5475 parms = DECL_ARGUMENTS (fndecl);
5478 for (i = 0; i < nargs; i++)
5479 TREE_VISITED (argarray[i]) = 0;
5481 bool warned = false;
5483 for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5485 tree type;
5486 if (TREE_CODE (parms) == PARM_DECL)
5488 type = TREE_TYPE (parms);
5489 parms = DECL_CHAIN (parms);
5491 else
5493 type = TREE_VALUE (parms);
5494 parms = TREE_CHAIN (parms);
5496 if (POINTER_TYPE_P (type)
5497 && TYPE_RESTRICT (type)
5498 && !TYPE_READONLY (TREE_TYPE (type)))
5499 warned |= warn_for_restrict (i, argarray.address (), nargs);
5502 for (i = 0; i < nargs; i++)
5503 TREE_VISITED (argarray[i]) = 0;
5505 return warned;
5508 /* Helper for check_function_nonnull; given a list of operands which
5509 must be non-null in ARGS, determine if operand PARAM_NUM should be
5510 checked. */
5512 static bool
5513 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5515 unsigned HOST_WIDE_INT arg_num = 0;
5517 for (; args; args = TREE_CHAIN (args))
5519 bool found = get_attribute_operand (TREE_VALUE (args), &arg_num);
5521 gcc_assert (found);
5523 if (arg_num == param_num)
5524 return true;
5526 return false;
5529 /* Check that the function argument PARAM (which is operand number
5530 PARAM_NUM) is non-null. This is called by check_function_nonnull
5531 via check_function_arguments_recurse. */
5533 static void
5534 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5536 struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5538 /* Just skip checking the argument if it's not a pointer. This can
5539 happen if the "nonnull" attribute was given without an operand
5540 list (which means to check every pointer argument). */
5542 tree paramtype = TREE_TYPE (param);
5543 if (TREE_CODE (paramtype) != POINTER_TYPE
5544 && TREE_CODE (paramtype) != NULLPTR_TYPE)
5545 return;
5547 /* Diagnose the simple cases of null arguments. */
5548 if (!integer_zerop (fold_for_warn (param)))
5549 return;
5551 auto_diagnostic_group adg;
5553 const location_t loc = EXPR_LOC_OR_LOC (param, pctx->loc);
5555 if (TREE_CODE (pctx->fntype) == METHOD_TYPE)
5556 --param_num;
5558 bool warned;
5559 if (param_num == 0)
5561 warned = warning_at (loc, OPT_Wnonnull,
5562 "%qs pointer null", "this");
5563 if (warned && pctx->fndecl)
5564 inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5565 "in a call to non-static member function %qD",
5566 pctx->fndecl);
5568 else
5570 warned = warning_at (loc, OPT_Wnonnull,
5571 "argument %u null where non-null expected",
5572 (unsigned) param_num);
5573 if (warned && pctx->fndecl)
5574 inform (DECL_SOURCE_LOCATION (pctx->fndecl),
5575 "in a call to function %qD declared %qs",
5576 pctx->fndecl, "nonnull");
5579 if (warned)
5580 pctx->warned_p = true;
5583 /* Helper for attribute handling; fetch the operand number from
5584 the attribute argument list. */
5586 bool
5587 get_attribute_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5589 /* Verify the arg number is a small constant. */
5590 if (tree_fits_uhwi_p (arg_num_expr))
5592 *valp = tree_to_uhwi (arg_num_expr);
5593 return true;
5595 else
5596 return false;
5599 /* Arguments being collected for optimization. */
5600 typedef const char *const_char_p; /* For DEF_VEC_P. */
5601 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5604 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5605 options in ARGS. ATTR_P is true if this is for attribute(optimize), and
5606 false for #pragma GCC optimize. */
5608 bool
5609 parse_optimize_options (tree args, bool attr_p)
5611 bool ret = true;
5612 unsigned opt_argc;
5613 unsigned i;
5614 const char **opt_argv;
5615 struct cl_decoded_option *decoded_options;
5616 unsigned int decoded_options_count;
5617 tree ap;
5619 /* Build up argv vector. Just in case the string is stored away, use garbage
5620 collected strings. */
5621 vec_safe_truncate (optimize_args, 0);
5622 vec_safe_push (optimize_args, (const char *) NULL);
5624 for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5626 tree value = TREE_VALUE (ap);
5628 if (TREE_CODE (value) == INTEGER_CST)
5630 char buffer[20];
5631 sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5632 vec_safe_push (optimize_args, ggc_strdup (buffer));
5635 else if (TREE_CODE (value) == STRING_CST)
5637 /* Split string into multiple substrings. */
5638 size_t len = TREE_STRING_LENGTH (value);
5639 char *p = ASTRDUP (TREE_STRING_POINTER (value));
5640 char *end = p + len;
5641 char *comma;
5642 char *next_p = p;
5644 while (next_p != NULL)
5646 size_t len2;
5647 char *q, *r;
5649 p = next_p;
5650 comma = strchr (p, ',');
5651 if (comma)
5653 len2 = comma - p;
5654 *comma = '\0';
5655 next_p = comma+1;
5657 else
5659 len2 = end - p;
5660 next_p = NULL;
5663 /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5664 options. */
5665 if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5667 ret = false;
5668 if (attr_p)
5669 warning (OPT_Wattributes,
5670 "bad option %qs to attribute %<optimize%>", p);
5671 else
5672 warning (OPT_Wpragmas,
5673 "bad option %qs to pragma %<optimize%>", p);
5674 continue;
5677 /* Can't use GC memory here, see PR88007. */
5678 r = q = XOBNEWVEC (&opts_obstack, char, len2 + 3);
5680 if (*p != '-')
5682 *r++ = '-';
5684 /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5685 itself is -Os, and any other switch begins with a -f. */
5686 if ((*p >= '0' && *p <= '9')
5687 || (p[0] == 's' && p[1] == '\0'))
5688 *r++ = 'O';
5689 else if (*p != 'O')
5690 *r++ = 'f';
5693 memcpy (r, p, len2);
5694 r[len2] = '\0';
5695 vec_safe_push (optimize_args, (const char *) q);
5701 opt_argc = optimize_args->length ();
5702 opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5704 for (i = 1; i < opt_argc; i++)
5705 opt_argv[i] = (*optimize_args)[i];
5707 /* Now parse the options. */
5708 decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
5709 &decoded_options,
5710 &decoded_options_count);
5711 /* Drop non-Optimization options. */
5712 unsigned j = 1;
5713 for (i = 1; i < decoded_options_count; ++i)
5715 if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
5717 ret = false;
5718 if (attr_p)
5719 warning (OPT_Wattributes,
5720 "bad option %qs to attribute %<optimize%>",
5721 decoded_options[i].orig_option_with_args_text);
5722 else
5723 warning (OPT_Wpragmas,
5724 "bad option %qs to pragma %<optimize%>",
5725 decoded_options[i].orig_option_with_args_text);
5726 continue;
5728 if (i != j)
5729 decoded_options[j] = decoded_options[i];
5730 j++;
5732 decoded_options_count = j;
5733 /* And apply them. */
5734 decode_options (&global_options, &global_options_set,
5735 decoded_options, decoded_options_count,
5736 input_location, global_dc, NULL);
5738 targetm.override_options_after_change();
5740 optimize_args->truncate (0);
5741 return ret;
5744 /* Check whether ATTR is a valid attribute fallthrough. */
5746 bool
5747 attribute_fallthrough_p (tree attr)
5749 if (attr == error_mark_node)
5750 return false;
5751 tree t = lookup_attribute ("fallthrough", attr);
5752 if (t == NULL_TREE)
5753 return false;
5754 /* This attribute shall appear at most once in each attribute-list. */
5755 if (lookup_attribute ("fallthrough", TREE_CHAIN (t)))
5756 warning (OPT_Wattributes, "%<fallthrough%> attribute specified multiple "
5757 "times");
5758 /* No attribute-argument-clause shall be present. */
5759 else if (TREE_VALUE (t) != NULL_TREE)
5760 warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
5761 "a parameter");
5762 /* Warn if other attributes are found. */
5763 for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
5765 tree name = get_attribute_name (t);
5766 if (!is_attribute_p ("fallthrough", name))
5768 if (!c_dialect_cxx () && get_attribute_namespace (t) == NULL_TREE)
5769 /* The specifications of standard attributes in C mean
5770 this is a constraint violation. */
5771 pedwarn (input_location, OPT_Wattributes, "%qE attribute ignored",
5772 get_attribute_name (t));
5773 else
5774 warning (OPT_Wattributes, "%qE attribute ignored", name);
5777 return true;
5781 /* Check for valid arguments being passed to a function with FNTYPE.
5782 There are NARGS arguments in the array ARGARRAY. LOC should be used
5783 for diagnostics. Return true if either -Wnonnull or -Wrestrict has
5784 been issued.
5786 The arguments in ARGARRAY may not have been folded yet (e.g. for C++,
5787 to preserve location wrappers); checks that require folded arguments
5788 should call fold_for_warn on them. */
5790 bool
5791 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
5792 int nargs, tree *argarray, vec<location_t> *arglocs)
5794 bool warned_p = false;
5796 /* Check for null being passed in a pointer argument that must be
5797 non-null. In C++, this includes the this pointer. We also need
5798 to do this if format checking is enabled. */
5799 if (warn_nonnull)
5801 nonnull_arg_ctx ctx = { loc, fndecl, fntype, false };
5802 warned_p = check_function_nonnull (ctx, nargs, argarray);
5805 /* Check for errors in format strings. */
5807 if (warn_format || warn_suggest_attribute_format)
5808 check_function_format (fntype, TYPE_ATTRIBUTES (fntype), nargs, argarray,
5809 arglocs);
5811 if (warn_format)
5812 check_function_sentinel (fntype, nargs, argarray);
5814 if (fndecl && fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
5816 switch (DECL_FUNCTION_CODE (fndecl))
5818 case BUILT_IN_SPRINTF:
5819 case BUILT_IN_SPRINTF_CHK:
5820 case BUILT_IN_SNPRINTF:
5821 case BUILT_IN_SNPRINTF_CHK:
5822 /* Let the sprintf pass handle these. */
5823 return warned_p;
5825 default:
5826 break;
5830 /* check_function_restrict sets the DECL_READ_P for arguments
5831 so it must be called unconditionally. */
5832 warned_p |= check_function_restrict (fndecl, fntype, nargs, argarray);
5834 return warned_p;
5837 /* Generic argument checking recursion routine. PARAM is the argument to
5838 be checked. PARAM_NUM is the number of the argument. CALLBACK is invoked
5839 once the argument is resolved. CTX is context for the callback. */
5840 void
5841 check_function_arguments_recurse (void (*callback)
5842 (void *, tree, unsigned HOST_WIDE_INT),
5843 void *ctx, tree param,
5844 unsigned HOST_WIDE_INT param_num)
5846 if (TREE_NO_WARNING (param))
5847 return;
5849 if (CONVERT_EXPR_P (param)
5850 && (TYPE_PRECISION (TREE_TYPE (param))
5851 == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
5853 /* Strip coercion. */
5854 check_function_arguments_recurse (callback, ctx,
5855 TREE_OPERAND (param, 0), param_num);
5856 return;
5859 if (TREE_CODE (param) == CALL_EXPR && CALL_EXPR_FN (param))
5861 tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
5862 tree attrs;
5863 bool found_format_arg = false;
5865 /* See if this is a call to a known internationalization function
5866 that modifies a format arg. Such a function may have multiple
5867 format_arg attributes (for example, ngettext). */
5869 for (attrs = TYPE_ATTRIBUTES (type);
5870 attrs;
5871 attrs = TREE_CHAIN (attrs))
5872 if (is_attribute_p ("format_arg", get_attribute_name (attrs)))
5874 tree inner_arg;
5875 tree format_num_expr;
5876 int format_num;
5877 int i;
5878 call_expr_arg_iterator iter;
5880 /* Extract the argument number, which was previously checked
5881 to be valid. */
5882 format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
5884 format_num = tree_to_uhwi (format_num_expr);
5886 for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
5887 inner_arg != NULL_TREE;
5888 inner_arg = next_call_expr_arg (&iter), i++)
5889 if (i == format_num)
5891 check_function_arguments_recurse (callback, ctx,
5892 inner_arg, param_num);
5893 found_format_arg = true;
5894 break;
5898 /* If we found a format_arg attribute and did a recursive check,
5899 we are done with checking this argument. Otherwise, we continue
5900 and this will be considered a non-literal. */
5901 if (found_format_arg)
5902 return;
5905 if (TREE_CODE (param) == COND_EXPR)
5907 /* Simplify to avoid warning for an impossible case. */
5908 param = fold_for_warn (param);
5909 if (TREE_CODE (param) == COND_EXPR)
5911 /* Check both halves of the conditional expression. */
5912 check_function_arguments_recurse (callback, ctx,
5913 TREE_OPERAND (param, 1),
5914 param_num);
5915 check_function_arguments_recurse (callback, ctx,
5916 TREE_OPERAND (param, 2),
5917 param_num);
5918 return;
5922 (*callback) (ctx, param, param_num);
5925 /* Checks for a builtin function FNDECL that the number of arguments
5926 NARGS against the required number REQUIRED and issues an error if
5927 there is a mismatch. Returns true if the number of arguments is
5928 correct, otherwise false. LOC is the location of FNDECL. */
5930 static bool
5931 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
5932 int required)
5934 if (nargs < required)
5936 error_at (loc, "too few arguments to function %qE", fndecl);
5937 return false;
5939 else if (nargs > required)
5941 error_at (loc, "too many arguments to function %qE", fndecl);
5942 return false;
5944 return true;
5947 /* Helper macro for check_builtin_function_arguments. */
5948 #define ARG_LOCATION(N) \
5949 (arg_loc.is_empty () \
5950 ? EXPR_LOC_OR_LOC (args[(N)], input_location) \
5951 : expansion_point_location (arg_loc[(N)]))
5953 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
5954 Returns false if there was an error, otherwise true. LOC is the
5955 location of the function; ARG_LOC is a vector of locations of the
5956 arguments. If FNDECL is the result of resolving an overloaded
5957 target built-in, ORIG_FNDECL is the original function decl,
5958 otherwise it is null. */
5960 bool
5961 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
5962 tree fndecl, tree orig_fndecl,
5963 int nargs, tree *args)
5965 if (!fndecl_built_in_p (fndecl))
5966 return true;
5968 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
5969 return (!targetm.check_builtin_call
5970 || targetm.check_builtin_call (loc, arg_loc, fndecl,
5971 orig_fndecl, nargs, args));
5973 if (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_FRONTEND)
5974 return true;
5976 gcc_assert (DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL);
5977 switch (DECL_FUNCTION_CODE (fndecl))
5979 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
5980 if (!tree_fits_uhwi_p (args[2]))
5982 error_at (ARG_LOCATION (2),
5983 "third argument to function %qE must be a constant integer",
5984 fndecl);
5985 return false;
5987 /* fall through */
5989 case BUILT_IN_ALLOCA_WITH_ALIGN:
5991 /* Get the requested alignment (in bits) if it's a constant
5992 integer expression. */
5993 unsigned HOST_WIDE_INT align
5994 = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
5996 /* Determine if the requested alignment is a power of 2. */
5997 if ((align & (align - 1)))
5998 align = 0;
6000 /* The maximum alignment in bits corresponding to the same
6001 maximum in bytes enforced in check_user_alignment(). */
6002 unsigned maxalign = (UINT_MAX >> 1) + 1;
6004 /* Reject invalid alignments. */
6005 if (align < BITS_PER_UNIT || maxalign < align)
6007 error_at (ARG_LOCATION (1),
6008 "second argument to function %qE must be a constant "
6009 "integer power of 2 between %qi and %qu bits",
6010 fndecl, BITS_PER_UNIT, maxalign);
6011 return false;
6013 return true;
6016 case BUILT_IN_CONSTANT_P:
6017 return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
6019 case BUILT_IN_ISFINITE:
6020 case BUILT_IN_ISINF:
6021 case BUILT_IN_ISINF_SIGN:
6022 case BUILT_IN_ISNAN:
6023 case BUILT_IN_ISNORMAL:
6024 case BUILT_IN_SIGNBIT:
6025 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
6027 if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
6029 error_at (ARG_LOCATION (0), "non-floating-point argument in "
6030 "call to function %qE", fndecl);
6031 return false;
6033 return true;
6035 return false;
6037 case BUILT_IN_ISGREATER:
6038 case BUILT_IN_ISGREATEREQUAL:
6039 case BUILT_IN_ISLESS:
6040 case BUILT_IN_ISLESSEQUAL:
6041 case BUILT_IN_ISLESSGREATER:
6042 case BUILT_IN_ISUNORDERED:
6043 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
6045 enum tree_code code0, code1;
6046 code0 = TREE_CODE (TREE_TYPE (args[0]));
6047 code1 = TREE_CODE (TREE_TYPE (args[1]));
6048 if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
6049 || (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
6050 || (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
6052 error_at (loc, "non-floating-point arguments in call to "
6053 "function %qE", fndecl);
6054 return false;
6056 return true;
6058 return false;
6060 case BUILT_IN_FPCLASSIFY:
6061 if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
6063 for (unsigned int i = 0; i < 5; i++)
6064 if (TREE_CODE (args[i]) != INTEGER_CST)
6066 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
6067 "call to function %qE", i + 1, fndecl);
6068 return false;
6071 if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
6073 error_at (ARG_LOCATION (5), "non-floating-point argument in "
6074 "call to function %qE", fndecl);
6075 return false;
6077 return true;
6079 return false;
6081 case BUILT_IN_ASSUME_ALIGNED:
6082 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
6084 if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
6086 error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
6087 "function %qE", fndecl);
6088 return false;
6090 return true;
6092 return false;
6094 case BUILT_IN_ADD_OVERFLOW:
6095 case BUILT_IN_SUB_OVERFLOW:
6096 case BUILT_IN_MUL_OVERFLOW:
6097 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6099 unsigned i;
6100 for (i = 0; i < 2; i++)
6101 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6103 error_at (ARG_LOCATION (i), "argument %u in call to function "
6104 "%qE does not have integral type", i + 1, fndecl);
6105 return false;
6107 if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
6108 || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
6110 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6111 "does not have pointer to integral type", fndecl);
6112 return false;
6114 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
6116 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6117 "has pointer to enumerated type", fndecl);
6118 return false;
6120 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
6122 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6123 "has pointer to boolean type", fndecl);
6124 return false;
6126 else if (TYPE_READONLY (TREE_TYPE (TREE_TYPE (args[2]))))
6128 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
6129 "has pointer to %<const%> type (%qT)", fndecl,
6130 TREE_TYPE (args[2]));
6131 return false;
6133 return true;
6135 return false;
6137 case BUILT_IN_ADD_OVERFLOW_P:
6138 case BUILT_IN_SUB_OVERFLOW_P:
6139 case BUILT_IN_MUL_OVERFLOW_P:
6140 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
6142 unsigned i;
6143 for (i = 0; i < 3; i++)
6144 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
6146 error_at (ARG_LOCATION (i), "argument %u in call to function "
6147 "%qE does not have integral type", i + 1, fndecl);
6148 return false;
6150 if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
6152 error_at (ARG_LOCATION (2), "argument 3 in call to function "
6153 "%qE has enumerated type", fndecl);
6154 return false;
6156 else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
6158 error_at (ARG_LOCATION (2), "argument 3 in call to function "
6159 "%qE has boolean type", fndecl);
6160 return false;
6162 return true;
6164 return false;
6166 default:
6167 return true;
6171 /* Subroutine of c_parse_error.
6172 Return the result of concatenating LHS and RHS. RHS is really
6173 a string literal, its first character is indicated by RHS_START and
6174 RHS_SIZE is its length (including the terminating NUL character).
6176 The caller is responsible for deleting the returned pointer. */
6178 static char *
6179 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
6181 const size_t lhs_size = strlen (lhs);
6182 char *result = XNEWVEC (char, lhs_size + rhs_size);
6183 memcpy (result, lhs, lhs_size);
6184 memcpy (result + lhs_size, rhs_start, rhs_size);
6185 return result;
6188 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
6189 before TOKEN, which had the associated VALUE. */
6191 void
6192 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
6193 tree value, unsigned char token_flags,
6194 rich_location *richloc)
6196 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
6198 char *message = NULL;
6200 if (token_type == CPP_EOF)
6201 message = catenate_messages (gmsgid, " at end of input");
6202 else if (token_type == CPP_CHAR
6203 || token_type == CPP_WCHAR
6204 || token_type == CPP_CHAR16
6205 || token_type == CPP_CHAR32
6206 || token_type == CPP_UTF8CHAR)
6208 unsigned int val = TREE_INT_CST_LOW (value);
6209 const char *prefix;
6211 switch (token_type)
6213 default:
6214 prefix = "";
6215 break;
6216 case CPP_WCHAR:
6217 prefix = "L";
6218 break;
6219 case CPP_CHAR16:
6220 prefix = "u";
6221 break;
6222 case CPP_CHAR32:
6223 prefix = "U";
6224 break;
6225 case CPP_UTF8CHAR:
6226 prefix = "u8";
6227 break;
6230 if (val <= UCHAR_MAX && ISGRAPH (val))
6231 message = catenate_messages (gmsgid, " before %s'%c'");
6232 else
6233 message = catenate_messages (gmsgid, " before %s'\\x%x'");
6235 error_at (richloc, message, prefix, val);
6236 free (message);
6237 message = NULL;
6239 else if (token_type == CPP_CHAR_USERDEF
6240 || token_type == CPP_WCHAR_USERDEF
6241 || token_type == CPP_CHAR16_USERDEF
6242 || token_type == CPP_CHAR32_USERDEF
6243 || token_type == CPP_UTF8CHAR_USERDEF)
6244 message = catenate_messages (gmsgid,
6245 " before user-defined character literal");
6246 else if (token_type == CPP_STRING_USERDEF
6247 || token_type == CPP_WSTRING_USERDEF
6248 || token_type == CPP_STRING16_USERDEF
6249 || token_type == CPP_STRING32_USERDEF
6250 || token_type == CPP_UTF8STRING_USERDEF)
6251 message = catenate_messages (gmsgid, " before user-defined string literal");
6252 else if (token_type == CPP_STRING
6253 || token_type == CPP_WSTRING
6254 || token_type == CPP_STRING16
6255 || token_type == CPP_STRING32
6256 || token_type == CPP_UTF8STRING)
6257 message = catenate_messages (gmsgid, " before string constant");
6258 else if (token_type == CPP_NUMBER)
6259 message = catenate_messages (gmsgid, " before numeric constant");
6260 else if (token_type == CPP_NAME)
6262 message = catenate_messages (gmsgid, " before %qE");
6263 error_at (richloc, message, value);
6264 free (message);
6265 message = NULL;
6267 else if (token_type == CPP_PRAGMA)
6268 message = catenate_messages (gmsgid, " before %<#pragma%>");
6269 else if (token_type == CPP_PRAGMA_EOL)
6270 message = catenate_messages (gmsgid, " before end of line");
6271 else if (token_type == CPP_DECLTYPE)
6272 message = catenate_messages (gmsgid, " before %<decltype%>");
6273 else if (token_type < N_TTYPES)
6275 message = catenate_messages (gmsgid, " before %qs token");
6276 error_at (richloc, message, cpp_type2name (token_type, token_flags));
6277 free (message);
6278 message = NULL;
6280 else
6281 error_at (richloc, gmsgid);
6283 if (message)
6285 error_at (richloc, message);
6286 free (message);
6288 #undef catenate_messages
6291 /* Return the gcc option code associated with the reason for a cpp
6292 message, or 0 if none. */
6294 static int
6295 c_option_controlling_cpp_diagnostic (enum cpp_warning_reason reason)
6297 const struct cpp_reason_option_codes_t *entry;
6299 for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6301 if (entry->reason == reason)
6302 return entry->option_code;
6304 return 0;
6307 /* Callback from cpp_diagnostic for PFILE to print diagnostics from the
6308 preprocessor. The diagnostic is of type LEVEL, with REASON set
6309 to the reason code if LEVEL is represents a warning, at location
6310 RICHLOC unless this is after lexing and the compiler's location
6311 should be used instead; MSG is the translated message and AP
6312 the arguments. Returns true if a diagnostic was emitted, false
6313 otherwise. */
6315 bool
6316 c_cpp_diagnostic (cpp_reader *pfile ATTRIBUTE_UNUSED,
6317 enum cpp_diagnostic_level level,
6318 enum cpp_warning_reason reason,
6319 rich_location *richloc,
6320 const char *msg, va_list *ap)
6322 diagnostic_info diagnostic;
6323 diagnostic_t dlevel;
6324 bool save_warn_system_headers = global_dc->dc_warn_system_headers;
6325 bool ret;
6327 switch (level)
6329 case CPP_DL_WARNING_SYSHDR:
6330 if (flag_no_output)
6331 return false;
6332 global_dc->dc_warn_system_headers = 1;
6333 /* Fall through. */
6334 case CPP_DL_WARNING:
6335 if (flag_no_output)
6336 return false;
6337 dlevel = DK_WARNING;
6338 break;
6339 case CPP_DL_PEDWARN:
6340 if (flag_no_output && !flag_pedantic_errors)
6341 return false;
6342 dlevel = DK_PEDWARN;
6343 break;
6344 case CPP_DL_ERROR:
6345 dlevel = DK_ERROR;
6346 break;
6347 case CPP_DL_ICE:
6348 dlevel = DK_ICE;
6349 break;
6350 case CPP_DL_NOTE:
6351 dlevel = DK_NOTE;
6352 break;
6353 case CPP_DL_FATAL:
6354 dlevel = DK_FATAL;
6355 break;
6356 default:
6357 gcc_unreachable ();
6359 if (done_lexing)
6360 richloc->set_range (0, input_location, SHOW_RANGE_WITH_CARET);
6361 diagnostic_set_info_translated (&diagnostic, msg, ap,
6362 richloc, dlevel);
6363 diagnostic_override_option_index
6364 (&diagnostic,
6365 c_option_controlling_cpp_diagnostic (reason));
6366 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6367 if (level == CPP_DL_WARNING_SYSHDR)
6368 global_dc->dc_warn_system_headers = save_warn_system_headers;
6369 return ret;
6372 /* Convert a character from the host to the target execution character
6373 set. cpplib handles this, mostly. */
6375 HOST_WIDE_INT
6376 c_common_to_target_charset (HOST_WIDE_INT c)
6378 /* Character constants in GCC proper are sign-extended under -fsigned-char,
6379 zero-extended under -fno-signed-char. cpplib insists that characters
6380 and character constants are always unsigned. Hence we must convert
6381 back and forth. */
6382 cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6384 uc = cpp_host_to_exec_charset (parse_in, uc);
6386 if (flag_signed_char)
6387 return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6388 >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6389 else
6390 return uc;
6393 /* Fold an offsetof-like expression. EXPR is a nested sequence of component
6394 references with an INDIRECT_REF of a constant at the bottom; much like the
6395 traditional rendering of offsetof as a macro. TYPE is the desired type of
6396 the whole expression. Return the folded result. */
6398 tree
6399 fold_offsetof (tree expr, tree type, enum tree_code ctx)
6401 tree base, off, t;
6402 tree_code code = TREE_CODE (expr);
6403 switch (code)
6405 case ERROR_MARK:
6406 return expr;
6408 case VAR_DECL:
6409 error ("cannot apply %<offsetof%> to static data member %qD", expr);
6410 return error_mark_node;
6412 case CALL_EXPR:
6413 case TARGET_EXPR:
6414 error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6415 return error_mark_node;
6417 case NOP_EXPR:
6418 case INDIRECT_REF:
6419 if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6421 error ("cannot apply %<offsetof%> to a non constant address");
6422 return error_mark_node;
6424 return convert (type, TREE_OPERAND (expr, 0));
6426 case COMPONENT_REF:
6427 base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6428 if (base == error_mark_node)
6429 return base;
6431 t = TREE_OPERAND (expr, 1);
6432 if (DECL_C_BIT_FIELD (t))
6434 error ("attempt to take address of bit-field structure "
6435 "member %qD", t);
6436 return error_mark_node;
6438 off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6439 size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6440 / BITS_PER_UNIT));
6441 break;
6443 case ARRAY_REF:
6444 base = fold_offsetof (TREE_OPERAND (expr, 0), type, code);
6445 if (base == error_mark_node)
6446 return base;
6448 t = TREE_OPERAND (expr, 1);
6449 STRIP_ANY_LOCATION_WRAPPER (t);
6451 /* Check if the offset goes beyond the upper bound of the array. */
6452 if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6454 tree upbound = array_ref_up_bound (expr);
6455 if (upbound != NULL_TREE
6456 && TREE_CODE (upbound) == INTEGER_CST
6457 && !tree_int_cst_equal (upbound,
6458 TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6460 if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6461 upbound = size_binop (PLUS_EXPR, upbound,
6462 build_int_cst (TREE_TYPE (upbound), 1));
6463 if (tree_int_cst_lt (upbound, t))
6465 tree v;
6467 for (v = TREE_OPERAND (expr, 0);
6468 TREE_CODE (v) == COMPONENT_REF;
6469 v = TREE_OPERAND (v, 0))
6470 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6471 == RECORD_TYPE)
6473 tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6474 for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6475 if (TREE_CODE (fld_chain) == FIELD_DECL)
6476 break;
6478 if (fld_chain)
6479 break;
6481 /* Don't warn if the array might be considered a poor
6482 man's flexible array member with a very permissive
6483 definition thereof. */
6484 if (TREE_CODE (v) == ARRAY_REF
6485 || TREE_CODE (v) == COMPONENT_REF)
6486 warning (OPT_Warray_bounds,
6487 "index %E denotes an offset "
6488 "greater than size of %qT",
6489 t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6494 t = convert (sizetype, t);
6495 off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6496 break;
6498 case COMPOUND_EXPR:
6499 /* Handle static members of volatile structs. */
6500 t = TREE_OPERAND (expr, 1);
6501 gcc_checking_assert (VAR_P (get_base_address (t)));
6502 return fold_offsetof (t, type);
6504 default:
6505 gcc_unreachable ();
6508 if (!POINTER_TYPE_P (type))
6509 return size_binop (PLUS_EXPR, base, convert (type, off));
6510 return fold_build_pointer_plus (base, off);
6513 /* *PTYPE is an incomplete array. Complete it with a domain based on
6514 INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6515 is true. Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6516 2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty. */
6519 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6521 tree maxindex, type, main_type, elt, unqual_elt;
6522 int failure = 0, quals;
6523 bool overflow_p = false;
6525 maxindex = size_zero_node;
6526 if (initial_value)
6528 STRIP_ANY_LOCATION_WRAPPER (initial_value);
6530 if (TREE_CODE (initial_value) == STRING_CST)
6532 int eltsize
6533 = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6534 maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6536 else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6538 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6540 if (vec_safe_is_empty (v))
6542 if (pedantic)
6543 failure = 3;
6544 maxindex = ssize_int (-1);
6546 else
6548 tree curindex;
6549 unsigned HOST_WIDE_INT cnt;
6550 constructor_elt *ce;
6551 bool fold_p = false;
6553 if ((*v)[0].index)
6554 maxindex = (*v)[0].index, fold_p = true;
6556 curindex = maxindex;
6558 for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
6560 bool curfold_p = false;
6561 if (ce->index)
6562 curindex = ce->index, curfold_p = true;
6563 else
6565 if (fold_p)
6567 /* Since we treat size types now as ordinary
6568 unsigned types, we need an explicit overflow
6569 check. */
6570 tree orig = curindex;
6571 curindex = fold_convert (sizetype, curindex);
6572 overflow_p |= tree_int_cst_lt (curindex, orig);
6574 curindex = size_binop (PLUS_EXPR, curindex,
6575 size_one_node);
6577 if (tree_int_cst_lt (maxindex, curindex))
6578 maxindex = curindex, fold_p = curfold_p;
6580 if (fold_p)
6582 tree orig = maxindex;
6583 maxindex = fold_convert (sizetype, maxindex);
6584 overflow_p |= tree_int_cst_lt (maxindex, orig);
6588 else
6590 /* Make an error message unless that happened already. */
6591 if (initial_value != error_mark_node)
6592 failure = 1;
6595 else
6597 failure = 2;
6598 if (!do_default)
6599 return failure;
6602 type = *ptype;
6603 elt = TREE_TYPE (type);
6604 quals = TYPE_QUALS (strip_array_types (elt));
6605 if (quals == 0)
6606 unqual_elt = elt;
6607 else
6608 unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
6610 /* Using build_distinct_type_copy and modifying things afterward instead
6611 of using build_array_type to create a new type preserves all of the
6612 TYPE_LANG_FLAG_? bits that the front end may have set. */
6613 main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
6614 TREE_TYPE (main_type) = unqual_elt;
6615 TYPE_DOMAIN (main_type)
6616 = build_range_type (TREE_TYPE (maxindex),
6617 build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
6618 TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
6619 layout_type (main_type);
6621 /* Make sure we have the canonical MAIN_TYPE. */
6622 hashval_t hashcode = type_hash_canon_hash (main_type);
6623 main_type = type_hash_canon (hashcode, main_type);
6625 /* Fix the canonical type. */
6626 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
6627 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
6628 SET_TYPE_STRUCTURAL_EQUALITY (main_type);
6629 else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
6630 || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
6631 != TYPE_DOMAIN (main_type)))
6632 TYPE_CANONICAL (main_type)
6633 = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
6634 TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
6635 TYPE_TYPELESS_STORAGE (main_type));
6636 else
6637 TYPE_CANONICAL (main_type) = main_type;
6639 if (quals == 0)
6640 type = main_type;
6641 else
6642 type = c_build_qualified_type (main_type, quals);
6644 if (COMPLETE_TYPE_P (type)
6645 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
6646 && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
6648 error ("size of array is too large");
6649 /* If we proceed with the array type as it is, we'll eventually
6650 crash in tree_to_[su]hwi(). */
6651 type = error_mark_node;
6654 *ptype = type;
6655 return failure;
6658 /* INIT is an constructor of a structure with a flexible array member.
6659 Complete the flexible array member with a domain based on it's value. */
6660 void
6661 complete_flexible_array_elts (tree init)
6663 tree elt, type;
6665 if (init == NULL_TREE || TREE_CODE (init) != CONSTRUCTOR)
6666 return;
6668 if (vec_safe_is_empty (CONSTRUCTOR_ELTS (init)))
6669 return;
6671 elt = CONSTRUCTOR_ELTS (init)->last ().value;
6672 type = TREE_TYPE (elt);
6673 if (TREE_CODE (type) == ARRAY_TYPE
6674 && TYPE_SIZE (type) == NULL_TREE)
6675 complete_array_type (&TREE_TYPE (elt), elt, false);
6676 else
6677 complete_flexible_array_elts (elt);
6680 /* Like c_mark_addressable but don't check register qualifier. */
6681 void
6682 c_common_mark_addressable_vec (tree t)
6684 if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
6685 t = C_MAYBE_CONST_EXPR_EXPR (t);
6686 while (handled_component_p (t))
6687 t = TREE_OPERAND (t, 0);
6688 if (!VAR_P (t)
6689 && TREE_CODE (t) != PARM_DECL
6690 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR)
6691 return;
6692 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
6693 TREE_ADDRESSABLE (t) = 1;
6694 if (TREE_CODE (t) == COMPOUND_LITERAL_EXPR)
6695 TREE_ADDRESSABLE (COMPOUND_LITERAL_EXPR_DECL (t)) = 1;
6700 /* Used to help initialize the builtin-types.def table. When a type of
6701 the correct size doesn't exist, use error_mark_node instead of NULL.
6702 The later results in segfaults even when a decl using the type doesn't
6703 get invoked. */
6705 tree
6706 builtin_type_for_size (int size, bool unsignedp)
6708 tree type = c_common_type_for_size (size, unsignedp);
6709 return type ? type : error_mark_node;
6712 /* Work out the size of the first argument of a call to
6713 __builtin_speculation_safe_value. Only pointers and integral types
6714 are permitted. Return -1 if the argument type is not supported or
6715 the size is too large; 0 if the argument type is a pointer or the
6716 size if it is integral. */
6717 static enum built_in_function
6718 speculation_safe_value_resolve_call (tree function, vec<tree, va_gc> *params)
6720 /* Type of the argument. */
6721 tree type;
6722 int size;
6724 if (vec_safe_is_empty (params))
6726 error ("too few arguments to function %qE", function);
6727 return BUILT_IN_NONE;
6730 type = TREE_TYPE ((*params)[0]);
6731 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6733 /* Force array-to-pointer decay for C++. */
6734 (*params)[0] = default_conversion ((*params)[0]);
6735 type = TREE_TYPE ((*params)[0]);
6738 if (POINTER_TYPE_P (type))
6739 return BUILT_IN_SPECULATION_SAFE_VALUE_PTR;
6741 if (!INTEGRAL_TYPE_P (type))
6742 goto incompatible;
6744 if (!COMPLETE_TYPE_P (type))
6745 goto incompatible;
6747 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
6748 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
6749 return ((enum built_in_function)
6750 ((int) BUILT_IN_SPECULATION_SAFE_VALUE_1 + exact_log2 (size)));
6752 incompatible:
6753 /* Issue the diagnostic only if the argument is valid, otherwise
6754 it would be redundant at best and could be misleading. */
6755 if (type != error_mark_node)
6756 error ("operand type %qT is incompatible with argument %d of %qE",
6757 type, 1, function);
6759 return BUILT_IN_NONE;
6762 /* Validate and coerce PARAMS, the arguments to ORIG_FUNCTION to fit
6763 the prototype for FUNCTION. The first argument is mandatory, a second
6764 argument, if present, must be type compatible with the first. */
6765 static bool
6766 speculation_safe_value_resolve_params (location_t loc, tree orig_function,
6767 vec<tree, va_gc> *params)
6769 tree val;
6771 if (params->length () == 0)
6773 error_at (loc, "too few arguments to function %qE", orig_function);
6774 return false;
6777 else if (params->length () > 2)
6779 error_at (loc, "too many arguments to function %qE", orig_function);
6780 return false;
6783 val = (*params)[0];
6784 if (TREE_CODE (TREE_TYPE (val)) == ARRAY_TYPE)
6785 val = default_conversion (val);
6786 if (!(TREE_CODE (TREE_TYPE (val)) == POINTER_TYPE
6787 || TREE_CODE (TREE_TYPE (val)) == INTEGER_TYPE))
6789 error_at (loc,
6790 "expecting argument of type pointer or of type integer "
6791 "for argument 1");
6792 return false;
6794 (*params)[0] = val;
6796 if (params->length () == 2)
6798 tree val2 = (*params)[1];
6799 if (TREE_CODE (TREE_TYPE (val2)) == ARRAY_TYPE)
6800 val2 = default_conversion (val2);
6801 if (error_operand_p (val2))
6802 return false;
6803 if (!(TREE_TYPE (val) == TREE_TYPE (val2)
6804 || useless_type_conversion_p (TREE_TYPE (val), TREE_TYPE (val2))))
6806 error_at (loc, "both arguments must be compatible");
6807 return false;
6809 (*params)[1] = val2;
6812 return true;
6815 /* Cast the result of the builtin back to the type of the first argument,
6816 preserving any qualifiers that it might have. */
6817 static tree
6818 speculation_safe_value_resolve_return (tree first_param, tree result)
6820 tree ptype = TREE_TYPE (first_param);
6821 tree rtype = TREE_TYPE (result);
6822 ptype = TYPE_MAIN_VARIANT (ptype);
6824 if (tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
6825 return convert (ptype, result);
6827 return result;
6830 /* A helper function for resolve_overloaded_builtin in resolving the
6831 overloaded __sync_ builtins. Returns a positive power of 2 if the
6832 first operand of PARAMS is a pointer to a supported data type.
6833 Returns 0 if an error is encountered.
6834 FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
6835 built-ins. */
6837 static int
6838 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch)
6840 /* Type of the argument. */
6841 tree argtype;
6842 /* Type the argument points to. */
6843 tree type;
6844 int size;
6846 if (vec_safe_is_empty (params))
6848 error ("too few arguments to function %qE", function);
6849 return 0;
6852 argtype = type = TREE_TYPE ((*params)[0]);
6853 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6855 /* Force array-to-pointer decay for C++. */
6856 (*params)[0] = default_conversion ((*params)[0]);
6857 type = TREE_TYPE ((*params)[0]);
6859 if (TREE_CODE (type) != POINTER_TYPE)
6860 goto incompatible;
6862 type = TREE_TYPE (type);
6863 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
6864 goto incompatible;
6866 if (!COMPLETE_TYPE_P (type))
6867 goto incompatible;
6869 if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
6870 goto incompatible;
6872 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
6873 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
6874 return size;
6876 incompatible:
6877 /* Issue the diagnostic only if the argument is valid, otherwise
6878 it would be redundant at best and could be misleading. */
6879 if (argtype != error_mark_node)
6880 error ("operand type %qT is incompatible with argument %d of %qE",
6881 argtype, 1, function);
6882 return 0;
6885 /* A helper function for resolve_overloaded_builtin. Adds casts to
6886 PARAMS to make arguments match up with those of FUNCTION. Drops
6887 the variadic arguments at the end. Returns false if some error
6888 was encountered; true on success. */
6890 static bool
6891 sync_resolve_params (location_t loc, tree orig_function, tree function,
6892 vec<tree, va_gc> *params, bool orig_format)
6894 function_args_iterator iter;
6895 tree ptype;
6896 unsigned int parmnum;
6898 function_args_iter_init (&iter, TREE_TYPE (function));
6899 /* We've declared the implementation functions to use "volatile void *"
6900 as the pointer parameter, so we shouldn't get any complaints from the
6901 call to check_function_arguments what ever type the user used. */
6902 function_args_iter_next (&iter);
6903 ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
6904 ptype = TYPE_MAIN_VARIANT (ptype);
6906 /* For the rest of the values, we need to cast these to FTYPE, so that we
6907 don't get warnings for passing pointer types, etc. */
6908 parmnum = 0;
6909 while (1)
6911 tree val, arg_type;
6913 arg_type = function_args_iter_cond (&iter);
6914 /* XXX void_type_node belies the abstraction. */
6915 if (arg_type == void_type_node)
6916 break;
6918 ++parmnum;
6919 if (params->length () <= parmnum)
6921 error_at (loc, "too few arguments to function %qE", orig_function);
6922 return false;
6925 /* Only convert parameters if arg_type is unsigned integer type with
6926 new format sync routines, i.e. don't attempt to convert pointer
6927 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
6928 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
6929 kinds). */
6930 if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
6932 /* Ideally for the first conversion we'd use convert_for_assignment
6933 so that we get warnings for anything that doesn't match the pointer
6934 type. This isn't portable across the C and C++ front ends atm. */
6935 val = (*params)[parmnum];
6936 val = convert (ptype, val);
6937 val = convert (arg_type, val);
6938 (*params)[parmnum] = val;
6941 function_args_iter_next (&iter);
6944 /* __atomic routines are not variadic. */
6945 if (!orig_format && params->length () != parmnum + 1)
6947 error_at (loc, "too many arguments to function %qE", orig_function);
6948 return false;
6951 /* The definition of these primitives is variadic, with the remaining
6952 being "an optional list of variables protected by the memory barrier".
6953 No clue what that's supposed to mean, precisely, but we consider all
6954 call-clobbered variables to be protected so we're safe. */
6955 params->truncate (parmnum + 1);
6957 return true;
6960 /* A helper function for resolve_overloaded_builtin. Adds a cast to
6961 RESULT to make it match the type of the first pointer argument in
6962 PARAMS. */
6964 static tree
6965 sync_resolve_return (tree first_param, tree result, bool orig_format)
6967 tree ptype = TREE_TYPE (TREE_TYPE (first_param));
6968 tree rtype = TREE_TYPE (result);
6969 ptype = TYPE_MAIN_VARIANT (ptype);
6971 /* New format doesn't require casting unless the types are the same size. */
6972 if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
6973 return convert (ptype, result);
6974 else
6975 return result;
6978 /* This function verifies the PARAMS to generic atomic FUNCTION.
6979 It returns the size if all the parameters are the same size, otherwise
6980 0 is returned if the parameters are invalid. */
6982 static int
6983 get_atomic_generic_size (location_t loc, tree function,
6984 vec<tree, va_gc> *params)
6986 unsigned int n_param;
6987 unsigned int n_model;
6988 unsigned int outputs = 0; // bitset of output parameters
6989 unsigned int x;
6990 int size_0;
6991 tree type_0;
6993 /* Determine the parameter makeup. */
6994 switch (DECL_FUNCTION_CODE (function))
6996 case BUILT_IN_ATOMIC_EXCHANGE:
6997 n_param = 4;
6998 n_model = 1;
6999 outputs = 5;
7000 break;
7001 case BUILT_IN_ATOMIC_LOAD:
7002 n_param = 3;
7003 n_model = 1;
7004 outputs = 2;
7005 break;
7006 case BUILT_IN_ATOMIC_STORE:
7007 n_param = 3;
7008 n_model = 1;
7009 outputs = 1;
7010 break;
7011 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7012 n_param = 6;
7013 n_model = 2;
7014 outputs = 3;
7015 break;
7016 default:
7017 gcc_unreachable ();
7020 if (vec_safe_length (params) != n_param)
7022 error_at (loc, "incorrect number of arguments to function %qE", function);
7023 return 0;
7026 /* Get type of first parameter, and determine its size. */
7027 type_0 = TREE_TYPE ((*params)[0]);
7028 if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
7030 /* Force array-to-pointer decay for C++. */
7031 (*params)[0] = default_conversion ((*params)[0]);
7032 type_0 = TREE_TYPE ((*params)[0]);
7034 if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
7036 error_at (loc, "argument 1 of %qE must be a non-void pointer type",
7037 function);
7038 return 0;
7041 if (!COMPLETE_TYPE_P (TREE_TYPE (type_0)))
7043 error_at (loc, "argument 1 of %qE must be a pointer to a complete type",
7044 function);
7045 return 0;
7048 /* Types must be compile time constant sizes. */
7049 if (!tree_fits_uhwi_p ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))))
7051 error_at (loc,
7052 "argument 1 of %qE must be a pointer to a constant size type",
7053 function);
7054 return 0;
7057 size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
7059 /* Zero size objects are not allowed. */
7060 if (size_0 == 0)
7062 error_at (loc,
7063 "argument 1 of %qE must be a pointer to a nonzero size object",
7064 function);
7065 return 0;
7068 /* Check each other parameter is a pointer and the same size. */
7069 for (x = 0; x < n_param - n_model; x++)
7071 int size;
7072 tree type = TREE_TYPE ((*params)[x]);
7073 /* __atomic_compare_exchange has a bool in the 4th position, skip it. */
7074 if (n_param == 6 && x == 3)
7075 continue;
7076 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
7078 /* Force array-to-pointer decay for C++. */
7079 (*params)[x] = default_conversion ((*params)[x]);
7080 type = TREE_TYPE ((*params)[x]);
7082 if (!POINTER_TYPE_P (type))
7084 error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
7085 function);
7086 return 0;
7088 else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
7089 && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
7090 != INTEGER_CST)
7092 error_at (loc, "argument %d of %qE must be a pointer to a constant "
7093 "size type", x + 1, function);
7094 return 0;
7096 else if (FUNCTION_POINTER_TYPE_P (type))
7098 error_at (loc, "argument %d of %qE must not be a pointer to a "
7099 "function", x + 1, function);
7100 return 0;
7102 tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
7103 size = type_size ? tree_to_uhwi (type_size) : 0;
7104 if (size != size_0)
7106 error_at (loc, "size mismatch in argument %d of %qE", x + 1,
7107 function);
7108 return 0;
7112 auto_diagnostic_group d;
7113 int quals = TYPE_QUALS (TREE_TYPE (type));
7114 /* Must not write to an argument of a const-qualified type. */
7115 if (outputs & (1 << x) && quals & TYPE_QUAL_CONST)
7117 if (c_dialect_cxx ())
7119 error_at (loc, "argument %d of %qE must not be a pointer to "
7120 "a %<const%> type", x + 1, function);
7121 return 0;
7123 else
7124 pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7125 "of %qE discards %<const%> qualifier", x + 1,
7126 function);
7128 /* Only the first argument is allowed to be volatile. */
7129 if (x > 0 && quals & TYPE_QUAL_VOLATILE)
7131 if (c_dialect_cxx ())
7133 error_at (loc, "argument %d of %qE must not be a pointer to "
7134 "a %<volatile%> type", x + 1, function);
7135 return 0;
7137 else
7138 pedwarn (loc, OPT_Wincompatible_pointer_types, "argument %d "
7139 "of %qE discards %<volatile%> qualifier", x + 1,
7140 function);
7145 /* Check memory model parameters for validity. */
7146 for (x = n_param - n_model ; x < n_param; x++)
7148 tree p = (*params)[x];
7149 if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
7151 error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
7152 function);
7153 return 0;
7155 p = fold_for_warn (p);
7156 if (TREE_CODE (p) == INTEGER_CST)
7158 /* memmodel_base masks the low 16 bits, thus ignore any bits above
7159 it by using TREE_INT_CST_LOW instead of tree_to_*hwi. Those high
7160 bits will be checked later during expansion in target specific
7161 way. */
7162 if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
7163 warning_at (loc, OPT_Winvalid_memory_model,
7164 "invalid memory model argument %d of %qE", x + 1,
7165 function);
7169 return size_0;
7173 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
7174 at the beginning of the parameter list PARAMS representing the size of the
7175 objects. This is to match the library ABI requirement. LOC is the location
7176 of the function call.
7177 The new function is returned if it needed rebuilding, otherwise NULL_TREE is
7178 returned to allow the external call to be constructed. */
7180 static tree
7181 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
7182 vec<tree, va_gc> *params)
7184 tree size_node;
7186 /* Insert a SIZE_T parameter as the first param. If there isn't
7187 enough space, allocate a new vector and recursively re-build with that. */
7188 if (!params->space (1))
7190 unsigned int z, len;
7191 vec<tree, va_gc> *v;
7192 tree f;
7194 len = params->length ();
7195 vec_alloc (v, len + 1);
7196 v->quick_push (build_int_cst (size_type_node, n));
7197 for (z = 0; z < len; z++)
7198 v->quick_push ((*params)[z]);
7199 f = build_function_call_vec (loc, vNULL, function, v, NULL);
7200 vec_free (v);
7201 return f;
7204 /* Add the size parameter and leave as a function call for processing. */
7205 size_node = build_int_cst (size_type_node, n);
7206 params->quick_insert (0, size_node);
7207 return NULL_TREE;
7211 /* Return whether atomic operations for naturally aligned N-byte
7212 arguments are supported, whether inline or through libatomic. */
7213 static bool
7214 atomic_size_supported_p (int n)
7216 switch (n)
7218 case 1:
7219 case 2:
7220 case 4:
7221 case 8:
7222 return true;
7224 case 16:
7225 return targetm.scalar_mode_supported_p (TImode);
7227 default:
7228 return false;
7232 /* This will process an __atomic_exchange function call, determine whether it
7233 needs to be mapped to the _N variation, or turned into a library call.
7234 LOC is the location of the builtin call.
7235 FUNCTION is the DECL that has been invoked;
7236 PARAMS is the argument list for the call. The return value is non-null
7237 TRUE is returned if it is translated into the proper format for a call to the
7238 external library, and NEW_RETURN is set the tree for that function.
7239 FALSE is returned if processing for the _N variation is required, and
7240 NEW_RETURN is set to the return value the result is copied into. */
7241 static bool
7242 resolve_overloaded_atomic_exchange (location_t loc, tree function,
7243 vec<tree, va_gc> *params, tree *new_return)
7245 tree p0, p1, p2, p3;
7246 tree I_type, I_type_ptr;
7247 int n = get_atomic_generic_size (loc, function, params);
7249 /* Size of 0 is an error condition. */
7250 if (n == 0)
7252 *new_return = error_mark_node;
7253 return true;
7256 /* If not a lock-free size, change to the library generic format. */
7257 if (!atomic_size_supported_p (n))
7259 *new_return = add_atomic_size_parameter (n, loc, function, params);
7260 return true;
7263 /* Otherwise there is a lockfree match, transform the call from:
7264 void fn(T* mem, T* desired, T* return, model)
7265 into
7266 *return = (T) (fn (In* mem, (In) *desired, model)) */
7268 p0 = (*params)[0];
7269 p1 = (*params)[1];
7270 p2 = (*params)[2];
7271 p3 = (*params)[3];
7273 /* Create pointer to appropriate size. */
7274 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7275 I_type_ptr = build_pointer_type (I_type);
7277 /* Convert object pointer to required type. */
7278 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7279 (*params)[0] = p0;
7280 /* Convert new value to required type, and dereference it. */
7281 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7282 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7283 (*params)[1] = p1;
7285 /* Move memory model to the 3rd position, and end param list. */
7286 (*params)[2] = p3;
7287 params->truncate (3);
7289 /* Convert return pointer and dereference it for later assignment. */
7290 *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7292 return false;
7296 /* This will process an __atomic_compare_exchange function call, determine
7297 whether it needs to be mapped to the _N variation, or turned into a lib call.
7298 LOC is the location of the builtin call.
7299 FUNCTION is the DECL that has been invoked;
7300 PARAMS is the argument list for the call. The return value is non-null
7301 TRUE is returned if it is translated into the proper format for a call to the
7302 external library, and NEW_RETURN is set the tree for that function.
7303 FALSE is returned if processing for the _N variation is required. */
7305 static bool
7306 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
7307 vec<tree, va_gc> *params,
7308 tree *new_return)
7310 tree p0, p1, p2;
7311 tree I_type, I_type_ptr;
7312 int n = get_atomic_generic_size (loc, function, params);
7314 /* Size of 0 is an error condition. */
7315 if (n == 0)
7317 *new_return = error_mark_node;
7318 return true;
7321 /* If not a lock-free size, change to the library generic format. */
7322 if (!atomic_size_supported_p (n))
7324 /* The library generic format does not have the weak parameter, so
7325 remove it from the param list. Since a parameter has been removed,
7326 we can be sure that there is room for the SIZE_T parameter, meaning
7327 there will not be a recursive rebuilding of the parameter list, so
7328 there is no danger this will be done twice. */
7329 if (n > 0)
7331 (*params)[3] = (*params)[4];
7332 (*params)[4] = (*params)[5];
7333 params->truncate (5);
7335 *new_return = add_atomic_size_parameter (n, loc, function, params);
7336 return true;
7339 /* Otherwise, there is a match, so the call needs to be transformed from:
7340 bool fn(T* mem, T* desired, T* return, weak, success, failure)
7341 into
7342 bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail) */
7344 p0 = (*params)[0];
7345 p1 = (*params)[1];
7346 p2 = (*params)[2];
7348 /* Create pointer to appropriate size. */
7349 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7350 I_type_ptr = build_pointer_type (I_type);
7352 /* Convert object pointer to required type. */
7353 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7354 (*params)[0] = p0;
7356 /* Convert expected pointer to required type. */
7357 p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
7358 (*params)[1] = p1;
7360 /* Convert desired value to required type, and dereference it. */
7361 p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
7362 p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
7363 (*params)[2] = p2;
7365 /* The rest of the parameters are fine. NULL means no special return value
7366 processing.*/
7367 *new_return = NULL;
7368 return false;
7372 /* This will process an __atomic_load function call, determine whether it
7373 needs to be mapped to the _N variation, or turned into a library call.
7374 LOC is the location of the builtin call.
7375 FUNCTION is the DECL that has been invoked;
7376 PARAMS is the argument list for the call. The return value is non-null
7377 TRUE is returned if it is translated into the proper format for a call to the
7378 external library, and NEW_RETURN is set the tree for that function.
7379 FALSE is returned if processing for the _N variation is required, and
7380 NEW_RETURN is set to the return value the result is copied into. */
7382 static bool
7383 resolve_overloaded_atomic_load (location_t loc, tree function,
7384 vec<tree, va_gc> *params, tree *new_return)
7386 tree p0, p1, p2;
7387 tree I_type, I_type_ptr;
7388 int n = get_atomic_generic_size (loc, function, params);
7390 /* Size of 0 is an error condition. */
7391 if (n == 0)
7393 *new_return = error_mark_node;
7394 return true;
7397 /* If not a lock-free size, change to the library generic format. */
7398 if (!atomic_size_supported_p (n))
7400 *new_return = add_atomic_size_parameter (n, loc, function, params);
7401 return true;
7404 /* Otherwise, there is a match, so the call needs to be transformed from:
7405 void fn(T* mem, T* return, model)
7406 into
7407 *return = (T) (fn ((In *) mem, model)) */
7409 p0 = (*params)[0];
7410 p1 = (*params)[1];
7411 p2 = (*params)[2];
7413 /* Create pointer to appropriate size. */
7414 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7415 I_type_ptr = build_pointer_type (I_type);
7417 /* Convert object pointer to required type. */
7418 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7419 (*params)[0] = p0;
7421 /* Move memory model to the 2nd position, and end param list. */
7422 (*params)[1] = p2;
7423 params->truncate (2);
7425 /* Convert return pointer and dereference it for later assignment. */
7426 *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7428 return false;
7432 /* This will process an __atomic_store function call, determine whether it
7433 needs to be mapped to the _N variation, or turned into a library call.
7434 LOC is the location of the builtin call.
7435 FUNCTION is the DECL that has been invoked;
7436 PARAMS is the argument list for the call. The return value is non-null
7437 TRUE is returned if it is translated into the proper format for a call to the
7438 external library, and NEW_RETURN is set the tree for that function.
7439 FALSE is returned if processing for the _N variation is required, and
7440 NEW_RETURN is set to the return value the result is copied into. */
7442 static bool
7443 resolve_overloaded_atomic_store (location_t loc, tree function,
7444 vec<tree, va_gc> *params, tree *new_return)
7446 tree p0, p1;
7447 tree I_type, I_type_ptr;
7448 int n = get_atomic_generic_size (loc, function, params);
7450 /* Size of 0 is an error condition. */
7451 if (n == 0)
7453 *new_return = error_mark_node;
7454 return true;
7457 /* If not a lock-free size, change to the library generic format. */
7458 if (!atomic_size_supported_p (n))
7460 *new_return = add_atomic_size_parameter (n, loc, function, params);
7461 return true;
7464 /* Otherwise, there is a match, so the call needs to be transformed from:
7465 void fn(T* mem, T* value, model)
7466 into
7467 fn ((In *) mem, (In) *value, model) */
7469 p0 = (*params)[0];
7470 p1 = (*params)[1];
7472 /* Create pointer to appropriate size. */
7473 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7474 I_type_ptr = build_pointer_type (I_type);
7476 /* Convert object pointer to required type. */
7477 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7478 (*params)[0] = p0;
7480 /* Convert new value to required type, and dereference it. */
7481 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7482 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7483 (*params)[1] = p1;
7485 /* The memory model is in the right spot already. Return is void. */
7486 *new_return = NULL_TREE;
7488 return false;
7492 /* Some builtin functions are placeholders for other expressions. This
7493 function should be called immediately after parsing the call expression
7494 before surrounding code has committed to the type of the expression.
7496 LOC is the location of the builtin call.
7498 FUNCTION is the DECL that has been invoked; it is known to be a builtin.
7499 PARAMS is the argument list for the call. The return value is non-null
7500 when expansion is complete, and null if normal processing should
7501 continue. */
7503 tree
7504 resolve_overloaded_builtin (location_t loc, tree function,
7505 vec<tree, va_gc> *params)
7507 /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
7508 Those are not valid to call with a pointer to _Bool (or C++ bool)
7509 and so must be rejected. */
7510 bool fetch_op = true;
7511 bool orig_format = true;
7512 tree new_return = NULL_TREE;
7514 switch (DECL_BUILT_IN_CLASS (function))
7516 case BUILT_IN_NORMAL:
7517 break;
7518 case BUILT_IN_MD:
7519 if (targetm.resolve_overloaded_builtin)
7520 return targetm.resolve_overloaded_builtin (loc, function, params);
7521 else
7522 return NULL_TREE;
7523 default:
7524 return NULL_TREE;
7527 /* Handle BUILT_IN_NORMAL here. */
7528 enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
7529 switch (orig_code)
7531 case BUILT_IN_SPECULATION_SAFE_VALUE_N:
7533 tree new_function, first_param, result;
7534 enum built_in_function fncode
7535 = speculation_safe_value_resolve_call (function, params);
7537 if (fncode == BUILT_IN_NONE)
7538 return error_mark_node;
7540 first_param = (*params)[0];
7541 if (!speculation_safe_value_resolve_params (loc, function, params))
7542 return error_mark_node;
7544 if (targetm.have_speculation_safe_value (true))
7546 new_function = builtin_decl_explicit (fncode);
7547 result = build_function_call_vec (loc, vNULL, new_function, params,
7548 NULL);
7550 if (result == error_mark_node)
7551 return result;
7553 return speculation_safe_value_resolve_return (first_param, result);
7555 else
7557 /* This target doesn't have, or doesn't need, active mitigation
7558 against incorrect speculative execution. Simply return the
7559 first parameter to the builtin. */
7560 if (!targetm.have_speculation_safe_value (false))
7561 /* The user has invoked __builtin_speculation_safe_value
7562 even though __HAVE_SPECULATION_SAFE_VALUE is not
7563 defined: emit a warning. */
7564 warning_at (input_location, 0,
7565 "this target does not define a speculation barrier; "
7566 "your program will still execute correctly, "
7567 "but incorrect speculation may not be "
7568 "restricted");
7570 /* If the optional second argument is present, handle any side
7571 effects now. */
7572 if (params->length () == 2
7573 && TREE_SIDE_EFFECTS ((*params)[1]))
7574 return build2 (COMPOUND_EXPR, TREE_TYPE (first_param),
7575 (*params)[1], first_param);
7577 return first_param;
7581 case BUILT_IN_ATOMIC_EXCHANGE:
7582 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7583 case BUILT_IN_ATOMIC_LOAD:
7584 case BUILT_IN_ATOMIC_STORE:
7586 /* Handle these 4 together so that they can fall through to the next
7587 case if the call is transformed to an _N variant. */
7588 switch (orig_code)
7590 case BUILT_IN_ATOMIC_EXCHANGE:
7592 if (resolve_overloaded_atomic_exchange (loc, function, params,
7593 &new_return))
7594 return new_return;
7595 /* Change to the _N variant. */
7596 orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
7597 break;
7600 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7602 if (resolve_overloaded_atomic_compare_exchange (loc, function,
7603 params,
7604 &new_return))
7605 return new_return;
7606 /* Change to the _N variant. */
7607 orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
7608 break;
7610 case BUILT_IN_ATOMIC_LOAD:
7612 if (resolve_overloaded_atomic_load (loc, function, params,
7613 &new_return))
7614 return new_return;
7615 /* Change to the _N variant. */
7616 orig_code = BUILT_IN_ATOMIC_LOAD_N;
7617 break;
7619 case BUILT_IN_ATOMIC_STORE:
7621 if (resolve_overloaded_atomic_store (loc, function, params,
7622 &new_return))
7623 return new_return;
7624 /* Change to the _N variant. */
7625 orig_code = BUILT_IN_ATOMIC_STORE_N;
7626 break;
7628 default:
7629 gcc_unreachable ();
7632 /* FALLTHRU */
7633 case BUILT_IN_ATOMIC_EXCHANGE_N:
7634 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
7635 case BUILT_IN_ATOMIC_LOAD_N:
7636 case BUILT_IN_ATOMIC_STORE_N:
7637 fetch_op = false;
7638 /* FALLTHRU */
7639 case BUILT_IN_ATOMIC_ADD_FETCH_N:
7640 case BUILT_IN_ATOMIC_SUB_FETCH_N:
7641 case BUILT_IN_ATOMIC_AND_FETCH_N:
7642 case BUILT_IN_ATOMIC_NAND_FETCH_N:
7643 case BUILT_IN_ATOMIC_XOR_FETCH_N:
7644 case BUILT_IN_ATOMIC_OR_FETCH_N:
7645 case BUILT_IN_ATOMIC_FETCH_ADD_N:
7646 case BUILT_IN_ATOMIC_FETCH_SUB_N:
7647 case BUILT_IN_ATOMIC_FETCH_AND_N:
7648 case BUILT_IN_ATOMIC_FETCH_NAND_N:
7649 case BUILT_IN_ATOMIC_FETCH_XOR_N:
7650 case BUILT_IN_ATOMIC_FETCH_OR_N:
7651 orig_format = false;
7652 /* FALLTHRU */
7653 case BUILT_IN_SYNC_FETCH_AND_ADD_N:
7654 case BUILT_IN_SYNC_FETCH_AND_SUB_N:
7655 case BUILT_IN_SYNC_FETCH_AND_OR_N:
7656 case BUILT_IN_SYNC_FETCH_AND_AND_N:
7657 case BUILT_IN_SYNC_FETCH_AND_XOR_N:
7658 case BUILT_IN_SYNC_FETCH_AND_NAND_N:
7659 case BUILT_IN_SYNC_ADD_AND_FETCH_N:
7660 case BUILT_IN_SYNC_SUB_AND_FETCH_N:
7661 case BUILT_IN_SYNC_OR_AND_FETCH_N:
7662 case BUILT_IN_SYNC_AND_AND_FETCH_N:
7663 case BUILT_IN_SYNC_XOR_AND_FETCH_N:
7664 case BUILT_IN_SYNC_NAND_AND_FETCH_N:
7665 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
7666 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
7667 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
7668 case BUILT_IN_SYNC_LOCK_RELEASE_N:
7670 /* The following are not _FETCH_OPs and must be accepted with
7671 pointers to _Bool (or C++ bool). */
7672 if (fetch_op)
7673 fetch_op =
7674 (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7675 && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
7676 && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
7677 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
7679 int n = sync_resolve_size (function, params, fetch_op);
7680 tree new_function, first_param, result;
7681 enum built_in_function fncode;
7683 if (n == 0)
7684 return error_mark_node;
7686 fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
7687 new_function = builtin_decl_explicit (fncode);
7688 if (!sync_resolve_params (loc, function, new_function, params,
7689 orig_format))
7690 return error_mark_node;
7692 first_param = (*params)[0];
7693 result = build_function_call_vec (loc, vNULL, new_function, params,
7694 NULL);
7695 if (result == error_mark_node)
7696 return result;
7697 if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7698 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
7699 && orig_code != BUILT_IN_ATOMIC_STORE_N
7700 && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
7701 result = sync_resolve_return (first_param, result, orig_format);
7703 if (fetch_op)
7704 /* Prevent -Wunused-value warning. */
7705 TREE_USED (result) = true;
7707 /* If new_return is set, assign function to that expr and cast the
7708 result to void since the generic interface returned void. */
7709 if (new_return)
7711 /* Cast function result from I{1,2,4,8,16} to the required type. */
7712 result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
7713 result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
7714 result);
7715 TREE_SIDE_EFFECTS (result) = 1;
7716 protected_set_expr_location (result, loc);
7717 result = convert (void_type_node, result);
7719 return result;
7722 default:
7723 return NULL_TREE;
7727 /* vector_types_compatible_elements_p is used in type checks of vectors
7728 values used as operands of binary operators. Where it returns true, and
7729 the other checks of the caller succeed (being vector types in he first
7730 place, and matching number of elements), we can just treat the types
7731 as essentially the same.
7732 Contrast with vector_targets_convertible_p, which is used for vector
7733 pointer types, and vector_types_convertible_p, which will allow
7734 language-specific matches under the control of flag_lax_vector_conversions,
7735 and might still require a conversion. */
7736 /* True if vector types T1 and T2 can be inputs to the same binary
7737 operator without conversion.
7738 We don't check the overall vector size here because some of our callers
7739 want to give different error messages when the vectors are compatible
7740 except for the element count. */
7742 bool
7743 vector_types_compatible_elements_p (tree t1, tree t2)
7745 bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
7746 t1 = TREE_TYPE (t1);
7747 t2 = TREE_TYPE (t2);
7749 enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
7751 gcc_assert ((INTEGRAL_TYPE_P (t1)
7752 || c1 == REAL_TYPE
7753 || c1 == FIXED_POINT_TYPE)
7754 && (INTEGRAL_TYPE_P (t2)
7755 || c2 == REAL_TYPE
7756 || c2 == FIXED_POINT_TYPE));
7758 t1 = c_common_signed_type (t1);
7759 t2 = c_common_signed_type (t2);
7760 /* Equality works here because c_common_signed_type uses
7761 TYPE_MAIN_VARIANT. */
7762 if (t1 == t2)
7763 return true;
7764 if (opaque && c1 == c2
7765 && (INTEGRAL_TYPE_P (t1) || c1 == REAL_TYPE)
7766 && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
7767 return true;
7768 return false;
7771 /* Check for missing format attributes on function pointers. LTYPE is
7772 the new type or left-hand side type. RTYPE is the old type or
7773 right-hand side type. Returns TRUE if LTYPE is missing the desired
7774 attribute. */
7776 bool
7777 check_missing_format_attribute (tree ltype, tree rtype)
7779 tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
7780 tree ra;
7782 for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
7783 if (is_attribute_p ("format", get_attribute_name (ra)))
7784 break;
7785 if (ra)
7787 tree la;
7788 for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
7789 if (is_attribute_p ("format", get_attribute_name (la)))
7790 break;
7791 return !la;
7793 else
7794 return false;
7797 /* Setup a TYPE_DECL node as a typedef representation.
7799 X is a TYPE_DECL for a typedef statement. Create a brand new
7800 ..._TYPE node (which will be just a variant of the existing
7801 ..._TYPE node with identical properties) and then install X
7802 as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
7804 The whole point here is to end up with a situation where each
7805 and every ..._TYPE node the compiler creates will be uniquely
7806 associated with AT MOST one node representing a typedef name.
7807 This way, even though the compiler substitutes corresponding
7808 ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
7809 early on, later parts of the compiler can always do the reverse
7810 translation and get back the corresponding typedef name. For
7811 example, given:
7813 typedef struct S MY_TYPE;
7814 MY_TYPE object;
7816 Later parts of the compiler might only know that `object' was of
7817 type `struct S' if it were not for code just below. With this
7818 code however, later parts of the compiler see something like:
7820 struct S' == struct S
7821 typedef struct S' MY_TYPE;
7822 struct S' object;
7824 And they can then deduce (from the node for type struct S') that
7825 the original object declaration was:
7827 MY_TYPE object;
7829 Being able to do this is important for proper support of protoize,
7830 and also for generating precise symbolic debugging information
7831 which takes full account of the programmer's (typedef) vocabulary.
7833 Obviously, we don't want to generate a duplicate ..._TYPE node if
7834 the TYPE_DECL node that we are now processing really represents a
7835 standard built-in type. */
7837 void
7838 set_underlying_type (tree x)
7840 if (x == error_mark_node)
7841 return;
7842 if (DECL_IS_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
7844 if (TYPE_NAME (TREE_TYPE (x)) == 0)
7845 TYPE_NAME (TREE_TYPE (x)) = x;
7847 else if (TREE_TYPE (x) != error_mark_node
7848 && DECL_ORIGINAL_TYPE (x) == NULL_TREE)
7850 tree tt = TREE_TYPE (x);
7851 DECL_ORIGINAL_TYPE (x) = tt;
7852 tt = build_variant_type_copy (tt);
7853 TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
7854 TYPE_NAME (tt) = x;
7856 /* Mark the type as used only when its type decl is decorated
7857 with attribute unused. */
7858 if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
7859 TREE_USED (tt) = 1;
7861 TREE_TYPE (x) = tt;
7865 /* Return true if it is worth exposing the DECL_ORIGINAL_TYPE of TYPE to
7866 the user in diagnostics, false if it would be better to use TYPE itself.
7867 TYPE is known to satisfy typedef_variant_p. */
7869 bool
7870 user_facing_original_type_p (const_tree type)
7872 gcc_assert (typedef_variant_p (type));
7873 tree decl = TYPE_NAME (type);
7875 /* Look through any typedef in "user" code. */
7876 if (!DECL_IN_SYSTEM_HEADER (decl) && !DECL_IS_BUILTIN (decl))
7877 return true;
7879 /* If the original type is also named and is in the user namespace,
7880 assume it too is a user-facing type. */
7881 tree orig_type = DECL_ORIGINAL_TYPE (decl);
7882 if (tree orig_id = TYPE_IDENTIFIER (orig_type))
7883 if (!name_reserved_for_implementation_p (IDENTIFIER_POINTER (orig_id)))
7884 return true;
7886 switch (TREE_CODE (orig_type))
7888 /* Don't look through to an anonymous vector type, since the syntax
7889 we use for them in diagnostics isn't real C or C++ syntax.
7890 And if ORIG_TYPE is named but in the implementation namespace,
7891 TYPE is likely to be more meaningful to the user. */
7892 case VECTOR_TYPE:
7893 return false;
7895 /* Don't expose anonymous tag types that are presumably meant to be
7896 known by their typedef name. Also don't expose tags that are in
7897 the implementation namespace, such as:
7899 typedef struct __foo foo; */
7900 case RECORD_TYPE:
7901 case UNION_TYPE:
7902 case ENUMERAL_TYPE:
7903 return false;
7905 /* Look through to anything else. */
7906 default:
7907 return true;
7911 /* Record the types used by the current global variable declaration
7912 being parsed, so that we can decide later to emit their debug info.
7913 Those types are in types_used_by_cur_var_decl, and we are going to
7914 store them in the types_used_by_vars_hash hash table.
7915 DECL is the declaration of the global variable that has been parsed. */
7917 void
7918 record_types_used_by_current_var_decl (tree decl)
7920 gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
7922 while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
7924 tree type = types_used_by_cur_var_decl->pop ();
7925 types_used_by_var_decl_insert (type, decl);
7929 /* The C and C++ parsers both use vectors to hold function arguments.
7930 For efficiency, we keep a cache of unused vectors. This is the
7931 cache. */
7933 typedef vec<tree, va_gc> *tree_gc_vec;
7934 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
7936 /* Return a new vector from the cache. If the cache is empty,
7937 allocate a new vector. These vectors are GC'ed, so it is OK if the
7938 pointer is not released.. */
7940 vec<tree, va_gc> *
7941 make_tree_vector (void)
7943 if (tree_vector_cache && !tree_vector_cache->is_empty ())
7944 return tree_vector_cache->pop ();
7945 else
7947 /* Passing 0 to vec::alloc returns NULL, and our callers require
7948 that we always return a non-NULL value. The vector code uses
7949 4 when growing a NULL vector, so we do too. */
7950 vec<tree, va_gc> *v;
7951 vec_alloc (v, 4);
7952 return v;
7956 /* Release a vector of trees back to the cache. */
7958 void
7959 release_tree_vector (vec<tree, va_gc> *vec)
7961 if (vec != NULL)
7963 vec->truncate (0);
7964 vec_safe_push (tree_vector_cache, vec);
7968 /* Get a new tree vector holding a single tree. */
7970 vec<tree, va_gc> *
7971 make_tree_vector_single (tree t)
7973 vec<tree, va_gc> *ret = make_tree_vector ();
7974 ret->quick_push (t);
7975 return ret;
7978 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain. */
7980 vec<tree, va_gc> *
7981 make_tree_vector_from_list (tree list)
7983 vec<tree, va_gc> *ret = make_tree_vector ();
7984 for (; list; list = TREE_CHAIN (list))
7985 vec_safe_push (ret, TREE_VALUE (list));
7986 return ret;
7989 /* Get a new tree vector of the values of a CONSTRUCTOR. */
7991 vec<tree, va_gc> *
7992 make_tree_vector_from_ctor (tree ctor)
7994 vec<tree,va_gc> *ret = make_tree_vector ();
7995 vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
7996 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
7997 ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
7998 return ret;
8001 /* Get a new tree vector which is a copy of an existing one. */
8003 vec<tree, va_gc> *
8004 make_tree_vector_copy (const vec<tree, va_gc> *orig)
8006 vec<tree, va_gc> *ret;
8007 unsigned int ix;
8008 tree t;
8010 ret = make_tree_vector ();
8011 vec_safe_reserve (ret, vec_safe_length (orig));
8012 FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
8013 ret->quick_push (t);
8014 return ret;
8017 /* Return true if KEYWORD starts a type specifier. */
8019 bool
8020 keyword_begins_type_specifier (enum rid keyword)
8022 switch (keyword)
8024 case RID_AUTO_TYPE:
8025 case RID_INT:
8026 case RID_CHAR:
8027 case RID_FLOAT:
8028 case RID_DOUBLE:
8029 case RID_VOID:
8030 case RID_UNSIGNED:
8031 case RID_LONG:
8032 case RID_SHORT:
8033 case RID_SIGNED:
8034 CASE_RID_FLOATN_NX:
8035 case RID_DFLOAT32:
8036 case RID_DFLOAT64:
8037 case RID_DFLOAT128:
8038 case RID_FRACT:
8039 case RID_ACCUM:
8040 case RID_BOOL:
8041 case RID_WCHAR:
8042 case RID_CHAR8:
8043 case RID_CHAR16:
8044 case RID_CHAR32:
8045 case RID_SAT:
8046 case RID_COMPLEX:
8047 case RID_TYPEOF:
8048 case RID_STRUCT:
8049 case RID_CLASS:
8050 case RID_UNION:
8051 case RID_ENUM:
8052 return true;
8053 default:
8054 if (keyword >= RID_FIRST_INT_N
8055 && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
8056 && int_n_enabled_p[keyword-RID_FIRST_INT_N])
8057 return true;
8058 return false;
8062 /* Return true if KEYWORD names a type qualifier. */
8064 bool
8065 keyword_is_type_qualifier (enum rid keyword)
8067 switch (keyword)
8069 case RID_CONST:
8070 case RID_VOLATILE:
8071 case RID_RESTRICT:
8072 case RID_ATOMIC:
8073 return true;
8074 default:
8075 return false;
8079 /* Return true if KEYWORD names a storage class specifier.
8081 RID_TYPEDEF is not included in this list despite `typedef' being
8082 listed in C99 6.7.1.1. 6.7.1.3 indicates that `typedef' is listed as
8083 such for syntactic convenience only. */
8085 bool
8086 keyword_is_storage_class_specifier (enum rid keyword)
8088 switch (keyword)
8090 case RID_STATIC:
8091 case RID_EXTERN:
8092 case RID_REGISTER:
8093 case RID_AUTO:
8094 case RID_MUTABLE:
8095 case RID_THREAD:
8096 return true;
8097 default:
8098 return false;
8102 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec]. */
8104 static bool
8105 keyword_is_function_specifier (enum rid keyword)
8107 switch (keyword)
8109 case RID_INLINE:
8110 case RID_NORETURN:
8111 case RID_VIRTUAL:
8112 case RID_EXPLICIT:
8113 return true;
8114 default:
8115 return false;
8119 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
8120 declaration-specifier (C99 6.7). */
8122 bool
8123 keyword_is_decl_specifier (enum rid keyword)
8125 if (keyword_is_storage_class_specifier (keyword)
8126 || keyword_is_type_qualifier (keyword)
8127 || keyword_is_function_specifier (keyword))
8128 return true;
8130 switch (keyword)
8132 case RID_TYPEDEF:
8133 case RID_FRIEND:
8134 case RID_CONSTEXPR:
8135 case RID_CONSTINIT:
8136 return true;
8137 default:
8138 return false;
8142 /* Initialize language-specific-bits of tree_contains_struct. */
8144 void
8145 c_common_init_ts (void)
8147 MARK_TS_EXP (SIZEOF_EXPR);
8148 MARK_TS_EXP (PAREN_SIZEOF_EXPR);
8149 MARK_TS_EXP (C_MAYBE_CONST_EXPR);
8150 MARK_TS_EXP (EXCESS_PRECISION_EXPR);
8151 MARK_TS_EXP (BREAK_STMT);
8152 MARK_TS_EXP (CONTINUE_STMT);
8153 MARK_TS_EXP (DO_STMT);
8154 MARK_TS_EXP (FOR_STMT);
8155 MARK_TS_EXP (SWITCH_STMT);
8156 MARK_TS_EXP (WHILE_STMT);
8159 /* Build a user-defined numeric literal out of an integer constant type VALUE
8160 with identifier SUFFIX. */
8162 tree
8163 build_userdef_literal (tree suffix_id, tree value,
8164 enum overflow_type overflow, tree num_string)
8166 tree literal = make_node (USERDEF_LITERAL);
8167 USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
8168 USERDEF_LITERAL_VALUE (literal) = value;
8169 USERDEF_LITERAL_OVERFLOW (literal) = overflow;
8170 USERDEF_LITERAL_NUM_STRING (literal) = num_string;
8171 return literal;
8174 /* For vector[index], convert the vector to an array of the underlying type.
8175 Return true if the resulting ARRAY_REF should not be an lvalue. */
8177 bool
8178 convert_vector_to_array_for_subscript (location_t loc,
8179 tree *vecp, tree index)
8181 bool ret = false;
8182 if (gnu_vector_type_p (TREE_TYPE (*vecp)))
8184 tree type = TREE_TYPE (*vecp);
8186 ret = !lvalue_p (*vecp);
8188 index = fold_for_warn (index);
8189 if (TREE_CODE (index) == INTEGER_CST)
8190 if (!tree_fits_uhwi_p (index)
8191 || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
8192 warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
8194 /* We are building an ARRAY_REF so mark the vector as addressable
8195 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
8196 for function parameters. */
8197 c_common_mark_addressable_vec (*vecp);
8199 *vecp = build1 (VIEW_CONVERT_EXPR,
8200 build_array_type_nelts (TREE_TYPE (type),
8201 TYPE_VECTOR_SUBPARTS (type)),
8202 *vecp);
8204 return ret;
8207 /* Determine which of the operands, if any, is a scalar that needs to be
8208 converted to a vector, for the range of operations. */
8209 enum stv_conv
8210 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
8211 bool complain)
8213 tree type0 = TREE_TYPE (op0);
8214 tree type1 = TREE_TYPE (op1);
8215 bool integer_only_op = false;
8216 enum stv_conv ret = stv_firstarg;
8218 gcc_assert (gnu_vector_type_p (type0) || gnu_vector_type_p (type1));
8219 switch (code)
8221 /* Most GENERIC binary expressions require homogeneous arguments.
8222 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
8223 argument that is a vector and a second one that is a scalar, so
8224 we never return stv_secondarg for them. */
8225 case RSHIFT_EXPR:
8226 case LSHIFT_EXPR:
8227 if (TREE_CODE (type0) == INTEGER_TYPE
8228 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8230 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8231 NULL_TREE, false))
8233 if (complain)
8234 error_at (loc, "conversion of scalar %qT to vector %qT "
8235 "involves truncation", type0, type1);
8236 return stv_error;
8238 else
8239 return stv_firstarg;
8241 break;
8243 case BIT_IOR_EXPR:
8244 case BIT_XOR_EXPR:
8245 case BIT_AND_EXPR:
8246 integer_only_op = true;
8247 /* fall through */
8249 case VEC_COND_EXPR:
8251 case PLUS_EXPR:
8252 case MINUS_EXPR:
8253 case MULT_EXPR:
8254 case TRUNC_DIV_EXPR:
8255 case CEIL_DIV_EXPR:
8256 case FLOOR_DIV_EXPR:
8257 case ROUND_DIV_EXPR:
8258 case EXACT_DIV_EXPR:
8259 case TRUNC_MOD_EXPR:
8260 case FLOOR_MOD_EXPR:
8261 case RDIV_EXPR:
8262 case EQ_EXPR:
8263 case NE_EXPR:
8264 case LE_EXPR:
8265 case GE_EXPR:
8266 case LT_EXPR:
8267 case GT_EXPR:
8268 /* What about UNLT_EXPR? */
8269 if (gnu_vector_type_p (type0))
8271 ret = stv_secondarg;
8272 std::swap (type0, type1);
8273 std::swap (op0, op1);
8276 if (TREE_CODE (type0) == INTEGER_TYPE
8277 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
8279 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8280 NULL_TREE, false))
8282 if (complain)
8283 error_at (loc, "conversion of scalar %qT to vector %qT "
8284 "involves truncation", type0, type1);
8285 return stv_error;
8287 return ret;
8289 else if (!integer_only_op
8290 /* Allow integer --> real conversion if safe. */
8291 && (TREE_CODE (type0) == REAL_TYPE
8292 || TREE_CODE (type0) == INTEGER_TYPE)
8293 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
8295 if (unsafe_conversion_p (TREE_TYPE (type1), op0,
8296 NULL_TREE, false))
8298 if (complain)
8299 error_at (loc, "conversion of scalar %qT to vector %qT "
8300 "involves truncation", type0, type1);
8301 return stv_error;
8303 return ret;
8305 default:
8306 break;
8309 return stv_nothing;
8312 /* Return the alignment of std::max_align_t.
8314 [support.types.layout] The type max_align_t is a POD type whose alignment
8315 requirement is at least as great as that of every scalar type, and whose
8316 alignment requirement is supported in every context. */
8318 unsigned
8319 max_align_t_align ()
8321 unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
8322 TYPE_ALIGN (long_double_type_node));
8323 if (float128_type_node != NULL_TREE)
8324 max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
8325 return max_align;
8328 /* Return true iff ALIGN is an integral constant that is a fundamental
8329 alignment, as defined by [basic.align] in the c++-11
8330 specifications.
8332 That is:
8334 [A fundamental alignment is represented by an alignment less than or
8335 equal to the greatest alignment supported by the implementation
8336 in all contexts, which is equal to alignof(max_align_t)]. */
8338 bool
8339 cxx_fundamental_alignment_p (unsigned align)
8341 return (align <= max_align_t_align ());
8344 /* Return true if T is a pointer to a zero-sized aggregate. */
8346 bool
8347 pointer_to_zero_sized_aggr_p (tree t)
8349 if (!POINTER_TYPE_P (t))
8350 return false;
8351 t = TREE_TYPE (t);
8352 return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
8355 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
8356 with no library fallback or for an ADDR_EXPR whose operand is such type
8357 issues an error pointing to the location LOC.
8358 Returns true when the expression has been diagnosed and false
8359 otherwise. */
8361 bool
8362 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
8364 if (TREE_CODE (expr) == ADDR_EXPR)
8365 expr = TREE_OPERAND (expr, 0);
8367 STRIP_ANY_LOCATION_WRAPPER (expr);
8369 if (TREE_TYPE (expr)
8370 && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
8371 && TREE_CODE (expr) == FUNCTION_DECL
8372 /* The intersection of DECL_BUILT_IN and DECL_IS_BUILTIN avoids
8373 false positives for user-declared built-ins such as abs or
8374 strlen, and for C++ operators new and delete.
8375 The c_decl_implicit() test avoids false positives for implicitly
8376 declared built-ins with library fallbacks (such as abs). */
8377 && fndecl_built_in_p (expr)
8378 && DECL_IS_BUILTIN (expr)
8379 && !c_decl_implicit (expr)
8380 && !DECL_ASSEMBLER_NAME_SET_P (expr))
8382 if (loc == UNKNOWN_LOCATION)
8383 loc = EXPR_LOC_OR_LOC (expr, input_location);
8385 /* Reject arguments that are built-in functions with
8386 no library fallback. */
8387 error_at (loc, "built-in function %qE must be directly called", expr);
8389 return true;
8392 return false;
8395 /* Issue an ERROR for an invalid SIZE of array NAME which is null
8396 for unnamed arrays. */
8398 void
8399 invalid_array_size_error (location_t loc, cst_size_error error,
8400 const_tree size, const_tree name)
8402 tree maxsize = max_object_size ();
8403 switch (error)
8405 case cst_size_not_constant:
8406 if (name)
8407 error_at (loc, "size of array %qE is not a constant expression",
8408 name);
8409 else
8410 error_at (loc, "size of array is not a constant expression");
8411 break;
8412 case cst_size_negative:
8413 if (name)
8414 error_at (loc, "size %qE of array %qE is negative",
8415 size, name);
8416 else
8417 error_at (loc, "size %qE of array is negative",
8418 size);
8419 break;
8420 case cst_size_too_big:
8421 if (name)
8422 error_at (loc, "size %qE of array %qE exceeds maximum "
8423 "object size %qE", size, name, maxsize);
8424 else
8425 error_at (loc, "size %qE of array exceeds maximum "
8426 "object size %qE", size, maxsize);
8427 break;
8428 case cst_size_overflow:
8429 if (name)
8430 error_at (loc, "size of array %qE exceeds maximum "
8431 "object size %qE", name, maxsize);
8432 else
8433 error_at (loc, "size of array exceeds maximum "
8434 "object size %qE", maxsize);
8435 break;
8436 default:
8437 gcc_unreachable ();
8441 /* Check if array size calculations overflow or if the array covers more
8442 than half of the address space. Return true if the size of the array
8443 is valid, false otherwise. T is either the type of the array or its
8444 size, and NAME is the name of the array, or null for unnamed arrays. */
8446 bool
8447 valid_array_size_p (location_t loc, const_tree t, tree name, bool complain)
8449 if (t == error_mark_node)
8450 return true;
8452 const_tree size;
8453 if (TYPE_P (t))
8455 if (!COMPLETE_TYPE_P (t))
8456 return true;
8457 size = TYPE_SIZE_UNIT (t);
8459 else
8460 size = t;
8462 if (TREE_CODE (size) != INTEGER_CST)
8463 return true;
8465 cst_size_error error;
8466 if (valid_constant_size_p (size, &error))
8467 return true;
8469 if (!complain)
8470 return false;
8472 if (TREE_CODE (TREE_TYPE (size)) == ENUMERAL_TYPE)
8473 /* Show the value of the enumerator rather than its name. */
8474 size = convert (ssizetype, const_cast<tree> (size));
8476 invalid_array_size_error (loc, error, size, name);
8477 return false;
8480 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
8481 timestamp to replace embedded current dates to get reproducible
8482 results. Returns -1 if SOURCE_DATE_EPOCH is not defined. */
8484 time_t
8485 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
8487 char *source_date_epoch;
8488 int64_t epoch;
8489 char *endptr;
8491 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
8492 if (!source_date_epoch)
8493 return (time_t) -1;
8495 errno = 0;
8496 #if defined(INT64_T_IS_LONG)
8497 epoch = strtol (source_date_epoch, &endptr, 10);
8498 #else
8499 epoch = strtoll (source_date_epoch, &endptr, 10);
8500 #endif
8501 if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
8502 || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
8504 error_at (input_location, "environment variable %qs must "
8505 "expand to a non-negative integer less than or equal to %wd",
8506 "SOURCE_DATE_EPOCH", MAX_SOURCE_DATE_EPOCH);
8507 return (time_t) -1;
8510 return (time_t) epoch;
8513 /* Callback for libcpp for offering spelling suggestions for misspelled
8514 directives. GOAL is an unrecognized string; CANDIDATES is a
8515 NULL-terminated array of candidate strings. Return the closest
8516 match to GOAL within CANDIDATES, or NULL if none are good
8517 suggestions. */
8519 const char *
8520 cb_get_suggestion (cpp_reader *, const char *goal,
8521 const char *const *candidates)
8523 best_match<const char *, const char *> bm (goal);
8524 while (*candidates)
8525 bm.consider (*candidates++);
8526 return bm.get_best_meaningful_candidate ();
8529 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
8530 modes X, Y. This isn't just >, as the FLT_EVAL_METHOD values added
8531 by C TS 18661-3 for interchange types that are computed in their
8532 native precision are larger than the C11 values for evaluating in the
8533 precision of float/double/long double. If either mode is
8534 FLT_EVAL_METHOD_UNPREDICTABLE, return that. */
8536 enum flt_eval_method
8537 excess_precision_mode_join (enum flt_eval_method x,
8538 enum flt_eval_method y)
8540 if (x == FLT_EVAL_METHOD_UNPREDICTABLE
8541 || y == FLT_EVAL_METHOD_UNPREDICTABLE)
8542 return FLT_EVAL_METHOD_UNPREDICTABLE;
8544 /* GCC only supports one interchange type right now, _Float16. If
8545 we're evaluating _Float16 in 16-bit precision, then flt_eval_method
8546 will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
8547 if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
8548 return y;
8549 if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
8550 return x;
8552 /* Other values for flt_eval_method are directly comparable, and we want
8553 the maximum. */
8554 return MAX (x, y);
8557 /* Return the value that should be set for FLT_EVAL_METHOD in the
8558 context of ISO/IEC TS 18861-3.
8560 This relates to the effective excess precision seen by the user,
8561 which is the join point of the precision the target requests for
8562 -fexcess-precision={standard,fast} and the implicit excess precision
8563 the target uses. */
8565 static enum flt_eval_method
8566 c_ts18661_flt_eval_method (void)
8568 enum flt_eval_method implicit
8569 = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
8571 enum excess_precision_type flag_type
8572 = (flag_excess_precision == EXCESS_PRECISION_STANDARD
8573 ? EXCESS_PRECISION_TYPE_STANDARD
8574 : EXCESS_PRECISION_TYPE_FAST);
8576 enum flt_eval_method requested
8577 = targetm.c.excess_precision (flag_type);
8579 return excess_precision_mode_join (implicit, requested);
8582 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
8583 those that were permitted by C11. That is to say, eliminates
8584 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
8586 static enum flt_eval_method
8587 c_c11_flt_eval_method (void)
8589 return excess_precision_mode_join (c_ts18661_flt_eval_method (),
8590 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
8593 /* Return the value that should be set for FLT_EVAL_METHOD.
8594 MAYBE_C11_ONLY_P is TRUE if we should check
8595 FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
8596 values we can return to those from C99/C11, and FALSE otherwise.
8597 See the comments on c_ts18661_flt_eval_method for what value we choose
8598 to set here. */
8601 c_flt_eval_method (bool maybe_c11_only_p)
8603 if (maybe_c11_only_p
8604 && flag_permitted_flt_eval_methods
8605 == PERMITTED_FLT_EVAL_METHODS_C11)
8606 return c_c11_flt_eval_method ();
8607 else
8608 return c_ts18661_flt_eval_method ();
8611 /* An enum for get_missing_token_insertion_kind for describing the best
8612 place to insert a missing token, if there is one. */
8614 enum missing_token_insertion_kind
8616 MTIK_IMPOSSIBLE,
8617 MTIK_INSERT_BEFORE_NEXT,
8618 MTIK_INSERT_AFTER_PREV
8621 /* Given a missing token of TYPE, determine if it is reasonable to
8622 emit a fix-it hint suggesting the insertion of the token, and,
8623 if so, where the token should be inserted relative to other tokens.
8625 It only makes sense to do this for values of TYPE that are symbols.
8627 Some symbols should go before the next token, e.g. in:
8628 if flag)
8629 we want to insert the missing '(' immediately before "flag",
8630 giving:
8631 if (flag)
8632 rather than:
8633 if( flag)
8634 These use MTIK_INSERT_BEFORE_NEXT.
8636 Other symbols should go after the previous token, e.g. in:
8637 if (flag
8638 do_something ();
8639 we want to insert the missing ')' immediately after the "flag",
8640 giving:
8641 if (flag)
8642 do_something ();
8643 rather than:
8644 if (flag
8645 )do_something ();
8646 These use MTIK_INSERT_AFTER_PREV. */
8648 static enum missing_token_insertion_kind
8649 get_missing_token_insertion_kind (enum cpp_ttype type)
8651 switch (type)
8653 /* Insert missing "opening" brackets immediately
8654 before the next token. */
8655 case CPP_OPEN_SQUARE:
8656 case CPP_OPEN_PAREN:
8657 return MTIK_INSERT_BEFORE_NEXT;
8659 /* Insert other missing symbols immediately after
8660 the previous token. */
8661 case CPP_CLOSE_PAREN:
8662 case CPP_CLOSE_SQUARE:
8663 case CPP_SEMICOLON:
8664 case CPP_COMMA:
8665 case CPP_COLON:
8666 return MTIK_INSERT_AFTER_PREV;
8668 /* Other kinds of token don't get fix-it hints. */
8669 default:
8670 return MTIK_IMPOSSIBLE;
8674 /* Given RICHLOC, a location for a diagnostic describing a missing token
8675 of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
8676 insertion of the token.
8678 The location of the attempted fix-it hint depends on TOKEN_TYPE:
8679 it will either be:
8680 (a) immediately after PREV_TOKEN_LOC, or
8682 (b) immediately before the primary location within RICHLOC (taken to
8683 be that of the token following where the token was expected).
8685 If we manage to add a fix-it hint, then the location of the
8686 fix-it hint is likely to be more useful as the primary location
8687 of the diagnostic than that of the following token, so we swap
8688 these locations.
8690 For example, given this bogus code:
8691 123456789012345678901234567890
8692 1 | int missing_semicolon (void)
8693 2 | {
8694 3 | return 42
8695 4 | }
8697 we will emit:
8699 "expected ';' before '}'"
8701 RICHLOC's primary location is at the closing brace, so before "swapping"
8702 we would emit the error at line 4 column 1:
8704 123456789012345678901234567890
8705 3 | return 42 |< fix-it hint emitted for this line
8706 | ; |
8707 4 | } |< "expected ';' before '}'" emitted at this line
8708 | ^ |
8710 It's more useful for the location of the diagnostic to be at the
8711 fix-it hint, so we swap the locations, so the primary location
8712 is at the fix-it hint, with the old primary location inserted
8713 as a secondary location, giving this, with the error at line 3
8714 column 12:
8716 123456789012345678901234567890
8717 3 | return 42 |< "expected ';' before '}'" emitted at this line,
8718 | ^ | with fix-it hint
8719 4 | ; |
8720 | } |< secondary range emitted here
8721 | ~ |. */
8723 void
8724 maybe_suggest_missing_token_insertion (rich_location *richloc,
8725 enum cpp_ttype token_type,
8726 location_t prev_token_loc)
8728 gcc_assert (richloc);
8730 enum missing_token_insertion_kind mtik
8731 = get_missing_token_insertion_kind (token_type);
8733 switch (mtik)
8735 default:
8736 gcc_unreachable ();
8737 break;
8739 case MTIK_IMPOSSIBLE:
8740 return;
8742 case MTIK_INSERT_BEFORE_NEXT:
8743 /* Attempt to add the fix-it hint before the primary location
8744 of RICHLOC. */
8745 richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
8746 break;
8748 case MTIK_INSERT_AFTER_PREV:
8749 /* Attempt to add the fix-it hint after PREV_TOKEN_LOC. */
8750 richloc->add_fixit_insert_after (prev_token_loc,
8751 cpp_type2name (token_type, 0));
8752 break;
8755 /* If we were successful, use the fix-it hint's location as the
8756 primary location within RICHLOC, adding the old primary location
8757 back as a secondary location. */
8758 if (!richloc->seen_impossible_fixit_p ())
8760 fixit_hint *hint = richloc->get_last_fixit_hint ();
8761 location_t hint_loc = hint->get_start_loc ();
8762 location_t old_loc = richloc->get_loc ();
8764 richloc->set_range (0, hint_loc, SHOW_RANGE_WITH_CARET);
8765 richloc->add_range (old_loc);
8769 #if CHECKING_P
8771 namespace selftest {
8773 /* Verify that fold_for_warn on error_mark_node is safe. */
8775 static void
8776 test_fold_for_warn ()
8778 ASSERT_EQ (error_mark_node, fold_for_warn (error_mark_node));
8781 /* Run all of the selftests within this file. */
8783 static void
8784 c_common_c_tests ()
8786 test_fold_for_warn ();
8789 /* Run all of the tests within c-family. */
8791 void
8792 c_family_tests (void)
8794 c_common_c_tests ();
8795 c_format_c_tests ();
8796 c_indentation_c_tests ();
8797 c_pretty_print_c_tests ();
8798 c_spellcheck_cc_tests ();
8801 } // namespace selftest
8803 #endif /* #if CHECKING_P */
8805 /* Attempt to locate a suitable location within FILE for a
8806 #include directive to be inserted before.
8807 LOC is the location of the relevant diagnostic.
8809 Attempt to return the location within FILE immediately
8810 after the last #include within that file, or the start of
8811 that file if it has no #include directives.
8813 Return UNKNOWN_LOCATION if no suitable location is found,
8814 or if an error occurs. */
8816 static location_t
8817 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
8819 /* Locate the last ordinary map within FILE that ended with a #include. */
8820 const line_map_ordinary *last_include_ord_map = NULL;
8822 /* ...and the next ordinary map within FILE after that one. */
8823 const line_map_ordinary *last_ord_map_after_include = NULL;
8825 /* ...and the first ordinary map within FILE. */
8826 const line_map_ordinary *first_ord_map_in_file = NULL;
8828 /* Get ordinary map containing LOC (or its expansion). */
8829 const line_map_ordinary *ord_map_for_loc = NULL;
8830 linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
8831 &ord_map_for_loc);
8832 gcc_assert (ord_map_for_loc);
8834 for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
8836 const line_map_ordinary *ord_map
8837 = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
8839 if (const line_map_ordinary *from
8840 = linemap_included_from_linemap (line_table, ord_map))
8841 /* We cannot use pointer equality, because with preprocessed
8842 input all filename strings are unique. */
8843 if (0 == strcmp (from->to_file, file))
8845 last_include_ord_map = from;
8846 last_ord_map_after_include = NULL;
8849 /* Likewise, use strcmp, and reject any line-zero introductory
8850 map. */
8851 if (ord_map->to_line && 0 == strcmp (ord_map->to_file, file))
8853 if (!first_ord_map_in_file)
8854 first_ord_map_in_file = ord_map;
8855 if (last_include_ord_map && !last_ord_map_after_include)
8856 last_ord_map_after_include = ord_map;
8859 /* Stop searching when reaching the ord_map containing LOC,
8860 as it makes no sense to provide fix-it hints that appear
8861 after the diagnostic in question. */
8862 if (ord_map == ord_map_for_loc)
8863 break;
8866 /* Determine where to insert the #include. */
8867 const line_map_ordinary *ord_map_for_insertion;
8869 /* We want the next ordmap in the file after the last one that's a
8870 #include, but failing that, the start of the file. */
8871 if (last_ord_map_after_include)
8872 ord_map_for_insertion = last_ord_map_after_include;
8873 else
8874 ord_map_for_insertion = first_ord_map_in_file;
8876 if (!ord_map_for_insertion)
8877 return UNKNOWN_LOCATION;
8879 /* The "start_location" is column 0, meaning "the whole line".
8880 rich_location and edit_context can't cope with this, so use
8881 column 1 instead. */
8882 location_t col_0 = ord_map_for_insertion->start_location;
8883 return linemap_position_for_loc_and_offset (line_table, col_0, 1);
8886 /* A map from filenames to sets of headers added to them, for
8887 ensuring idempotency within maybe_add_include_fixit. */
8889 /* The values within the map. We need string comparison as there's
8890 no guarantee that two different diagnostics that are recommending
8891 adding e.g. "<stdio.h>" are using the same buffer. */
8893 typedef hash_set <const char *, false, nofree_string_hash> per_file_includes_t;
8895 /* The map itself. We don't need string comparison for the filename keys,
8896 as they come from libcpp. */
8898 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
8899 static added_includes_t *added_includes;
8901 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
8902 in a suitable location within the file of RICHLOC's primary
8903 location.
8905 This function is idempotent: a header will be added at most once to
8906 any given file.
8908 If OVERRIDE_LOCATION is true, then if a fix-it is added and will be
8909 printed, then RICHLOC's primary location will be replaced by that of
8910 the fix-it hint (for use by "inform" notes where the location of the
8911 issue has already been reported). */
8913 void
8914 maybe_add_include_fixit (rich_location *richloc, const char *header,
8915 bool override_location)
8917 location_t loc = richloc->get_loc ();
8918 const char *file = LOCATION_FILE (loc);
8919 if (!file)
8920 return;
8922 /* Idempotency: don't add the same header more than once to a given file. */
8923 if (!added_includes)
8924 added_includes = new added_includes_t ();
8925 per_file_includes_t *&set = added_includes->get_or_insert (file);
8926 if (set)
8927 if (set->contains (header))
8928 /* ...then we've already added HEADER to that file. */
8929 return;
8930 if (!set)
8931 set = new per_file_includes_t ();
8932 set->add (header);
8934 /* Attempt to locate a suitable place for the new directive. */
8935 location_t include_insert_loc
8936 = try_to_locate_new_include_insertion_point (file, loc);
8937 if (include_insert_loc == UNKNOWN_LOCATION)
8938 return;
8940 char *text = xasprintf ("#include %s\n", header);
8941 richloc->add_fixit_insert_before (include_insert_loc, text);
8942 free (text);
8944 if (override_location && global_dc->show_caret)
8946 /* Replace the primary location with that of the insertion point for the
8947 fix-it hint.
8949 We use SHOW_LINES_WITHOUT_RANGE so that we don't meaningless print a
8950 caret for the insertion point (or colorize it).
8952 Hence we print e.g.:
8954 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
8955 73 | # include <debug/vector>
8956 +++ |+#include <vector>
8957 74 | #endif
8959 rather than:
8961 ../x86_64-pc-linux-gnu/libstdc++-v3/include/vector:74:1: note: msg 2
8962 73 | # include <debug/vector>
8963 +++ |+#include <vector>
8964 74 | #endif
8967 avoiding the caret on the first column of line 74. */
8968 richloc->set_range (0, include_insert_loc, SHOW_LINES_WITHOUT_RANGE);
8972 /* Attempt to convert a braced array initializer list CTOR for array
8973 TYPE into a STRING_CST for convenience and efficiency. Return
8974 the converted string on success or the original ctor on failure. */
8976 static tree
8977 braced_list_to_string (tree type, tree ctor, bool member)
8979 /* Ignore non-members with unknown size like arrays with unspecified
8980 bound. */
8981 tree typesize = TYPE_SIZE_UNIT (type);
8982 if (!member && !tree_fits_uhwi_p (typesize))
8983 return ctor;
8985 /* If the array has an explicit bound, use it to constrain the size
8986 of the string. If it doesn't, be sure to create a string that's
8987 as long as implied by the index of the last zero specified via
8988 a designator, as in:
8989 const char a[] = { [7] = 0 }; */
8990 unsigned HOST_WIDE_INT maxelts;
8991 if (typesize)
8993 maxelts = tree_to_uhwi (typesize);
8994 maxelts /= tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type)));
8996 else
8997 maxelts = HOST_WIDE_INT_M1U;
8999 /* Avoid converting initializers for zero-length arrays (but do
9000 create them for flexible array members). */
9001 if (!maxelts)
9002 return ctor;
9004 unsigned HOST_WIDE_INT nelts = CONSTRUCTOR_NELTS (ctor);
9006 auto_vec<char> str;
9007 str.reserve (nelts + 1);
9009 unsigned HOST_WIDE_INT i;
9010 tree index, value;
9012 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, index, value)
9014 unsigned HOST_WIDE_INT idx = i;
9015 if (index)
9017 if (!tree_fits_uhwi_p (index))
9018 return ctor;
9019 idx = tree_to_uhwi (index);
9022 /* auto_vec is limited to UINT_MAX elements. */
9023 if (idx > UINT_MAX)
9024 return ctor;
9026 /* Avoid non-constant initializers. */
9027 if (!tree_fits_shwi_p (value))
9028 return ctor;
9030 /* Skip over embedded nuls except the last one (initializer
9031 elements are in ascending order of indices). */
9032 HOST_WIDE_INT val = tree_to_shwi (value);
9033 if (!val && i + 1 < nelts)
9034 continue;
9036 if (idx < str.length())
9037 return ctor;
9039 /* Bail if the CTOR has a block of more than 256 embedded nuls
9040 due to implicitly initialized elements. */
9041 unsigned nchars = (idx - str.length ()) + 1;
9042 if (nchars > 256)
9043 return ctor;
9045 if (nchars > 1)
9047 str.reserve (idx);
9048 str.quick_grow_cleared (idx);
9051 if (idx >= maxelts)
9052 return ctor;
9054 str.safe_insert (idx, val);
9057 /* Append a nul string termination. */
9058 if (maxelts != HOST_WIDE_INT_M1U && str.length () < maxelts)
9059 str.safe_push (0);
9061 /* Build a STRING_CST with the same type as the array. */
9062 tree res = build_string (str.length (), str.begin ());
9063 TREE_TYPE (res) = type;
9064 return res;
9067 /* Implementation of the two-argument braced_lists_to_string withe
9068 the same arguments plus MEMBER which is set for struct members
9069 to allow initializers for flexible member arrays. */
9071 static tree
9072 braced_lists_to_strings (tree type, tree ctor, bool member)
9074 if (TREE_CODE (ctor) != CONSTRUCTOR)
9075 return ctor;
9077 tree_code code = TREE_CODE (type);
9079 tree ttp;
9080 if (code == ARRAY_TYPE)
9081 ttp = TREE_TYPE (type);
9082 else if (code == RECORD_TYPE)
9084 ttp = TREE_TYPE (ctor);
9085 if (TREE_CODE (ttp) == ARRAY_TYPE)
9087 type = ttp;
9088 ttp = TREE_TYPE (ttp);
9091 else
9092 return ctor;
9094 if ((TREE_CODE (ttp) == ARRAY_TYPE || TREE_CODE (ttp) == INTEGER_TYPE)
9095 && TYPE_STRING_FLAG (ttp))
9096 return braced_list_to_string (type, ctor, member);
9098 code = TREE_CODE (ttp);
9099 if (code == ARRAY_TYPE || RECORD_OR_UNION_TYPE_P (ttp))
9101 bool rec = RECORD_OR_UNION_TYPE_P (ttp);
9103 /* Handle array of arrays or struct member initializers. */
9104 tree val;
9105 unsigned HOST_WIDE_INT idx;
9106 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, val)
9108 val = braced_lists_to_strings (ttp, val, rec);
9109 CONSTRUCTOR_ELT (ctor, idx)->value = val;
9113 return ctor;
9116 /* Attempt to convert a CTOR containing braced array initializer lists
9117 for array TYPE into one containing STRING_CSTs, for convenience and
9118 efficiency. Recurse for arrays of arrays and member initializers.
9119 Return the converted CTOR or STRING_CST on success or the original
9120 CTOR otherwise. */
9122 tree
9123 braced_lists_to_strings (tree type, tree ctor)
9125 return braced_lists_to_strings (type, ctor, false);
9129 /* Emit debug for functions before finalizing early debug. */
9131 void
9132 c_common_finalize_early_debug (void)
9134 /* Emit early debug for reachable functions, and by consequence,
9135 locally scoped symbols. Also emit debug for extern declared
9136 functions that are still reachable at this point. */
9137 struct cgraph_node *cnode;
9138 FOR_EACH_FUNCTION (cnode)
9139 if (!cnode->alias && !cnode->thunk
9140 && (cnode->has_gimple_body_p () || !DECL_IS_BUILTIN (cnode->decl)))
9141 (*debug_hooks->early_global_decl) (cnode->decl);
9144 #include "gt-c-family-c-common.h"